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 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
51 * @ingroup FileAbstraction
53 abstract class File
implements IDBAccessObject
{
54 // Bitfield values akin to the Revision deletion constants
55 const DELETED_FILE
= 1;
56 const DELETED_COMMENT
= 2;
57 const DELETED_USER
= 4;
58 const DELETED_RESTRICTED
= 8;
60 /** Force rendering in the current process */
63 * Force rendering even if thumbnail already exist and using RENDER_NOW
64 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
66 const RENDER_FORCE
= 2;
68 const DELETE_SOURCE
= 1;
70 // Audience options for File::getDescription()
72 const FOR_THIS_USER
= 2;
75 // Options for File::thumbName()
76 const THUMB_FULL_NAME
= 1;
79 * Some member variables can be lazy-initialised using __get(). The
80 * initialisation function for these variables is always a function named
81 * like getVar(), where Var is the variable name with upper-case first
84 * The following variables are initialised in this way in this base class:
85 * name, extension, handler, path, canRender, isSafeFile,
86 * transformScript, hashPath, pageCount, url
88 * Code within this class should generally use the accessor function
89 * directly, since __get() isn't re-entrant and therefore causes bugs that
90 * depend on initialisation order.
94 * The following member variables are not lazy-initialised
97 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
100 /** @var Title|string|bool */
103 /** @var string Text of last error */
104 protected $lastError;
106 /** @var string Main part of the title, with underscores (Title::getDBkey) */
107 protected $redirected;
110 protected $redirectedTitle;
112 /** @var FSFile|bool False if undefined */
115 /** @var MediaHandler */
118 /** @var string The URL corresponding to one of the four basic zones */
121 /** @var string File extension */
122 protected $extension;
124 /** @var string The name of a file from its title object */
127 /** @var string The storage path corresponding to one of the zones */
130 /** @var string Relative path including trailing slash */
133 /** @var string|false Number of pages of a multipage document, or false for
134 * documents which aren't multipage documents
136 protected $pageCount;
138 /** @var string URL of transformscript (for example thumb.php) */
139 protected $transformScript;
142 protected $redirectTitle;
144 /** @var bool Whether the output of transform() for this file is likely to be valid. */
145 protected $canRender;
147 /** @var bool Whether this media file is in a format that is unlikely to
148 * contain viruses or malicious content
150 protected $isSafeFile;
152 /** @var string Required Repository class type */
153 protected $repoClass = FileRepo
::class;
155 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
156 protected $tmpBucketedThumbCache = [];
159 * Call this constructor from child classes.
161 * Both $title and $repo are optional, though some functions
162 * may return false or throw exceptions if they are not set.
163 * Most subclasses will want to call assertRepoDefined() here.
165 * @param Title|string|bool $title
166 * @param FileRepo|bool $repo
168 function __construct( $title, $repo ) {
169 // Some subclasses do not use $title, but set name/title some other way
170 if ( $title !== false ) {
171 $title = self
::normalizeTitle( $title, 'exception' );
173 $this->title
= $title;
178 * Given a string or Title object return either a
179 * valid Title object with namespace NS_FILE or null
181 * @param Title|string $title
182 * @param string|bool $exception Use 'exception' to throw an error on bad titles
183 * @throws MWException
186 static function normalizeTitle( $title, $exception = false ) {
188 if ( $ret instanceof Title
) {
189 # Normalize NS_MEDIA -> NS_FILE
190 if ( $ret->getNamespace() == NS_MEDIA
) {
191 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
192 # Sanity check the title namespace
193 } elseif ( $ret->getNamespace() !== NS_FILE
) {
197 # Convert strings to Title objects
198 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
200 if ( !$ret && $exception !== false ) {
201 throw new MWException( "`$title` is not a valid file title." );
207 function __get( $name ) {
208 $function = [ $this, 'get' . ucfirst( $name ) ];
209 if ( !is_callable( $function ) ) {
212 $this->$name = $function();
219 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
220 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
221 * Keep in sync with mw.Title.normalizeExtension() in JS.
223 * @param string $extension File extension (without the leading dot)
224 * @return string File extension in canonical form
226 static function normalizeExtension( $extension ) {
227 $lower = strtolower( $extension );
234 if ( isset( $squish[$lower] ) ) {
235 return $squish[$lower];
236 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
244 * Checks if file extensions are compatible
246 * @param File $old Old file
247 * @param string $new New name
251 static function checkExtensionCompatibility( File
$old, $new ) {
252 $oldMime = $old->getMimeType();
253 $n = strrpos( $new, '.' );
254 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
255 $mimeMagic = MediaWiki\MediaWikiServices
::getInstance()->getMimeAnalyzer();
257 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
261 * Upgrade the database row if there is one
262 * Called by ImagePage
265 function upgradeRow() {
269 * Split an internet media type into its two components; if not
270 * a two-part name, set the minor type to 'unknown'.
272 * @param string $mime "text/html" etc
273 * @return string[] ("text", "html") etc
275 public static function splitMime( $mime ) {
276 if ( strpos( $mime, '/' ) !== false ) {
277 return explode( '/', $mime, 2 );
279 return [ $mime, 'unknown' ];
284 * Callback for usort() to do file sorts by name
288 * @return int Result of name comparison
290 public static function compare( File
$a, File
$b ) {
291 return strcmp( $a->getName(), $b->getName() );
295 * Return the name of this file
299 public function getName() {
300 if ( !isset( $this->name
) ) {
301 $this->assertRepoDefined();
302 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
309 * Get the file extension, e.g. "svg"
313 function getExtension() {
314 if ( !isset( $this->extension
) ) {
315 $n = strrpos( $this->getName(), '.' );
316 $this->extension
= self
::normalizeExtension(
317 $n ?
substr( $this->getName(), $n +
1 ) : '' );
320 return $this->extension
;
324 * Return the associated title object
328 public function getTitle() {
333 * Return the title used to find this file
337 public function getOriginalTitle() {
338 if ( $this->redirected
) {
339 return $this->getRedirectedTitle();
346 * Return the URL of the file
350 public function getUrl() {
351 if ( !isset( $this->url
) ) {
352 $this->assertRepoDefined();
353 $ext = $this->getExtension();
354 $this->url
= $this->repo
->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
361 * Get short description URL for a files based on the page ID
363 * @return string|null
366 public function getDescriptionShortUrl() {
371 * Return a fully-qualified URL to the file.
372 * Upload URL paths _may or may not_ be fully qualified, so
373 * we check. Local paths are assumed to belong on $wgServer.
377 public function getFullUrl() {
378 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
384 public function getCanonicalUrl() {
385 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
391 function getViewURL() {
392 if ( $this->mustRender() ) {
393 if ( $this->canRender() ) {
394 return $this->createThumb( $this->getWidth() );
396 wfDebug( __METHOD__
. ': supposed to render ' . $this->getName() .
397 ' (' . $this->getMimeType() . "), but can't!\n" );
399 return $this->getUrl(); # hm... return NULL?
402 return $this->getUrl();
407 * Return the storage path to the file. Note that this does
408 * not mean that a file actually exists under that location.
410 * This path depends on whether directory hashing is active or not,
411 * i.e. whether the files are all found in the same directory,
412 * or in hashed paths like /images/3/3c.
414 * Most callers don't check the return value, but ForeignAPIFile::getPath
417 * @return string|bool ForeignAPIFile::getPath can return false
419 public function getPath() {
420 if ( !isset( $this->path
) ) {
421 $this->assertRepoDefined();
422 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
429 * Get an FS copy or original of this file and return the path.
430 * Returns false on failure. Callers must not alter the file.
431 * Temporary files are cleared automatically.
433 * @return string|bool False on failure
435 public function getLocalRefPath() {
436 $this->assertRepoDefined();
437 if ( !isset( $this->fsFile
) ) {
438 $starttime = microtime( true );
439 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
441 $statTiming = microtime( true ) - $starttime;
442 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
443 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
445 if ( !$this->fsFile
) {
446 $this->fsFile
= false; // null => false; cache negative hits
450 return ( $this->fsFile
)
451 ?
$this->fsFile
->getPath()
456 * Return the width of the image. Returns false if the width is unknown
460 * Overridden by LocalFile, UnregisteredLocalFile
465 public function getWidth( $page = 1 ) {
470 * Return the height of the image. Returns false if the height is unknown
474 * Overridden by LocalFile, UnregisteredLocalFile
477 * @return bool|int False on failure
479 public function getHeight( $page = 1 ) {
484 * Return the smallest bucket from $wgThumbnailBuckets which is at least
485 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
486 * will always be bigger than $desiredWidth.
488 * @param int $desiredWidth
492 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
493 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
495 $imageWidth = $this->getWidth( $page );
497 if ( $imageWidth === false ) {
501 if ( $desiredWidth > $imageWidth ) {
505 if ( !$wgThumbnailBuckets ) {
509 $sortedBuckets = $wgThumbnailBuckets;
511 sort( $sortedBuckets );
513 foreach ( $sortedBuckets as $bucket ) {
514 if ( $bucket >= $imageWidth ) {
518 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
523 // Image is bigger than any available bucket
528 * Returns ID or name of user who uploaded the file
531 * @param string $type 'text' or 'id'
534 public function getUser( $type = 'text' ) {
539 * Get the duration of a media file in seconds
543 public function getLength() {
544 $handler = $this->getHandler();
546 return $handler->getLength( $this );
553 * Return true if the file is vectorized
557 public function isVectorized() {
558 $handler = $this->getHandler();
560 return $handler->isVectorized( $this );
567 * Gives a (possibly empty) list of languages to render
570 * If the file doesn't have translations, or if the file
571 * format does not support that sort of thing, returns
577 public function getAvailableLanguages() {
578 $handler = $this->getHandler();
580 return $handler->getAvailableLanguages( $this );
587 * Get the language code from the available languages for this file that matches the language
588 * requested by the user
590 * @param string $userPreferredLanguage
591 * @return string|null
593 public function getMatchedLanguage( $userPreferredLanguage ) {
594 $handler = $this->getHandler();
596 return $handler->getMatchedLanguage(
597 $userPreferredLanguage,
598 $handler->getAvailableLanguages( $this )
606 * In files that support multiple language, what is the default language
607 * to use if none specified.
609 * @return string|null Lang code, or null if filetype doesn't support multiple languages.
612 public function getDefaultRenderLanguage() {
613 $handler = $this->getHandler();
615 return $handler->getDefaultRenderLanguage( $this );
622 * Will the thumbnail be animated if one would expect it to be.
624 * Currently used to add a warning to the image description page
626 * @return bool False if the main image is both animated
627 * and the thumbnail is not. In all other cases must return
628 * true. If image is not renderable whatsoever, should
631 public function canAnimateThumbIfAppropriate() {
632 $handler = $this->getHandler();
634 // We cannot handle image whatsoever, thus
635 // one would not expect it to be animated
640 return !$this->allowInlineDisplay()
641 // Image is not animated, so one would
642 // not expect thumb to be
643 ||
!$handler->isAnimatedImage( $this )
644 // Image is animated, but thumbnail isn't.
645 // This is unexpected to the user.
646 ||
$handler->canAnimateThumbnail( $this );
650 * Get handler-specific metadata
651 * Overridden by LocalFile, UnregisteredLocalFile
655 public function getMetadata() {
660 * Like getMetadata but returns a handler independent array of common values.
661 * @see MediaHandler::getCommonMetaArray()
662 * @return array|bool Array or false if not supported
665 public function getCommonMetaArray() {
666 $handler = $this->getHandler();
672 return $handler->getCommonMetaArray( $this );
676 * get versioned metadata
678 * @param array|string $metadata Array or string of (serialized) metadata
679 * @param int $version Version number.
680 * @return array Array containing metadata, or what was passed to it on fail
681 * (unserializing if not array)
683 public function convertMetadataVersion( $metadata, $version ) {
684 $handler = $this->getHandler();
685 if ( !is_array( $metadata ) ) {
686 // Just to make the return type consistent
687 $metadata = unserialize( $metadata );
690 return $handler->convertMetadataVersion( $metadata, $version );
697 * Return the bit depth of the file
698 * Overridden by LocalFile
702 public function getBitDepth() {
707 * Return the size of the image file, in bytes
708 * Overridden by LocalFile, UnregisteredLocalFile
712 public function getSize() {
717 * Returns the MIME type of the file.
718 * Overridden by LocalFile, UnregisteredLocalFile
723 function getMimeType() {
724 return 'unknown/unknown';
728 * Return the type of the media in the file.
729 * Use the value returned by this function with the MEDIATYPE_xxx constants.
730 * Overridden by LocalFile,
734 function getMediaType() {
735 return MEDIATYPE_UNKNOWN
;
739 * Checks if the output of transform() for this file is likely
740 * to be valid. If this is false, various user elements will
741 * display a placeholder instead.
743 * Currently, this checks if the file is an image format
744 * that can be converted to a format
745 * supported by all browsers (namely GIF, PNG and JPEG),
746 * or if it is an SVG image and SVG conversion is enabled.
750 function canRender() {
751 if ( !isset( $this->canRender
) ) {
752 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this ) && $this->exists();
755 return $this->canRender
;
759 * Accessor for __get()
762 protected function getCanRender() {
763 return $this->canRender();
767 * Return true if the file is of a type that can't be directly
768 * rendered by typical browsers and needs to be re-rasterized.
770 * This returns true for everything but the bitmap types
771 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
772 * also return true for any non-image formats.
776 function mustRender() {
777 return $this->getHandler() && $this->handler
->mustRender( $this );
781 * Alias for canRender()
785 function allowInlineDisplay() {
786 return $this->canRender();
790 * Determines if this media file is in a format that is unlikely to
791 * contain viruses or malicious content. It uses the global
792 * $wgTrustedMediaFormats list to determine if the file is safe.
794 * This is used to show a warning on the description page of non-safe files.
795 * It may also be used to disallow direct [[media:...]] links to such files.
797 * Note that this function will always return true if allowInlineDisplay()
798 * or isTrustedFile() is true for this file.
802 function isSafeFile() {
803 if ( !isset( $this->isSafeFile
) ) {
804 $this->isSafeFile
= $this->getIsSafeFileUncached();
807 return $this->isSafeFile
;
811 * Accessor for __get()
815 protected function getIsSafeFile() {
816 return $this->isSafeFile();
824 protected function getIsSafeFileUncached() {
825 global $wgTrustedMediaFormats;
827 if ( $this->allowInlineDisplay() ) {
830 if ( $this->isTrustedFile() ) {
834 $type = $this->getMediaType();
835 $mime = $this->getMimeType();
836 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
838 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
839 return false; # unknown type, not trusted
841 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
845 if ( $mime === "unknown/unknown" ) {
846 return false; # unknown type, not trusted
848 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
856 * Returns true if the file is flagged as trusted. Files flagged that way
857 * can be linked to directly, even if that is not allowed for this type of
860 * This is a dummy function right now and always returns false. It could be
861 * implemented to extract a flag from the database. The trusted flag could be
862 * set on upload, if the user has sufficient privileges, to bypass script-
863 * and html-filters. It may even be coupled with cryptographics signatures
868 function isTrustedFile() {
869 # this could be implemented to check a flag in the database,
870 # look for signatures, etc
875 * Load any lazy-loaded file object fields from source
877 * This is only useful when setting $flags
879 * Overridden by LocalFile to actually query the DB
881 * @param int $flags Bitfield of File::READ_* constants
883 public function load( $flags = 0 ) {
887 * Returns true if file exists in the repository.
889 * Overridden by LocalFile to avoid unnecessary stat calls.
891 * @return bool Whether file exists in the repository.
893 public function exists() {
894 return $this->getPath() && $this->repo
->fileExists( $this->path
);
898 * Returns true if file exists in the repository and can be included in a page.
899 * It would be unsafe to include private images, making public thumbnails inadvertently
901 * @return bool Whether file exists in the repository and is includable.
903 public function isVisible() {
904 return $this->exists();
910 function getTransformScript() {
911 if ( !isset( $this->transformScript
) ) {
912 $this->transformScript
= false;
914 $script = $this->repo
->getThumbScriptUrl();
916 $this->transformScript
= wfAppendQuery( $script, [ 'f' => $this->getName() ] );
921 return $this->transformScript
;
925 * Get a ThumbnailImage which is the same size as the source
927 * @param array $handlerParams
929 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
931 function getUnscaledThumb( $handlerParams = [] ) {
932 $hp =& $handlerParams;
933 $page = $hp['page'] ??
false;
934 $width = $this->getWidth( $page );
936 return $this->iconThumb();
938 $hp['width'] = $width;
939 // be sure to ignore any height specification as well (T64258)
940 unset( $hp['height'] );
942 return $this->transform( $hp );
946 * Return the file name of a thumbnail with the specified parameters.
947 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
948 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
950 * @param array $params Handler-specific parameters
951 * @param int $flags Bitfield that supports THUMB_* constants
952 * @return string|null
954 public function thumbName( $params, $flags = 0 ) {
955 $name = ( $this->repo
&& !( $flags & self
::THUMB_FULL_NAME
) )
956 ?
$this->repo
->nameForThumb( $this->getName() )
959 return $this->generateThumbName( $name, $params );
963 * Generate a thumbnail file name from a name and specified parameters
965 * @param string $name
966 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
967 * @return string|null
969 public function generateThumbName( $name, $params ) {
970 if ( !$this->getHandler() ) {
973 $extension = $this->getExtension();
974 list( $thumbExt, ) = $this->getHandler()->getThumbType(
975 $extension, $this->getMimeType(), $params );
976 $thumbName = $this->getHandler()->makeParamString( $params );
978 if ( $this->repo
->supportsSha1URLs() ) {
979 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
981 $thumbName .= '-' . $name;
983 if ( $thumbExt != $extension ) {
984 $thumbName .= ".$thumbExt";
992 * Create a thumbnail of the image having the specified width/height.
993 * The thumbnail will not be created if the width is larger than the
994 * image's width. Let the browser do the scaling in this case.
995 * The thumbnail is stored on disk and is only computed if the thumbnail
996 * file does not exist OR if it is older than the image.
999 * Keeps aspect ratio of original image. If both width and height are
1000 * specified, the generated image will be no bigger than width x height,
1001 * and will also have correct aspect ratio.
1003 * @param int $width Maximum width of the generated thumbnail
1004 * @param int $height Maximum height of the image (optional)
1008 public function createThumb( $width, $height = -1 ) {
1009 $params = [ 'width' => $width ];
1010 if ( $height != -1 ) {
1011 $params['height'] = $height;
1013 $thumb = $this->transform( $params );
1014 if ( !$thumb ||
$thumb->isError() ) {
1018 return $thumb->getUrl();
1022 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
1024 * @param string $thumbPath Thumbnail storage path
1025 * @param string $thumbUrl Thumbnail URL
1026 * @param array $params
1028 * @return MediaTransformOutput
1030 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1031 global $wgIgnoreImageErrors;
1033 $handler = $this->getHandler();
1034 if ( $handler && $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1035 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1037 return new MediaTransformError( 'thumbnail_error',
1038 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1043 * Transform a media file
1045 * @param array $params An associative array of handler-specific parameters.
1046 * Typical keys are width, height and page.
1047 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1048 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
1050 function transform( $params, $flags = 0 ) {
1051 global $wgThumbnailEpoch;
1054 if ( !$this->canRender() ) {
1055 $thumb = $this->iconThumb();
1056 break; // not a bitmap or renderable image, don't try
1059 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1060 $descriptionUrl = $this->getDescriptionUrl();
1061 if ( $descriptionUrl ) {
1062 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
1065 $handler = $this->getHandler();
1066 $script = $this->getTransformScript();
1067 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
1068 // Use a script to transform on client request, if possible
1069 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1075 $normalisedParams = $params;
1076 $handler->normaliseParams( $this, $normalisedParams );
1078 $thumbName = $this->thumbName( $normalisedParams );
1079 $thumbUrl = $this->getThumbUrl( $thumbName );
1080 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1082 if ( $this->repo
) {
1083 // Defer rendering if a 404 handler is set up...
1084 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
1085 // XXX: Pass in the storage path even though we are not rendering anything
1086 // and the path is supposed to be an FS path. This is due to getScalerType()
1087 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1088 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1091 // Check if an up-to-date thumbnail already exists...
1092 wfDebug( __METHOD__
. ": Doing stat for $thumbPath\n" );
1093 if ( !( $flags & self
::RENDER_FORCE
) && $this->repo
->fileExists( $thumbPath ) ) {
1094 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
1095 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1096 // XXX: Pass in the storage path even though we are not rendering anything
1097 // and the path is supposed to be an FS path. This is due to getScalerType()
1098 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1099 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1100 $thumb->setStoragePath( $thumbPath );
1103 } elseif ( $flags & self
::RENDER_FORCE
) {
1104 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
1107 // If the backend is ready-only, don't keep generating thumbnails
1108 // only to return transformation errors, just return the error now.
1109 if ( $this->repo
->getReadOnlyReason() !== false ) {
1110 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1115 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1118 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1120 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1124 return is_object( $thumb ) ?
$thumb : false;
1128 * Generates a thumbnail according to the given parameters and saves it to storage
1129 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1130 * @param array $transformParams
1132 * @return bool|MediaTransformOutput
1134 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1135 global $wgIgnoreImageErrors;
1137 $stats = MediaWikiServices
::getInstance()->getStatsdDataFactory();
1139 $handler = $this->getHandler();
1141 $normalisedParams = $transformParams;
1142 $handler->normaliseParams( $this, $normalisedParams );
1144 $thumbName = $this->thumbName( $normalisedParams );
1145 $thumbUrl = $this->getThumbUrl( $thumbName );
1146 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1148 $tmpThumbPath = $tmpFile->getPath();
1150 if ( $handler->supportsBucketing() ) {
1151 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1154 $starttime = microtime( true );
1156 // Actually render the thumbnail...
1157 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1158 $tmpFile->bind( $thumb ); // keep alive with $thumb
1160 $statTiming = microtime( true ) - $starttime;
1161 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1163 if ( !$thumb ) { // bad params?
1165 } elseif ( $thumb->isError() ) { // transform error
1166 /** @var MediaTransformError $thumb */
1167 $this->lastError
= $thumb->toText();
1168 // Ignore errors if requested
1169 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
1170 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1172 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
1173 // Copy the thumbnail from the file system into storage...
1175 $starttime = microtime( true );
1177 $disposition = $this->getThumbDisposition( $thumbName );
1178 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1179 if ( $status->isOK() ) {
1180 $thumb->setStoragePath( $thumbPath );
1182 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1185 $statTiming = microtime( true ) - $starttime;
1186 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1188 // Give extensions a chance to do something with this thumbnail...
1189 Hooks
::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
1196 * Generates chained bucketed thumbnails if needed
1197 * @param array $params
1199 * @return bool Whether at least one bucket was generated
1201 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1203 ||
!isset( $params['physicalWidth'] )
1204 ||
!isset( $params['physicalHeight'] )
1209 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1211 if ( !$bucket ||
$bucket == $params['physicalWidth'] ) {
1215 $bucketPath = $this->getBucketThumbPath( $bucket );
1217 if ( $this->repo
->fileExists( $bucketPath ) ) {
1221 $starttime = microtime( true );
1223 $params['physicalWidth'] = $bucket;
1224 $params['width'] = $bucket;
1226 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1228 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1234 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1236 $buckettime = microtime( true ) - $starttime;
1238 if ( !$thumb ||
$thumb->isError() ) {
1242 $this->tmpBucketedThumbCache
[$bucket] = $tmpFile->getPath();
1243 // For the caching to work, we need to make the tmp file survive as long as
1244 // this object exists
1245 $tmpFile->bind( $this );
1247 MediaWikiServices
::getInstance()->getStatsdDataFactory()->timing(
1248 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1254 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1255 * @param array $params
1256 * @return array Source path and width/height of the source
1258 public function getThumbnailSource( $params ) {
1260 && $this->getHandler()->supportsBucketing()
1261 && isset( $params['physicalWidth'] )
1262 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1264 if ( $this->getWidth() != 0 ) {
1265 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1270 // Try to avoid reading from storage if the file was generated by this script
1271 if ( isset( $this->tmpBucketedThumbCache
[$bucket] ) ) {
1272 $tmpPath = $this->tmpBucketedThumbCache
[$bucket];
1274 if ( file_exists( $tmpPath ) ) {
1278 'height' => $bucketHeight
1283 $bucketPath = $this->getBucketThumbPath( $bucket );
1285 if ( $this->repo
->fileExists( $bucketPath ) ) {
1286 $fsFile = $this->repo
->getLocalReference( $bucketPath );
1290 'path' => $fsFile->getPath(),
1292 'height' => $bucketHeight
1298 // Thumbnailing a very large file could result in network saturation if
1299 // everyone does it at once.
1300 if ( $this->getSize() >= 1e7
) { // 10MB
1301 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1303 'doWork' => function () {
1304 return $this->getLocalRefPath();
1308 $srcPath = $work->execute();
1310 $srcPath = $this->getLocalRefPath();
1316 'width' => $this->getWidth(),
1317 'height' => $this->getHeight()
1322 * Returns the repo path of the thumb for a given bucket
1323 * @param int $bucket
1326 protected function getBucketThumbPath( $bucket ) {
1327 $thumbName = $this->getBucketThumbName( $bucket );
1328 return $this->getThumbPath( $thumbName );
1332 * Returns the name of the thumb for a given bucket
1333 * @param int $bucket
1336 protected function getBucketThumbName( $bucket ) {
1337 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1341 * Creates a temp FS file with the same extension and the thumbnail
1342 * @param string $thumbPath Thumbnail path
1343 * @return TempFSFile|null
1345 protected function makeTransformTmpFile( $thumbPath ) {
1346 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
1347 return TempFSFile
::factory( 'transform_', $thumbExt, wfTempDir() );
1351 * @param string $thumbName Thumbnail name
1352 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1353 * @return string Content-Disposition header value
1355 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1356 $fileName = $this->name
; // file name to suggest
1357 $thumbExt = FileBackend
::extensionFromPath( $thumbName );
1358 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1359 $fileName .= ".$thumbExt";
1362 return FileBackend
::makeContentDisposition( $dispositionType, $fileName );
1366 * Hook into transform() to allow migration of thumbnail files
1368 * Overridden by LocalFile
1369 * @param string $thumbName
1371 function migrateThumbFile( $thumbName ) {
1375 * Get a MediaHandler instance for this file
1377 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1378 * or false if none found
1380 function getHandler() {
1381 if ( !isset( $this->handler
) ) {
1382 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
1385 return $this->handler
;
1389 * Get a ThumbnailImage representing a file type icon
1391 * @return ThumbnailImage
1393 function iconThumb() {
1394 global $wgResourceBasePath, $IP;
1395 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1396 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1398 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1399 foreach ( $try as $icon ) {
1400 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1401 $params = [ 'width' => 120, 'height' => 120 ];
1403 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1411 * Get last thumbnailing error.
1415 function getLastError() {
1416 return $this->lastError
;
1420 * Get all thumbnail names previously generated for this file
1422 * Overridden by LocalFile
1425 function getThumbnails() {
1430 * Purge shared caches such as thumbnails and DB data caching
1432 * Overridden by LocalFile
1433 * @param array $options Options, which include:
1434 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1436 function purgeCache( $options = [] ) {
1440 * Purge the file description page, but don't go after
1441 * pages using the file. Use when modifying file history
1442 * but not the current data.
1444 function purgeDescription() {
1445 $title = $this->getTitle();
1447 $title->invalidateCache();
1448 $title->purgeSquid();
1453 * Purge metadata and all affected pages when the file is created,
1454 * deleted, or majorly updated.
1456 function purgeEverything() {
1457 // Delete thumbnails and refresh file metadata cache
1458 $this->purgeCache();
1459 $this->purgeDescription();
1461 // Purge cache of all pages using this file
1462 $title = $this->getTitle();
1464 DeferredUpdates
::addUpdate(
1465 new HTMLCacheUpdate( $title, 'imagelinks', 'file-purge' )
1471 * Return a fragment of the history of file.
1474 * @param int|null $limit Limit of rows to return
1475 * @param string|int|null $start Only revisions older than $start will be returned
1476 * @param string|int|null $end Only revisions newer than $end will be returned
1477 * @param bool $inc Include the endpoints of the time range
1481 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1486 * Return the history of this file, line by line. Starts with current version,
1487 * then old versions. Should return an object similar to an image/oldimage
1491 * Overridden in LocalFile
1494 public function nextHistoryLine() {
1499 * Reset the history pointer to the first element of the history.
1500 * Always call this function after using nextHistoryLine() to free db resources
1502 * Overridden in LocalFile.
1504 public function resetHistory() {
1508 * Get the filename hash component of the directory including trailing slash,
1510 * If the repository is not hashed, returns an empty string.
1514 function getHashPath() {
1515 if ( !isset( $this->hashPath
) ) {
1516 $this->assertRepoDefined();
1517 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1520 return $this->hashPath
;
1524 * Get the path of the file relative to the public zone root.
1525 * This function is overridden in OldLocalFile to be like getArchiveRel().
1530 return $this->getHashPath() . $this->getName();
1534 * Get the path of an archived file relative to the public zone root
1536 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1540 function getArchiveRel( $suffix = false ) {
1541 $path = 'archive/' . $this->getHashPath();
1542 if ( $suffix === false ) {
1543 $path = rtrim( $path, '/' );
1552 * Get the path, relative to the thumbnail zone root, of the
1553 * thumbnail directory or a particular file if $suffix is specified
1555 * @param bool|string $suffix If not false, the name of a thumbnail file
1558 function getThumbRel( $suffix = false ) {
1559 $path = $this->getRel();
1560 if ( $suffix !== false ) {
1561 $path .= '/' . $suffix;
1568 * Get urlencoded path of the file relative to the public zone root.
1569 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1573 function getUrlRel() {
1574 return $this->getHashPath() . rawurlencode( $this->getName() );
1578 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1579 * or a specific thumb if the $suffix is given.
1581 * @param string $archiveName The timestamped name of an archived image
1582 * @param bool|string $suffix If not false, the name of a thumbnail file
1585 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1586 $path = $this->getArchiveRel( $archiveName );
1587 if ( $suffix !== false ) {
1588 $path .= '/' . $suffix;
1595 * Get the path of the archived file.
1597 * @param bool|string $suffix If not false, the name of an archived file.
1600 function getArchivePath( $suffix = false ) {
1601 $this->assertRepoDefined();
1603 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1607 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1609 * @param string $archiveName The timestamped name of an archived image
1610 * @param bool|string $suffix If not false, the name of a thumbnail file
1613 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1614 $this->assertRepoDefined();
1616 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1617 $this->getArchiveThumbRel( $archiveName, $suffix );
1621 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1623 * @param bool|string $suffix If not false, the name of a thumbnail file
1626 function getThumbPath( $suffix = false ) {
1627 $this->assertRepoDefined();
1629 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1633 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1635 * @param bool|string $suffix If not false, the name of a media file
1638 function getTranscodedPath( $suffix = false ) {
1639 $this->assertRepoDefined();
1641 return $this->repo
->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1645 * Get the URL of the archive directory, or a particular file if $suffix is specified
1647 * @param bool|string $suffix If not false, the name of an archived file
1650 function getArchiveUrl( $suffix = false ) {
1651 $this->assertRepoDefined();
1652 $ext = $this->getExtension();
1653 $path = $this->repo
->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1654 if ( $suffix === false ) {
1655 $path = rtrim( $path, '/' );
1657 $path .= rawurlencode( $suffix );
1664 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1666 * @param string $archiveName The timestamped name of an archived image
1667 * @param bool|string $suffix If not false, the name of a thumbnail file
1670 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1671 $this->assertRepoDefined();
1672 $ext = $this->getExtension();
1673 $path = $this->repo
->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1674 $this->getHashPath() . rawurlencode( $archiveName );
1675 if ( $suffix !== false ) {
1676 $path .= '/' . rawurlencode( $suffix );
1683 * Get the URL of the zone directory, or a particular file if $suffix is specified
1685 * @param string $zone Name of requested zone
1686 * @param bool|string $suffix If not false, the name of a file in zone
1687 * @return string Path
1689 function getZoneUrl( $zone, $suffix = false ) {
1690 $this->assertRepoDefined();
1691 $ext = $this->getExtension();
1692 $path = $this->repo
->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1693 if ( $suffix !== false ) {
1694 $path .= '/' . rawurlencode( $suffix );
1701 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1703 * @param bool|string $suffix If not false, the name of a thumbnail file
1704 * @return string Path
1706 function getThumbUrl( $suffix = false ) {
1707 return $this->getZoneUrl( 'thumb', $suffix );
1711 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1713 * @param bool|string $suffix If not false, the name of a media file
1714 * @return string Path
1716 function getTranscodedUrl( $suffix = false ) {
1717 return $this->getZoneUrl( 'transcoded', $suffix );
1721 * Get the public zone virtual URL for a current version source file
1723 * @param bool|string $suffix If not false, the name of a thumbnail file
1726 function getVirtualUrl( $suffix = false ) {
1727 $this->assertRepoDefined();
1728 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1729 if ( $suffix !== false ) {
1730 $path .= '/' . rawurlencode( $suffix );
1737 * Get the public zone virtual URL for an archived version source file
1739 * @param bool|string $suffix If not false, the name of a thumbnail file
1742 function getArchiveVirtualUrl( $suffix = false ) {
1743 $this->assertRepoDefined();
1744 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1745 if ( $suffix === false ) {
1746 $path = rtrim( $path, '/' );
1748 $path .= rawurlencode( $suffix );
1755 * Get the virtual URL for a thumbnail file or directory
1757 * @param bool|string $suffix If not false, the name of a thumbnail file
1760 function getThumbVirtualUrl( $suffix = false ) {
1761 $this->assertRepoDefined();
1762 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1763 if ( $suffix !== false ) {
1764 $path .= '/' . rawurlencode( $suffix );
1773 function isHashed() {
1774 $this->assertRepoDefined();
1776 return (bool)$this->repo
->getHashLevels();
1780 * @throws MWException
1782 function readOnlyError() {
1783 throw new MWException( static::class . ': write operations are not supported' );
1787 * Record a file upload in the upload log and the image table
1789 * Overridden by LocalFile
1790 * @param string $oldver
1791 * @param string $desc
1792 * @param string $license
1793 * @param string $copyStatus
1794 * @param string $source
1795 * @param bool $watch
1796 * @param string|bool $timestamp
1797 * @param null|User $user User object or null to use $wgUser
1799 * @throws MWException
1801 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1802 $watch = false, $timestamp = false, User
$user = null
1804 $this->readOnlyError();
1808 * Move or copy a file to its public location. If a file exists at the
1809 * destination, move it to an archive. Returns a Status object with
1810 * the archive name in the "value" member on success.
1812 * The archive name should be passed through to recordUpload for database
1815 * Options to $options include:
1816 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1818 * @param string|FSFile $src Local filesystem path to the source image
1819 * @param int $flags A bitwise combination of:
1820 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1821 * @param array $options Optional additional parameters
1822 * @return Status On success, the value member contains the
1823 * archive name, or an empty string if it was a new file.
1826 * Overridden by LocalFile
1828 function publish( $src, $flags = 0, array $options = [] ) {
1829 $this->readOnlyError();
1833 * @param bool|IContextSource $context Context to use (optional)
1836 function formatMetadata( $context = false ) {
1837 if ( !$this->getHandler() ) {
1841 return $this->getHandler()->formatMetadata( $this, $context );
1845 * Returns true if the file comes from the local file repository.
1849 function isLocal() {
1850 return $this->repo
&& $this->repo
->isLocal();
1854 * Returns the name of the repository.
1858 function getRepoName() {
1859 return $this->repo ?
$this->repo
->getName() : 'unknown';
1863 * Returns the repository
1865 * @return FileRepo|LocalRepo|bool
1867 function getRepo() {
1872 * Returns true if the image is an old version
1882 * Is this file a "deleted" file in a private archive?
1885 * @param int $field One of DELETED_* bitfield constants
1888 function isDeleted( $field ) {
1893 * Return the deletion bitfield
1897 function getVisibility() {
1902 * Was this file ever deleted from the wiki?
1906 function wasDeleted() {
1907 $title = $this->getTitle();
1909 return $title && $title->isDeletedQuick();
1913 * Move file to the new title
1915 * Move current, old version and all thumbnails
1916 * to the new filename. Old file is deleted.
1918 * Cache purging is done; checks for validity
1919 * and logging are caller's responsibility
1921 * @param Title $target New file name
1924 function move( $target ) {
1925 $this->readOnlyError();
1929 * Delete all versions of the file.
1931 * Moves the files into an archive directory (or deletes them)
1932 * and removes the database rows.
1934 * Cache purging is done; logging is caller's responsibility.
1936 * @param string $reason
1937 * @param bool $suppress Hide content from sysops?
1938 * @param User|null $user
1941 * Overridden by LocalFile
1943 function delete( $reason, $suppress = false, $user = null ) {
1944 $this->readOnlyError();
1948 * Restore all or specified deleted revisions to the given file.
1949 * Permissions and logging are left to the caller.
1951 * May throw database exceptions on error.
1953 * @param array $versions Set of record ids of deleted items to restore,
1954 * or empty to restore all revisions.
1955 * @param bool $unsuppress Remove restrictions on content upon restoration?
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 = AtEase
::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() {