27 use Wikimedia\AtEase\AtEase;
28 use Wikimedia\RequestTimeout\TimeoutException;
29 use Wikimedia\ScopedCallback;
44 'originalwidth' =>
'ImageWidth',
45 'originalheight' =>
'ImageLength',
46 'description' =>
'ImageDescription',
47 'title' =>
'ObjectName',
51 $svgConverters = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverters );
52 $svgConverter = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverter );
53 if ( !isset( $svgConverters[$svgConverter] ) ) {
54 wfDebug(
"\$wgSVGConverter is invalid, disabling SVG rendering." );
75 # @todo Detect animated SVGs
77 if ( isset( $metadata[
'animated'] ) ) {
78 return $metadata[
'animated'];
99 if ( isset( $metadata[
'translations'] ) ) {
100 foreach ( $metadata[
'translations'] as
$lang => $langType ) {
102 $langList[] = strtolower(
$lang );
106 return array_unique( $langList );
125 foreach ( $svgLanguages as $svgLang ) {
126 if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
129 $trimmedSvgLang = $svgLang;
130 while ( strpos( $trimmedSvgLang,
'-' ) !==
false ) {
131 $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang,
'-' ) );
132 if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
147 return $params[
'lang'] ?? $params[
'targetlang'] ??
'en';
175 if ( parent::normaliseParams( $image, $params ) ) {
193 $svgMaxSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGMaxSize );
195 # Don't make an image bigger than wgMaxSVGSize on the smaller side
196 if ( $params[
'physicalWidth'] <= $params[
'physicalHeight'] ) {
197 if ( $params[
'physicalWidth'] > $svgMaxSize ) {
198 $srcWidth = $image->getWidth( $params[
'page'] );
199 $srcHeight = $image->getHeight( $params[
'page'] );
200 $params[
'physicalWidth'] = $svgMaxSize;
201 $params[
'physicalHeight'] =
File::scaleHeight( $srcWidth, $srcHeight, $svgMaxSize );
203 } elseif ( $params[
'physicalHeight'] > $svgMaxSize ) {
204 $srcWidth = $image->getWidth( $params[
'page'] );
205 $srcHeight = $image->getHeight( $params[
'page'] );
206 $params[
'physicalWidth'] =
File::scaleHeight( $srcHeight, $srcWidth, $svgMaxSize );
207 $params[
'physicalHeight'] = $svgMaxSize;
211 if ( isset( $params[
'targetlang'] ) && !$image->getMatchedLanguage( $params[
'targetlang'] ) ) {
212 unset( $params[
'targetlang'] );
226 public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
230 $clientWidth = $params[
'width'];
231 $clientHeight = $params[
'height'];
232 $physicalWidth = $params[
'physicalWidth'];
233 $physicalHeight = $params[
'physicalHeight'];
236 if ( $flags & self::TRANSFORM_LATER ) {
241 if ( isset( $metadata[
'error'] ) ) {
242 $err =
wfMessage(
'svg-long-error', $metadata[
'error'][
'message'] );
249 wfMessage(
'thumbnail_dest_directory' ) );
252 $srcPath = $image->getLocalRefPath();
253 if ( $srcPath ===
false ) {
255 sprintf(
'Thumbnail failed on %s: could not get local copy of "%s"',
259 $params[
'width'], $params[
'height'],
268 $lnPath =
"$tmpDir/" . basename( $srcPath );
269 $ok = mkdir( $tmpDir, 0771 );
272 sprintf(
'Thumbnail failed on %s: could not create temporary directory %s',
275 $params[
'width'], $params[
'height'],
276 wfMessage(
'thumbnail-temp-create' )->text()
279 $ok = symlink( $srcPath, $lnPath );
281 $cleaner =
new ScopedCallback(
static function () use ( $tmpDir, $lnPath ) {
282 AtEase::suppressWarnings();
285 AtEase::restoreWarnings();
289 $ok = copy( $srcPath, $lnPath );
293 sprintf(
'Thumbnail failed on %s: could not link %s to %s',
296 $params[
'width'], $params[
'height'],
301 $status = $this->
rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight,
$lang );
302 if ( $status ===
true ) {
320 public function rasterize( $srcPath, $dstPath, $width, $height,
$lang =
false ) {
321 $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
322 $svgConverters = $mainConfig->get( MainConfigNames::SVGConverters );
323 $svgConverter = $mainConfig->get( MainConfigNames::SVGConverter );
324 $svgConverterPath = $mainConfig->get( MainConfigNames::SVGConverterPath );
327 if ( isset( $svgConverters[$svgConverter] ) ) {
328 if ( is_array( $svgConverters[$svgConverter] ) ) {
330 $func = $svgConverters[$svgConverter][0];
331 if ( !is_callable( $func ) ) {
334 $err = $func( $srcPath,
339 ...array_slice( $svgConverters[$svgConverter], 1 )
341 $retval = (bool)$err;
345 [
'$path/',
'$width',
'$height',
'$input',
'$output' ],
346 [ $svgConverterPath ? Shell::escape(
"{$svgConverterPath}/" ) :
"",
349 Shell::escape( $srcPath ),
350 Shell::escape( $dstPath ) ],
351 $svgConverters[$svgConverter]
355 if (
$lang !==
false ) {
356 $env[
'LANG'] =
$lang;
359 wfDebug( __METHOD__ .
": $cmd" );
365 if ( $retval != 0 || $removed ) {
376 $im =
new Imagick( $srcPath );
377 $im->setBackgroundColor(
'transparent' );
378 $im->readImage( $srcPath );
379 $im->setImageFormat(
'png' );
380 $im->setImageDepth( 8 );
382 if ( !$im->thumbnailImage( intval( $width ), intval( $height ),
false ) ) {
383 return 'Could not resize image';
385 if ( !$im->writeImage( $dstPath ) ) {
386 return "Could not write to $dstPath";
391 return [
'png',
'image/png' ];
405 if ( isset( $metadata[
'error'] ) ) {
406 return wfMessage(
'svg-long-error', $metadata[
'error'][
'message'] )->text();
410 $msg =
wfMessage(
'svg-long-desc-animated' );
415 return $msg->numParams(
$file->getWidth(),
$file->getHeight() )->sizeParams(
$file->getSize() )->parse();
428 $metadata += $svgReader->getMetadata();
429 }
catch ( TimeoutException $e ) {
431 }
catch ( Exception $e ) {
433 $metadata[
'error'] = [
434 'message' => $e->getMessage(),
435 'code' => $e->getCode()
437 wfDebug( __METHOD__ .
': ' . $e->getMessage() );
441 'width' => $metadata[
'width'] ?? 0,
442 'height' => $metadata[
'height'] ?? 0,
443 'metadata' => $metadata
448 if ( isset( $unser[
'version'] ) && $unser[
'version'] == self::SVG_METADATA_VERSION ) {
464 if ( !isset( $meta[
'originalWidth'] ) ) {
473 $fields = [
'objectname',
'imagedescription' ];
489 if ( !$metadata || isset( $metadata[
'error'] ) ) {
502 foreach ( $metadata as $name => $value ) {
503 $tag = strtolower( $name );
504 if ( isset( self::$metaConversion[$tag] ) ) {
505 $tag = strtolower( self::$metaConversion[$tag] );
512 in_array( $tag, $visibleFields ) ?
'visible' :
'collapsed',
519 return $showMeta ? $result :
false;
528 if ( in_array( $name, [
'width',
'height' ] ) ) {
530 return ( $value > 0 );
531 } elseif ( $name ==
'lang' ) {
534 || !MediaWikiServices::getInstance()->getLanguageNameUtils()
535 ->isValidCode( $value )
554 if ( $code !==
'en' ) {
555 $lang =
'lang' . strtolower( $code ) .
'-';
557 if ( !isset( $params[
'width'] ) ) {
561 return "$lang{$params['width']}px";
566 if ( preg_match(
'/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
567 return [
'width' => array_pop( $m ),
'lang' => $m[1] ];
568 } elseif ( preg_match(
'/^(\d+)px$/', $str, $m ) ) {
569 return [
'width' => $m[1],
'lang' =>
'en' ];
576 return [
'img_lang' =>
'lang',
'img_width' =>
'width' ];
584 $scriptParams = [
'width' => $params[
'width'] ];
585 if ( isset( $params[
'lang'] ) ) {
586 $scriptParams[
'lang'] = $params[
'lang'];
589 return $scriptParams;
594 if ( !$metadata || isset( $metadata[
'error'] ) ) {
598 foreach ( $metadata as $name => $value ) {
599 $tag = strtolower( $name );
600 if ( $tag ===
'originalwidth' || $tag ===
'originalheight' ) {
605 if ( isset( self::$metaConversion[$tag] ) ) {
606 $tag = self::$metaConversion[$tag];
607 $stdMetadata[$tag] = $value;
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Implements some public methods and some protected utility functions which are required by multiple ch...
getMetadataArray()
Get the unserialized handler-specific metadata STUB.
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Media handler abstract base class for images.
A class containing constants representing the names of configuration variables.
validateParam( $name, $value)
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
normaliseParams( $image, &$params)
formatMetadata( $file, $context=false)
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
getScriptParams( $params)
makeParamString( $params)
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
static array $metaConversion
A list of metadata tags that can be converted to the commonly used exif tags.
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
validateMetadata( $unser)
getLanguageFromParams(array $params)
Determines render language from image parameters.
getAvailableLanguages(File $file)
Which languages (systemLanguage attribute) is supported.
getLongDesc( $file)
Subtitle for the image.
normaliseParamsInternal( $image, $params)
Code taken out of normaliseParams() for testability.
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
getDefaultRenderLanguage(File $file)
What language to render file in if none selected.
rasterize( $srcPath, $dstPath, $width, $height, $lang=false)
Transform an SVG file to PNG This function can be called outside of thumbnail contexts.
getSizeAndMetadata( $state, $filename)
isEnabled()
False if the handler is disabled for all files.
canAnimateThumbnail( $file)
We do not support making animated svg thumbnails.
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
static rasterizeImagickExt( $srcPath, $dstPath, $width, $height)
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
getMatchedLanguage( $userPreferredLanguage, array $svgLanguages)
SVG's systemLanguage matching rules state: 'The systemLanguage attribute ...
const SVG_METADATA_VERSION
getParamMap()
Get an associative array mapping magic word IDs to parameter names.Will be used by the parser to iden...
Media transform output for images.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
if(!is_readable( $file)) $ext
if(!isset( $args[0])) $lang