3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
8 use MediaWiki\MediaWikiServices
;
11 * Base code for files.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
29 * @ingroup FileAbstraction
32 // @phan-file-suppress PhanTypeMissingReturn false positives
34 * Implements some public methods and some protected utility functions which
35 * are required by multiple child classes. Contains stub functionality for
36 * unimplemented public methods.
38 * Stub functions which should be overridden are marked with STUB. Some more
39 * concrete functions are also typically overridden by child classes.
41 * Note that only the repo object knows what its file class is called. You should
42 * never name a file class explictly outside of the repo class. Instead use the
43 * repo's factory functions to generate file objects, for example:
45 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
47 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
50 * @ingroup FileAbstraction
52 abstract class File
implements IDBAccessObject
{
53 // Bitfield values akin to the Revision deletion constants
54 const DELETED_FILE
= 1;
55 const DELETED_COMMENT
= 2;
56 const DELETED_USER
= 4;
57 const DELETED_RESTRICTED
= 8;
59 /** Force rendering in the current process */
62 * Force rendering even if thumbnail already exist and using RENDER_NOW
63 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
65 const RENDER_FORCE
= 2;
67 const DELETE_SOURCE
= 1;
69 // Audience options for File::getDescription()
71 const FOR_THIS_USER
= 2;
74 // Options for File::thumbName()
75 const THUMB_FULL_NAME
= 1;
78 * Some member variables can be lazy-initialised using __get(). The
79 * initialisation function for these variables is always a function named
80 * like getVar(), where Var is the variable name with upper-case first
83 * The following variables are initialised in this way in this base class:
84 * name, extension, handler, path, canRender, isSafeFile,
85 * transformScript, hashPath, pageCount, url
87 * Code within this class should generally use the accessor function
88 * directly, since __get() isn't re-entrant and therefore causes bugs that
89 * depend on initialisation order.
93 * The following member variables are not lazy-initialised
96 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
99 /** @var Title|string|bool */
102 /** @var string Text of last error */
103 protected $lastError;
105 /** @var string Main part of the title, with underscores (Title::getDBkey) */
106 protected $redirected;
109 protected $redirectedTitle;
111 /** @var FSFile|bool False if undefined */
114 /** @var MediaHandler */
117 /** @var string The URL corresponding to one of the four basic zones */
120 /** @var string File extension */
121 protected $extension;
123 /** @var string The name of a file from its title object */
126 /** @var string The storage path corresponding to one of the zones */
129 /** @var string Relative path including trailing slash */
132 /** @var string|false Number of pages of a multipage document, or false for
133 * documents which aren't multipage documents
135 protected $pageCount;
137 /** @var string URL of transformscript (for example thumb.php) */
138 protected $transformScript;
141 protected $redirectTitle;
143 /** @var bool Whether the output of transform() for this file is likely to be valid. */
144 protected $canRender;
146 /** @var bool Whether this media file is in a format that is unlikely to
147 * contain viruses or malicious content
149 protected $isSafeFile;
151 /** @var string Required Repository class type */
152 protected $repoClass = FileRepo
::class;
154 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
155 protected $tmpBucketedThumbCache = [];
158 * Call this constructor from child classes.
160 * Both $title and $repo are optional, though some functions
161 * may return false or throw exceptions if they are not set.
162 * Most subclasses will want to call assertRepoDefined() here.
164 * @param Title|string|bool $title
165 * @param FileRepo|bool $repo
167 function __construct( $title, $repo ) {
168 // Some subclasses do not use $title, but set name/title some other way
169 if ( $title !== false ) {
170 $title = self
::normalizeTitle( $title, 'exception' );
172 $this->title
= $title;
177 * Given a string or Title object return either a
178 * valid Title object with namespace NS_FILE or null
180 * @param Title|string $title
181 * @param string|bool $exception Use 'exception' to throw an error on bad titles
182 * @throws MWException
185 static function normalizeTitle( $title, $exception = false ) {
187 if ( $ret instanceof Title
) {
188 # Normalize NS_MEDIA -> NS_FILE
189 if ( $ret->getNamespace() == NS_MEDIA
) {
190 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
191 # Sanity check the title namespace
192 } elseif ( $ret->getNamespace() !== NS_FILE
) {
196 # Convert strings to Title objects
197 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
199 if ( !$ret && $exception !== false ) {
200 throw new MWException( "`$title` is not a valid file title." );
206 function __get( $name ) {
207 $function = [ $this, 'get' . ucfirst( $name ) ];
208 if ( !is_callable( $function ) ) {
211 $this->$name = $function();
218 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
219 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
220 * Keep in sync with mw.Title.normalizeExtension() in JS.
222 * @param string $extension File extension (without the leading dot)
223 * @return string File extension in canonical form
225 static function normalizeExtension( $extension ) {
226 $lower = strtolower( $extension );
233 if ( isset( $squish[$lower] ) ) {
234 return $squish[$lower];
235 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
243 * Checks if file extensions are compatible
245 * @param File $old Old file
246 * @param string $new New name
250 static function checkExtensionCompatibility( File
$old, $new ) {
251 $oldMime = $old->getMimeType();
252 $n = strrpos( $new, '.' );
253 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
254 $mimeMagic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
256 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
260 * Upgrade the database row if there is one
261 * Called by ImagePage
264 function upgradeRow() {
268 * Split an internet media type into its two components; if not
269 * a two-part name, set the minor type to 'unknown'.
271 * @param string $mime "text/html" etc
272 * @return string[] ("text", "html") etc
274 public static function splitMime( $mime ) {
275 if ( strpos( $mime, '/' ) !== false ) {
276 return explode( '/', $mime, 2 );
278 return [ $mime, 'unknown' ];
283 * Callback for usort() to do file sorts by name
287 * @return int Result of name comparison
289 public static function compare( File
$a, File
$b ) {
290 return strcmp( $a->getName(), $b->getName() );
294 * Return the name of this file
298 public function getName() {
299 if ( !isset( $this->name
) ) {
300 $this->assertRepoDefined();
301 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
308 * Get the file extension, e.g. "svg"
312 function getExtension() {
313 if ( !isset( $this->extension
) ) {
314 $n = strrpos( $this->getName(), '.' );
315 $this->extension
= self
::normalizeExtension(
316 $n ?
substr( $this->getName(), $n +
1 ) : '' );
319 return $this->extension
;
323 * Return the associated title object
327 public function getTitle() {
332 * Return the title used to find this file
336 public function getOriginalTitle() {
337 if ( $this->redirected
) {
338 return $this->getRedirectedTitle();
345 * Return the URL of the file
349 public function getUrl() {
350 if ( !isset( $this->url
) ) {
351 $this->assertRepoDefined();
352 $ext = $this->getExtension();
353 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
360 * Get short description URL for a files based on the page ID
362 * @return string|null
365 public function getDescriptionShortUrl() {
370 * Return a fully-qualified URL to the file.
371 * Upload URL paths _may or may not_ be fully qualified, so
372 * we check. Local paths are assumed to belong on $wgServer.
376 public function getFullUrl() {
377 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
383 public function getCanonicalUrl() {
384 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
390 function getViewURL() {
391 if ( $this->mustRender() ) {
392 if ( $this->canRender() ) {
393 return $this->createThumb( $this->getWidth() );
395 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
396 ' (' . $this->getMimeType() . "), but can't!\n" );
398 return $this->getUrl(); # hm... return NULL?
401 return $this->getUrl();
406 * Return the storage path to the file. Note that this does
407 * not mean that a file actually exists under that location.
409 * This path depends on whether directory hashing is active or not,
410 * i.e. whether the files are all found in the same directory,
411 * or in hashed paths like /images/3/3c.
413 * Most callers don't check the return value, but ForeignAPIFile::getPath
416 * @return string|bool ForeignAPIFile::getPath can return false
418 public function getPath() {
419 if ( !isset( $this->path
) ) {
420 $this->assertRepoDefined();
421 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
428 * Get an FS copy or original of this file and return the path.
429 * Returns false on failure. Callers must not alter the file.
430 * Temporary files are cleared automatically.
432 * @return string|bool False on failure
434 public function getLocalRefPath() {
435 $this->assertRepoDefined();
436 if ( !isset( $this->fsFile
) ) {
437 $starttime = microtime( true );
438 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
440 $statTiming = microtime( true ) - $starttime;
441 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
442 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
444 if ( !$this->fsFile
) {
445 $this->fsFile
= false; // null => false; cache negative hits
449 return ( $this->fsFile
)
450 ?
$this->fsFile
->getPath()
455 * Return the width of the image. Returns false if the width is unknown
459 * Overridden by LocalFile, UnregisteredLocalFile
464 public function getWidth( $page = 1 ) {
469 * Return the height of the image. Returns false if the height is unknown
473 * Overridden by LocalFile, UnregisteredLocalFile
476 * @return bool|int False on failure
478 public function getHeight( $page = 1 ) {
483 * Return the smallest bucket from $wgThumbnailBuckets which is at least
484 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
485 * will always be bigger than $desiredWidth.
487 * @param int $desiredWidth
491 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
492 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
494 $imageWidth = $this->getWidth( $page );
496 if ( $imageWidth === false ) {
500 if ( $desiredWidth > $imageWidth ) {
504 if ( !$wgThumbnailBuckets ) {
508 $sortedBuckets = $wgThumbnailBuckets;
510 sort( $sortedBuckets );
512 foreach ( $sortedBuckets as $bucket ) {
513 if ( $bucket >= $imageWidth ) {
517 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
522 // Image is bigger than any available bucket
527 * Returns ID or name of user who uploaded the file
530 * @param string $type 'text' or 'id'
533 public function getUser( $type = 'text' ) {
538 * Get the duration of a media file in seconds
542 public function getLength() {
543 $handler = $this->getHandler();
545 return $handler->getLength( $this );
552 * Return true if the file is vectorized
556 public function isVectorized() {
557 $handler = $this->getHandler();
559 return $handler->isVectorized( $this );
566 * Gives a (possibly empty) list of languages to render
569 * If the file doesn't have translations, or if the file
570 * format does not support that sort of thing, returns
576 public function getAvailableLanguages() {
577 $handler = $this->getHandler();
579 return $handler->getAvailableLanguages( $this );
586 * Get the language code from the available languages for this file that matches the language
587 * requested by the user
589 * @param string $userPreferredLanguage
590 * @return string|null
592 public function getMatchedLanguage( $userPreferredLanguage ) {
593 $handler = $this->getHandler();
595 return $handler->getMatchedLanguage(
596 $userPreferredLanguage,
597 $handler->getAvailableLanguages( $this )
605 * In files that support multiple language, what is the default language
606 * to use if none specified.
608 * @return string|null Lang code, or null if filetype doesn't support multiple languages.
611 public function getDefaultRenderLanguage() {
612 $handler = $this->getHandler();
614 return $handler->getDefaultRenderLanguage( $this );
621 * Will the thumbnail be animated if one would expect it to be.
623 * Currently used to add a warning to the image description page
625 * @return bool False if the main image is both animated
626 * and the thumbnail is not. In all other cases must return
627 * true. If image is not renderable whatsoever, should
630 public function canAnimateThumbIfAppropriate() {
631 $handler = $this->getHandler();
633 // We cannot handle image whatsoever, thus
634 // one would not expect it to be animated
639 return !$this->allowInlineDisplay()
640 // Image is not animated, so one would
641 // not expect thumb to be
642 ||
!$handler->isAnimatedImage( $this )
643 // Image is animated, but thumbnail isn't.
644 // This is unexpected to the user.
645 ||
$handler->canAnimateThumbnail( $this );
649 * Get handler-specific metadata
650 * Overridden by LocalFile, UnregisteredLocalFile
654 public function getMetadata() {
659 * Like getMetadata but returns a handler independent array of common values.
660 * @see MediaHandler::getCommonMetaArray()
661 * @return array|bool Array or false if not supported
664 public function getCommonMetaArray() {
665 $handler = $this->getHandler();
671 return $handler->getCommonMetaArray( $this );
675 * get versioned metadata
677 * @param array|string $metadata Array or string of (serialized) metadata
678 * @param int $version Version number.
679 * @return array Array containing metadata, or what was passed to it on fail
680 * (unserializing if not array)
682 public function convertMetadataVersion( $metadata, $version ) {
683 $handler = $this->getHandler();
684 if ( !is_array( $metadata ) ) {
685 // Just to make the return type consistent
686 $metadata = unserialize( $metadata );
689 return $handler->convertMetadataVersion( $metadata, $version );
696 * Return the bit depth of the file
697 * Overridden by LocalFile
701 public function getBitDepth() {
706 * Return the size of the image file, in bytes
707 * Overridden by LocalFile, UnregisteredLocalFile
711 public function getSize() {
716 * Returns the MIME type of the file.
717 * Overridden by LocalFile, UnregisteredLocalFile
722 function getMimeType() {
723 return 'unknown/unknown';
727 * Return the type of the media in the file.
728 * Use the value returned by this function with the MEDIATYPE_xxx constants.
729 * Overridden by LocalFile,
733 function getMediaType() {
734 return MEDIATYPE_UNKNOWN
;
738 * Checks if the output of transform() for this file is likely
739 * to be valid. If this is false, various user elements will
740 * display a placeholder instead.
742 * Currently, this checks if the file is an image format
743 * that can be converted to a format
744 * supported by all browsers (namely GIF, PNG and JPEG),
745 * or if it is an SVG image and SVG conversion is enabled.
749 function canRender() {
750 if ( !isset( $this->canRender
) ) {
751 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
754 return $this->canRender
;
758 * Accessor for __get()
761 protected function getCanRender() {
762 return $this->canRender();
766 * Return true if the file is of a type that can't be directly
767 * rendered by typical browsers and needs to be re-rasterized.
769 * This returns true for everything but the bitmap types
770 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
771 * also return true for any non-image formats.
775 function mustRender() {
776 return $this->getHandler() && $this->handler
->mustRender( $this );
780 * Alias for canRender()
784 function allowInlineDisplay() {
785 return $this->canRender();
789 * Determines if this media file is in a format that is unlikely to
790 * contain viruses or malicious content. It uses the global
791 * $wgTrustedMediaFormats list to determine if the file is safe.
793 * This is used to show a warning on the description page of non-safe files.
794 * It may also be used to disallow direct [[media:...]] links to such files.
796 * Note that this function will always return true if allowInlineDisplay()
797 * or isTrustedFile() is true for this file.
801 function isSafeFile() {
802 if ( !isset( $this->isSafeFile
) ) {
803 $this->isSafeFile
= $this->getIsSafeFileUncached();
806 return $this->isSafeFile
;
810 * Accessor for __get()
814 protected function getIsSafeFile() {
815 return $this->isSafeFile();
823 protected function getIsSafeFileUncached() {
824 global $wgTrustedMediaFormats;
826 if ( $this->allowInlineDisplay() ) {
829 if ( $this->isTrustedFile() ) {
833 $type = $this->getMediaType();
834 $mime = $this->getMimeType();
835 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
837 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
838 return false; # unknown type, not trusted
840 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
844 if ( $mime === "unknown/unknown" ) {
845 return false; # unknown type, not trusted
847 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
855 * Returns true if the file is flagged as trusted. Files flagged that way
856 * can be linked to directly, even if that is not allowed for this type of
859 * This is a dummy function right now and always returns false. It could be
860 * implemented to extract a flag from the database. The trusted flag could be
861 * set on upload, if the user has sufficient privileges, to bypass script-
862 * and html-filters. It may even be coupled with cryptographics signatures
867 function isTrustedFile() {
868 # this could be implemented to check a flag in the database,
869 # look for signatures, etc
874 * Load any lazy-loaded file object fields from source
876 * This is only useful when setting $flags
878 * Overridden by LocalFile to actually query the DB
880 * @param int $flags Bitfield of File::READ_* constants
882 public function load( $flags = 0 ) {
886 * Returns true if file exists in the repository.
888 * Overridden by LocalFile to avoid unnecessary stat calls.
890 * @return bool Whether file exists in the repository.
892 public function exists() {
893 return $this->getPath() && $this->repo
->fileExists( $this->path
);
897 * Returns true if file exists in the repository and can be included in a page.
898 * It would be unsafe to include private images, making public thumbnails inadvertently
900 * @return bool Whether file exists in the repository and is includable.
902 public function isVisible() {
903 return $this->exists();
909 function getTransformScript() {
910 if ( !isset( $this->transformScript
) ) {
911 $this->transformScript
= false;
913 $script = $this->repo
->getThumbScriptUrl();
915 $this->transformScript
= wfAppendQuery( $script, [ 'f' => $this->getName() ] );
920 return $this->transformScript
;
924 * Get a ThumbnailImage which is the same size as the source
926 * @param array $handlerParams
928 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
930 function getUnscaledThumb( $handlerParams = [] ) {
931 $hp =& $handlerParams;
932 $page = $hp['page'] ??
false;
933 $width = $this->getWidth( $page );
935 return $this->iconThumb();
937 $hp['width'] = $width;
938 // be sure to ignore any height specification as well (T64258)
939 unset( $hp['height'] );
941 return $this->transform( $hp );
945 * Return the file name of a thumbnail with the specified parameters.
946 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
947 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
949 * @param array $params Handler-specific parameters
950 * @param int $flags Bitfield that supports THUMB_* constants
951 * @return string|null
953 public function thumbName( $params, $flags = 0 ) {
954 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
955 ?
$this->repo
->nameForThumb( $this->getName() )
958 return $this->generateThumbName( $name, $params );
962 * Generate a thumbnail file name from a name and specified parameters
964 * @param string $name
965 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
966 * @return string|null
968 public function generateThumbName( $name, $params ) {
969 if ( !$this->getHandler() ) {
972 $extension = $this->getExtension();
973 list( $thumbExt, ) = $this->getHandler()->getThumbType(
974 $extension, $this->getMimeType(), $params );
975 $thumbName = $this->getHandler()->makeParamString( $params );
977 if ( $this->repo
->supportsSha1URLs() ) {
978 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
980 $thumbName .= '-' . $name;
982 if ( $thumbExt != $extension ) {
983 $thumbName .= ".$thumbExt";
991 * Create a thumbnail of the image having the specified width/height.
992 * The thumbnail will not be created if the width is larger than the
993 * image's width. Let the browser do the scaling in this case.
994 * The thumbnail is stored on disk and is only computed if the thumbnail
995 * file does not exist OR if it is older than the image.
998 * Keeps aspect ratio of original image. If both width and height are
999 * specified, the generated image will be no bigger than width x height,
1000 * and will also have correct aspect ratio.
1002 * @param int $width Maximum width of the generated thumbnail
1003 * @param int $height Maximum height of the image (optional)
1007 public function createThumb( $width, $height = -1 ) {
1008 $params = [ 'width' => $width ];
1009 if ( $height != -1 ) {
1010 $params['height'] = $height;
1012 $thumb = $this->transform( $params );
1013 if ( !$thumb ||
$thumb->isError() ) {
1017 return $thumb->getUrl();
1021 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
1023 * @param string $thumbPath Thumbnail storage path
1024 * @param string $thumbUrl Thumbnail URL
1025 * @param array $params
1027 * @return MediaTransformOutput
1029 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1030 global $wgIgnoreImageErrors;
1032 $handler = $this->getHandler();
1033 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1034 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1036 return new MediaTransformError( 'thumbnail_error',
1037 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1042 * Transform a media file
1044 * @param array $params An associative array of handler-specific parameters.
1045 * Typical keys are width, height and page.
1046 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1047 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
1049 function transform( $params, $flags = 0 ) {
1050 global $wgThumbnailEpoch;
1053 if ( !$this->canRender() ) {
1054 $thumb = $this->iconThumb();
1055 break; // not a bitmap or renderable image, don't try
1058 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1059 $descriptionUrl = $this->getDescriptionUrl();
1060 if ( $descriptionUrl ) {
1061 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1064 $handler = $this->getHandler();
1065 $script = $this->getTransformScript();
1066 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1067 // Use a script to transform on client request, if possible
1068 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1074 $normalisedParams = $params;
1075 $handler->normaliseParams( $this, $normalisedParams );
1077 $thumbName = $this->thumbName( $normalisedParams );
1078 $thumbUrl = $this->getThumbUrl( $thumbName );
1079 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1081 if ( $this->repo
) {
1082 // Defer rendering if a 404 handler is set up...
1083 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1084 // XXX: Pass in the storage path even though we are not rendering anything
1085 // and the path is supposed to be an FS path. This is due to getScalerType()
1086 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1087 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1090 // Check if an up-to-date thumbnail already exists...
1091 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1092 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1093 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1094 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1095 // XXX: Pass in the storage path even though we are not rendering anything
1096 // and the path is supposed to be an FS path. This is due to getScalerType()
1097 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1098 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1099 $thumb->setStoragePath( $thumbPath );
1102 } elseif ( $flags & self
::RENDER_FORCE
) {
1103 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1106 // If the backend is ready-only, don't keep generating thumbnails
1107 // only to return transformation errors, just return the error now.
1108 if ( $this->repo
->getReadOnlyReason() !== false ) {
1109 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1114 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1117 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1119 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1123 return is_object( $thumb ) ?
$thumb : false;
1127 * Generates a thumbnail according to the given parameters and saves it to storage
1128 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1129 * @param array $transformParams
1131 * @return bool|MediaTransformOutput
1133 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1134 global $wgIgnoreImageErrors;
1136 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1138 $handler = $this->getHandler();
1140 $normalisedParams = $transformParams;
1141 $handler->normaliseParams( $this, $normalisedParams );
1143 $thumbName = $this->thumbName( $normalisedParams );
1144 $thumbUrl = $this->getThumbUrl( $thumbName );
1145 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1147 $tmpThumbPath = $tmpFile->getPath();
1149 if ( $handler->supportsBucketing() ) {
1150 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1153 $starttime = microtime( true );
1155 // Actually render the thumbnail...
1156 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1157 $tmpFile->bind( $thumb ); // keep alive with $thumb
1159 $statTiming = microtime( true ) - $starttime;
1160 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1162 if ( !$thumb ) { // bad params?
1164 } elseif ( $thumb->isError() ) { // transform error
1165 /** @var MediaTransformError $thumb */
1166 $this->lastError
= $thumb->toText();
1167 // Ignore errors if requested
1168 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1169 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1171 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1172 // Copy the thumbnail from the file system into storage...
1174 $starttime = microtime( true );
1176 $disposition = $this->getThumbDisposition( $thumbName );
1177 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1178 if ( $status->isOK() ) {
1179 $thumb->setStoragePath( $thumbPath );
1181 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1184 $statTiming = microtime( true ) - $starttime;
1185 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1187 // Give extensions a chance to do something with this thumbnail...
1188 Hooks
::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
1195 * Generates chained bucketed thumbnails if needed
1196 * @param array $params
1198 * @return bool Whether at least one bucket was generated
1200 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1202 ||
!isset( $params['physicalWidth'] )
1203 ||
!isset( $params['physicalHeight'] )
1208 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1210 if ( !$bucket ||
$bucket == $params['physicalWidth'] ) {
1214 $bucketPath = $this->getBucketThumbPath( $bucket );
1216 if ( $this->repo
->fileExists( $bucketPath ) ) {
1220 $starttime = microtime( true );
1222 $params['physicalWidth'] = $bucket;
1223 $params['width'] = $bucket;
1225 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1227 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1233 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1235 $buckettime = microtime( true ) - $starttime;
1237 if ( !$thumb ||
$thumb->isError() ) {
1241 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1242 // For the caching to work, we need to make the tmp file survive as long as
1243 // this object exists
1244 $tmpFile->bind( $this );
1246 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
1247 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1253 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1254 * @param array $params
1255 * @return array Source path and width/height of the source
1257 public function getThumbnailSource( $params ) {
1259 && $this->getHandler()->supportsBucketing()
1260 && isset( $params['physicalWidth'] )
1261 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1263 if ( $this->getWidth() != 0 ) {
1264 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1269 // Try to avoid reading from storage if the file was generated by this script
1270 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1271 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1273 if ( file_exists( $tmpPath ) ) {
1277 'height' => $bucketHeight
1282 $bucketPath = $this->getBucketThumbPath( $bucket );
1284 if ( $this->repo
->fileExists( $bucketPath ) ) {
1285 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1289 'path' => $fsFile->getPath(),
1291 'height' => $bucketHeight
1297 // Thumbnailing a very large file could result in network saturation if
1298 // everyone does it at once.
1299 if ( $this->getSize() >= 1e7
) { // 10MB
1300 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1302 'doWork' => function () {
1303 return $this->getLocalRefPath();
1307 $srcPath = $work->execute();
1309 $srcPath = $this->getLocalRefPath();
1315 'width' => $this->getWidth(),
1316 'height' => $this->getHeight()
1321 * Returns the repo path of the thumb for a given bucket
1322 * @param int $bucket
1325 protected function getBucketThumbPath( $bucket ) {
1326 $thumbName = $this->getBucketThumbName( $bucket );
1327 return $this->getThumbPath( $thumbName );
1331 * Returns the name of the thumb for a given bucket
1332 * @param int $bucket
1335 protected function getBucketThumbName( $bucket ) {
1336 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1340 * Creates a temp FS file with the same extension and the thumbnail
1341 * @param string $thumbPath Thumbnail path
1342 * @return TempFSFile|null
1344 protected function makeTransformTmpFile( $thumbPath ) {
1345 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1346 return TempFSFile
::factory( 'transform_', $thumbExt, wfTempDir() );
1350 * @param string $thumbName Thumbnail name
1351 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1352 * @return string Content-Disposition header value
1354 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1355 $fileName = $this->name
; // file name to suggest
1356 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1357 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1358 $fileName .= ".$thumbExt";
1361 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1365 * Hook into transform() to allow migration of thumbnail files
1367 * Overridden by LocalFile
1368 * @param string $thumbName
1370 function migrateThumbFile( $thumbName ) {
1374 * Get a MediaHandler instance for this file
1376 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1377 * or false if none found
1379 function getHandler() {
1380 if ( !isset( $this->handler
) ) {
1381 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1384 return $this->handler
;
1388 * Get a ThumbnailImage representing a file type icon
1390 * @return ThumbnailImage
1392 function iconThumb() {
1393 global $wgResourceBasePath, $IP;
1394 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1395 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1397 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1398 foreach ( $try as $icon ) {
1399 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1400 $params = [ 'width' => 120, 'height' => 120 ];
1402 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1410 * Get last thumbnailing error.
1414 function getLastError() {
1415 return $this->lastError
;
1419 * Get all thumbnail names previously generated for this file
1421 * Overridden by LocalFile
1424 function getThumbnails() {
1429 * Purge shared caches such as thumbnails and DB data caching
1431 * Overridden by LocalFile
1432 * @param array $options Options, which include:
1433 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1435 function purgeCache( $options = [] ) {
1439 * Purge the file description page, but don't go after
1440 * pages using the file. Use when modifying file history
1441 * but not the current data.
1443 function purgeDescription() {
1444 $title = $this->getTitle();
1446 $title->invalidateCache();
1447 $title->purgeSquid();
1452 * Purge metadata and all affected pages when the file is created,
1453 * deleted, or majorly updated.
1455 function purgeEverything() {
1456 // Delete thumbnails and refresh file metadata cache
1457 $this->purgeCache();
1458 $this->purgeDescription();
1460 // Purge cache of all pages using this file
1461 $title = $this->getTitle();
1463 DeferredUpdates
::addUpdate(
1464 new HTMLCacheUpdate( $title, 'imagelinks', 'file-purge' )
1470 * Return a fragment of the history of file.
1473 * @param int|null $limit Limit of rows to return
1474 * @param string|int|null $start Only revisions older than $start will be returned
1475 * @param string|int|null $end Only revisions newer than $end will be returned
1476 * @param bool $inc Include the endpoints of the time range
1480 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1485 * Return the history of this file, line by line. Starts with current version,
1486 * then old versions. Should return an object similar to an image/oldimage
1490 * Overridden in LocalFile
1493 public function nextHistoryLine() {
1498 * Reset the history pointer to the first element of the history.
1499 * Always call this function after using nextHistoryLine() to free db resources
1501 * Overridden in LocalFile.
1503 public function resetHistory() {
1507 * Get the filename hash component of the directory including trailing slash,
1509 * If the repository is not hashed, returns an empty string.
1513 function getHashPath() {
1514 if ( !isset( $this->hashPath
) ) {
1515 $this->assertRepoDefined();
1516 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1519 return $this->hashPath
;
1523 * Get the path of the file relative to the public zone root.
1524 * This function is overridden in OldLocalFile to be like getArchiveRel().
1529 return $this->getHashPath() . $this->getName();
1533 * Get the path of an archived file relative to the public zone root
1535 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1539 function getArchiveRel( $suffix = false ) {
1540 $path = 'archive/' . $this->getHashPath();
1541 if ( $suffix === false ) {
1542 $path = rtrim( $path, '/' );
1551 * Get the path, relative to the thumbnail zone root, of the
1552 * thumbnail directory or a particular file if $suffix is specified
1554 * @param bool|string $suffix If not false, the name of a thumbnail file
1557 function getThumbRel( $suffix = false ) {
1558 $path = $this->getRel();
1559 if ( $suffix !== false ) {
1560 $path .= '/' . $suffix;
1567 * Get urlencoded path of the file relative to the public zone root.
1568 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1572 function getUrlRel() {
1573 return $this->getHashPath() . rawurlencode( $this->getName() );
1577 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1578 * or a specific thumb if the $suffix is given.
1580 * @param string $archiveName The timestamped name of an archived image
1581 * @param bool|string $suffix If not false, the name of a thumbnail file
1584 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1585 $path = $this->getArchiveRel( $archiveName );
1586 if ( $suffix !== false ) {
1587 $path .= '/' . $suffix;
1594 * Get the path of the archived file.
1596 * @param bool|string $suffix If not false, the name of an archived file.
1599 function getArchivePath( $suffix = false ) {
1600 $this->assertRepoDefined();
1602 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1606 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1608 * @param string $archiveName The timestamped name of an archived image
1609 * @param bool|string $suffix If not false, the name of a thumbnail file
1612 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1613 $this->assertRepoDefined();
1615 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1616 $this->getArchiveThumbRel( $archiveName, $suffix );
1620 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1622 * @param bool|string $suffix If not false, the name of a thumbnail file
1625 function getThumbPath( $suffix = false ) {
1626 $this->assertRepoDefined();
1628 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1632 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1634 * @param bool|string $suffix If not false, the name of a media file
1637 function getTranscodedPath( $suffix = false ) {
1638 $this->assertRepoDefined();
1640 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1644 * Get the URL of the archive directory, or a particular file if $suffix is specified
1646 * @param bool|string $suffix If not false, the name of an archived file
1649 function getArchiveUrl( $suffix = false ) {
1650 $this->assertRepoDefined();
1651 $ext = $this->getExtension();
1652 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1653 if ( $suffix === false ) {
1654 $path = rtrim( $path, '/' );
1656 $path .= rawurlencode( $suffix );
1663 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1665 * @param string $archiveName The timestamped name of an archived image
1666 * @param bool|string $suffix If not false, the name of a thumbnail file
1669 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1670 $this->assertRepoDefined();
1671 $ext = $this->getExtension();
1672 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1673 $this->getHashPath() . rawurlencode( $archiveName );
1674 if ( $suffix !== false ) {
1675 $path .= '/' . rawurlencode( $suffix );
1682 * Get the URL of the zone directory, or a particular file if $suffix is specified
1684 * @param string $zone Name of requested zone
1685 * @param bool|string $suffix If not false, the name of a file in zone
1686 * @return string Path
1688 function getZoneUrl( $zone, $suffix = false ) {
1689 $this->assertRepoDefined();
1690 $ext = $this->getExtension();
1691 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1692 if ( $suffix !== false ) {
1693 $path .= '/' . rawurlencode( $suffix );
1700 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1702 * @param bool|string $suffix If not false, the name of a thumbnail file
1703 * @return string Path
1705 function getThumbUrl( $suffix = false ) {
1706 return $this->getZoneUrl( 'thumb', $suffix );
1710 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1712 * @param bool|string $suffix If not false, the name of a media file
1713 * @return string Path
1715 function getTranscodedUrl( $suffix = false ) {
1716 return $this->getZoneUrl( 'transcoded', $suffix );
1720 * Get the public zone virtual URL for a current version source file
1722 * @param bool|string $suffix If not false, the name of a thumbnail file
1725 function getVirtualUrl( $suffix = false ) {
1726 $this->assertRepoDefined();
1727 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1728 if ( $suffix !== false ) {
1729 $path .= '/' . rawurlencode( $suffix );
1736 * Get the public zone virtual URL for an archived version source file
1738 * @param bool|string $suffix If not false, the name of a thumbnail file
1741 function getArchiveVirtualUrl( $suffix = false ) {
1742 $this->assertRepoDefined();
1743 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1744 if ( $suffix === false ) {
1745 $path = rtrim( $path, '/' );
1747 $path .= rawurlencode( $suffix );
1754 * Get the virtual URL for a thumbnail file or directory
1756 * @param bool|string $suffix If not false, the name of a thumbnail file
1759 function getThumbVirtualUrl( $suffix = false ) {
1760 $this->assertRepoDefined();
1761 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1762 if ( $suffix !== false ) {
1763 $path .= '/' . rawurlencode( $suffix );
1772 function isHashed() {
1773 $this->assertRepoDefined();
1775 return (bool)$this->repo
->getHashLevels();
1779 * @throws MWException
1781 function readOnlyError() {
1782 throw new MWException( static::class . ': write operations are not supported' );
1786 * Record a file upload in the upload log and the image table
1788 * Overridden by LocalFile
1789 * @param string $oldver
1790 * @param string $desc
1791 * @param string $license
1792 * @param string $copyStatus
1793 * @param string $source
1794 * @param bool $watch
1795 * @param string|bool $timestamp
1796 * @param null|User $user User object or null to use $wgUser
1798 * @throws MWException
1800 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1801 $watch = false, $timestamp = false, User
$user = null
1803 $this->readOnlyError();
1807 * Move or copy a file to its public location. If a file exists at the
1808 * destination, move it to an archive. Returns a Status object with
1809 * the archive name in the "value" member on success.
1811 * The archive name should be passed through to recordUpload for database
1814 * Options to $options include:
1815 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1817 * @param string|FSFile $src Local filesystem path to the source image
1818 * @param int $flags A bitwise combination of:
1819 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1820 * @param array $options Optional additional parameters
1821 * @return Status On success, the value member contains the
1822 * archive name, or an empty string if it was a new file.
1825 * Overridden by LocalFile
1827 function publish( $src, $flags = 0, array $options = [] ) {
1828 $this->readOnlyError();
1832 * @param bool|IContextSource $context Context to use (optional)
1835 function formatMetadata( $context = false ) {
1836 if ( !$this->getHandler() ) {
1840 return $this->getHandler()->formatMetadata( $this, $context );
1844 * Returns true if the file comes from the local file repository.
1848 function isLocal() {
1849 return $this->repo
&& $this->repo
->isLocal();
1853 * Returns the name of the repository.
1857 function getRepoName() {
1858 return $this->repo ?
$this->repo
->getName() : 'unknown';
1862 * Returns the repository
1864 * @return FileRepo|LocalRepo|bool
1866 function getRepo() {
1871 * Returns true if the image is an old version
1881 * Is this file a "deleted" file in a private archive?
1884 * @param int $field One of DELETED_* bitfield constants
1887 function isDeleted( $field ) {
1892 * Return the deletion bitfield
1896 function getVisibility() {
1901 * Was this file ever deleted from the wiki?
1905 function wasDeleted() {
1906 $title = $this->getTitle();
1908 return $title && $title->isDeletedQuick();
1912 * Move file to the new title
1914 * Move current, old version and all thumbnails
1915 * to the new filename. Old file is deleted.
1917 * Cache purging is done; checks for validity
1918 * and logging are caller's responsibility
1920 * @param Title $target New file name
1923 function move( $target ) {
1924 $this->readOnlyError();
1928 * Delete all versions of the file.
1930 * Moves the files into an archive directory (or deletes them)
1931 * and removes the database rows.
1933 * Cache purging is done; logging is caller's responsibility.
1935 * @param string $reason
1936 * @param bool $suppress Hide content from sysops?
1937 * @param User|null $user
1940 * Overridden by LocalFile
1942 function delete( $reason, $suppress = false, $user = null ) {
1943 $this->readOnlyError();
1947 * Restore all or specified deleted revisions to the given file.
1948 * Permissions and logging are left to the caller.
1950 * May throw database exceptions on error.
1952 * @param array $versions Set of record ids of deleted items to restore,
1953 * or empty to restore all revisions.
1954 * @param bool $unsuppress Remove restrictions on content upon restoration?
1955 * @return int|bool The number of file revisions restored if successful,
1956 * or false on failure
1958 * Overridden by LocalFile
1960 function restore( $versions = [], $unsuppress = false ) {
1961 $this->readOnlyError();
1965 * Returns 'true' if this file is a type which supports multiple pages,
1966 * e.g. DJVU or PDF. Note that this may be true even if the file in
1967 * question only has a single page.
1971 function isMultipage() {
1972 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1976 * Returns the number of pages of a multipage document, or false for
1977 * documents which aren't multipage documents
1979 * @return string|bool|int
1981 function pageCount() {
1982 if ( !isset( $this->pageCount
) ) {
1983 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1984 $this->pageCount
= $this->handler
->pageCount( $this );
1986 $this->pageCount
= false;
1990 return $this->pageCount
;
1994 * Calculate the height of a thumbnail using the source and destination width
1996 * @param int $srcWidth
1997 * @param int $srcHeight
1998 * @param int $dstWidth
2002 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
2003 // Exact integer multiply followed by division
2004 if ( $srcWidth == 0 ) {
2007 return (int)round( $srcHeight * $dstWidth / $srcWidth );
2012 * Get an image size array like that returned by getImageSize(), or false if it
2013 * can't be determined. Loads the image size directly from the file ignoring caches.
2015 * @note Use getWidth()/getHeight() instead of this method unless you have a
2016 * a good reason. This method skips all caches.
2018 * @param string $filePath The path to the file (e.g. From getLocalRefPath() )
2019 * @return array|false The width, followed by height, with optionally more things after
2021 function getImageSize( $filePath ) {
2022 if ( !$this->getHandler() ) {
2026 return $this->getHandler()->getImageSize( $this, $filePath );
2030 * Get the URL of the image description page. May return false if it is
2031 * unknown or not applicable.
2035 function getDescriptionUrl() {
2036 if ( $this->repo
) {
2037 return $this->repo
->getDescriptionUrl( $this->getName() );
2044 * Get the HTML text of the description page, if available
2046 * @param Language|null $lang Optional language to fetch description in
2047 * @return string|false
2049 function getDescriptionText( Language
$lang = null ) {
2052 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
2056 $lang = $lang ??
$wgLang;
2058 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2060 $cache = MediaWikiServices
::getInstance()->getMainWANObjectCache();
2061 $key = $this->repo
->getLocalCacheKey(
2062 'RemoteFileDescription',
2064 md5( $this->getName() )
2066 $fname = __METHOD__
;
2068 return $cache->getWithSetCallback(
2070 $this->repo
->descriptionCacheExpiry ?
: $cache::TTL_UNCACHEABLE
,
2071 function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl, $fname ) {
2072 wfDebug( "Fetching shared description from $renderUrl\n" );
2073 $res = MediaWikiServices
::getInstance()->getHttpRequestFactory()->
2074 get( $renderUrl, [], $fname );
2076 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
2088 * Get description of file revision
2091 * @param int $audience One of:
2092 * File::FOR_PUBLIC to be displayed to all users
2093 * File::FOR_THIS_USER to be displayed to the given user
2094 * File::RAW get the description regardless of permissions
2095 * @param User|null $user User object to check for, only if FOR_THIS_USER is
2096 * passed to the $audience parameter
2097 * @return null|string
2099 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
2104 * Get the 14-character timestamp of the file upload
2106 * @return string|bool TS_MW timestamp or false on failure
2108 function getTimestamp() {
2109 $this->assertRepoDefined();
2111 return $this->repo
->getFileTimestamp( $this->getPath() );
2115 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2116 * Returns false if the file does not have a description page, or retrieving the timestamp
2117 * would be expensive.
2119 * @return string|bool
2121 public function getDescriptionTouched() {
2126 * Get the SHA-1 base 36 hash of the file
2130 function getSha1() {
2131 $this->assertRepoDefined();
2133 return $this->repo
->getFileSha1( $this->getPath() );
2137 * Get the deletion archive key, "<sha1>.<ext>"
2139 * @return string|false
2141 function getStorageKey() {
2142 $hash = $this->getSha1();
2146 $ext = $this->getExtension();
2147 $dotExt = $ext === '' ?
'' : ".$ext";
2149 return $hash . $dotExt;
2153 * Determine if the current user is allowed to view a particular
2154 * field of this file, if it's marked as deleted.
2157 * @param User|null $user User object to check, or null to use $wgUser
2160 function userCan( $field, User
$user = null ) {
2165 * @return string[] HTTP header name/value map to use for HEAD/GET request responses
2168 function getContentHeaders() {
2169 $handler = $this->getHandler();
2171 $metadata = $this->getMetadata();
2173 if ( is_string( $metadata ) ) {
2174 $metadata = Wikimedia\
quietCall( 'unserialize', $metadata );
2177 if ( !is_array( $metadata ) ) {
2181 return $handler->getContentHeaders( $metadata );
2190 function getLongDesc() {
2191 $handler = $this->getHandler();
2193 return $handler->getLongDesc( $this );
2195 return MediaHandler
::getGeneralLongDesc( $this );
2202 function getShortDesc() {
2203 $handler = $this->getHandler();
2205 return $handler->getShortDesc( $this );
2207 return MediaHandler
::getGeneralShortDesc( $this );
2214 function getDimensionsString() {
2215 $handler = $this->getHandler();
2217 return $handler->getDimensionsString( $this );
2226 function getRedirected() {
2227 return $this->redirected
;
2231 * @return Title|null
2233 function getRedirectedTitle() {
2234 if ( $this->redirected
) {
2235 if ( !$this->redirectTitle
) {
2236 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
2239 return $this->redirectTitle
;
2246 * @param string $from
2249 function redirectedFrom( $from ) {
2250 $this->redirected
= $from;
2256 function isMissing() {
2261 * Check if this file object is small and can be cached
2264 public function isCacheable() {
2269 * Assert that $this->repo is set to a valid FileRepo instance
2270 * @throws MWException
2272 protected function assertRepoDefined() {
2273 if ( !( $this->repo
instanceof $this->repoClass
) ) {
2274 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2279 * Assert that $this->title is set to a Title
2280 * @throws MWException
2282 protected function assertTitleDefined() {
2283 if ( !( $this->title
instanceof Title
) ) {
2284 throw new MWException( "A Title object is not set for this File.\n" );
2289 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2292 public function isExpensiveToThumbnail() {
2293 $handler = $this->getHandler();
2294 return $handler ?
$handler->isExpensiveToThumbnail( $this ) : false;
2298 * Whether the thumbnails created on the same server as this code is running.
2302 public function isTransformedLocally() {