3 * Handler for SVG images.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Wikimedia\ScopedCallback
;
26 * Handler for SVG images.
30 class SvgHandler
extends ImageHandler
{
31 const SVG_METADATA_VERSION
= 2;
33 /** @var array A list of metadata tags that can be converted
34 * to the commonly used exif tags. This allows messages
35 * to be reused, and consistent tag names for {{#formatmetadata:..}}
37 private static $metaConversion = [
38 'originalwidth' => 'ImageWidth',
39 'originalheight' => 'ImageLength',
40 'description' => 'ImageDescription',
41 'title' => 'ObjectName',
44 function isEnabled() {
45 global $wgSVGConverters, $wgSVGConverter;
46 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
47 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
55 public function mustRender( $file ) {
59 function isVectorized( $file ) {
67 function isAnimatedImage( $file ) {
68 # @todo Detect animated SVGs
69 $metadata = $file->getMetadata();
71 $metadata = $this->unpackMetadata( $metadata );
72 if ( isset( $metadata['animated'] ) ) {
73 return $metadata['animated'];
81 * Which languages (systemLanguage attribute) is supported.
83 * @note This list is not guaranteed to be exhaustive.
84 * To avoid OOM errors, we only look at first bit of a file.
85 * Thus all languages on this list are present in the file,
86 * but its possible for the file to have a language not on
90 * @return array Array of language codes, or empty if no language switching supported.
92 public function getAvailableLanguages( File
$file ) {
93 $metadata = $file->getMetadata();
96 $metadata = $this->unpackMetadata( $metadata );
97 if ( isset( $metadata['translations'] ) ) {
98 foreach ( $metadata['translations'] as $lang => $langType ) {
99 if ( $langType === SVGReader
::LANG_FULL_MATCH
) {
100 $langList[] = strtolower( $lang );
105 return array_unique( $langList );
109 * SVG's systemLanguage matching rules state:
110 * 'The `systemLanguage` attribute ... [e]valuates to "true" if one of the languages indicated
111 * by user preferences exactly equals one of the languages given in the value of this parameter,
112 * or if one of the languages indicated by user preferences exactly equals a prefix of one of
113 * the languages given in the value of this parameter such that the first tag character
114 * following the prefix is "-".'
116 * Return the first element of $svgLanguages that matches $userPreferredLanguage
118 * @see https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
119 * @param string $userPreferredLanguage
120 * @param array $svgLanguages
121 * @return string|null
123 public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
124 foreach ( $svgLanguages as $svgLang ) {
125 if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
128 $trimmedSvgLang = $svgLang;
129 while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
130 $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
131 if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
140 * What language to render file in if none selected
142 * @param File $file Language code
145 public function getDefaultRenderLanguage( File
$file ) {
150 * We do not support making animated svg thumbnails
154 function canAnimateThumbnail( $file ) {
160 * @param array &$params
163 function normaliseParams( $image, &$params ) {
164 global $wgSVGMaxSize;
165 if ( !parent
::normaliseParams( $image, $params ) ) {
168 # Don't make an image bigger than wgMaxSVGSize on the smaller side
169 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
170 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
171 $srcWidth = $image->getWidth( $params['page'] );
172 $srcHeight = $image->getHeight( $params['page'] );
173 $params['physicalWidth'] = $wgSVGMaxSize;
174 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
177 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
178 $srcWidth = $image->getWidth( $params['page'] );
179 $srcHeight = $image->getHeight( $params['page'] );
180 $params['physicalWidth'] = File
::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
181 $params['physicalHeight'] = $wgSVGMaxSize;
190 * @param string $dstPath
191 * @param string $dstUrl
192 * @param array $params
194 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
196 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
197 if ( !$this->normaliseParams( $image, $params ) ) {
198 return new TransformParameterError( $params );
200 $clientWidth = $params['width'];
201 $clientHeight = $params['height'];
202 $physicalWidth = $params['physicalWidth'];
203 $physicalHeight = $params['physicalHeight'];
204 $lang = $params['lang'] ??
$this->getDefaultRenderLanguage( $image );
206 if ( $flags & self
::TRANSFORM_LATER
) {
207 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
210 $metadata = $this->unpackMetadata( $image->getMetadata() );
211 if ( isset( $metadata['error'] ) ) { // sanity check
212 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
214 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
217 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
218 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
219 wfMessage( 'thumbnail_dest_directory' ) );
222 $srcPath = $image->getLocalRefPath();
223 if ( $srcPath === false ) { // Failed to get local copy
224 wfDebugLog( 'thumbnail',
225 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
226 wfHostname(), $image->getName() ) );
228 return new MediaTransformError( 'thumbnail_error',
229 $params['width'], $params['height'],
230 wfMessage( 'filemissing' )
234 // Make a temp dir with a symlink to the local copy in it.
235 // This plays well with rsvg-convert policy for external entities.
236 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
237 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
238 $lnPath = "$tmpDir/" . basename( $srcPath );
239 $ok = mkdir( $tmpDir, 0771 );
241 wfDebugLog( 'thumbnail',
242 sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
243 wfHostname(), $tmpDir ) );
244 return new MediaTransformError( 'thumbnail_error',
245 $params['width'], $params['height'],
246 wfMessage( 'thumbnail-temp-create' )->text()
249 $ok = symlink( $srcPath, $lnPath );
250 /** @noinspection PhpUnusedLocalVariableInspection */
251 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
252 Wikimedia\
suppressWarnings();
255 Wikimedia\restoreWarnings
();
258 wfDebugLog( 'thumbnail',
259 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
260 wfHostname(), $lnPath, $srcPath ) );
261 return new MediaTransformError( 'thumbnail_error',
262 $params['width'], $params['height'],
263 wfMessage( 'thumbnail-temp-create' )
267 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
268 if ( $status === true ) {
269 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
271 return $status; // MediaTransformError
276 * Transform an SVG file to PNG
277 * This function can be called outside of thumbnail contexts
278 * @param string $srcPath
279 * @param string $dstPath
280 * @param string $width
281 * @param string $height
282 * @param bool|string $lang Language code of the language to render the SVG in
283 * @throws MWException
284 * @return bool|MediaTransformError
286 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
287 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
290 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
291 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
292 // This is a PHP callable
293 $func = $wgSVGConverters[$wgSVGConverter][0];
294 if ( !is_callable( $func ) ) {
295 throw new MWException( "$func is not callable" );
297 $err = $func( $srcPath,
302 ...array_slice( $wgSVGConverters[$wgSVGConverter], 1 )
304 $retval = (bool)$err;
308 [ '$path/', '$width', '$height', '$input', '$output' ],
309 [ $wgSVGConverterPath ?
wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
312 wfEscapeShellArg( $srcPath ),
313 wfEscapeShellArg( $dstPath ) ],
314 $wgSVGConverters[$wgSVGConverter]
318 if ( $lang !== false ) {
319 $env['LANG'] = $lang;
322 wfDebug( __METHOD__
. ": $cmd\n" );
323 $err = wfShellExecWithStderr( $cmd, $retval, $env );
326 $removed = $this->removeBadFile( $dstPath, $retval );
327 if ( $retval != 0 ||
$removed ) {
328 $this->logErrorForExternalProcess( $retval, $err, $cmd );
329 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
335 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
336 $im = new Imagick( $srcPath );
337 $im->setImageFormat( 'png' );
338 $im->setBackgroundColor( 'transparent' );
339 $im->setImageDepth( 8 );
341 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
342 return 'Could not resize image';
344 if ( !$im->writeImage( $dstPath ) ) {
345 return "Could not write to $dstPath";
350 * @param File|FSFile $file
351 * @param string $path Unused
352 * @param bool|array $metadata
355 function getImageSize( $file, $path, $metadata = false ) {
356 if ( $metadata === false && $file instanceof File
) {
357 $metadata = $file->getMetadata();
359 $metadata = $this->unpackMetadata( $metadata );
361 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
362 return [ $metadata['width'], $metadata['height'], 'SVG',
363 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" ];
365 return [ 0, 0, 'SVG', "width=\"0\" height=\"0\"" ];
369 function getThumbType( $ext, $mime, $params = null ) {
370 return [ 'png', 'image/png' ];
374 * Subtitle for the image. Different from the base
375 * class so it can be denoted that SVG's have
376 * a "nominal" resolution, and not a fixed one,
377 * as well as so animation can be denoted.
382 function getLongDesc( $file ) {
385 $metadata = $this->unpackMetadata( $file->getMetadata() );
386 if ( isset( $metadata['error'] ) ) {
387 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
390 $size = $wgLang->formatSize( $file->getSize() );
392 if ( $this->isAnimatedImage( $file ) ) {
393 $msg = wfMessage( 'svg-long-desc-animated' );
395 $msg = wfMessage( 'svg-long-desc' );
398 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
400 return $msg->parse();
404 * @param File|FSFile $file
405 * @param string $filename
406 * @return string Serialised metadata
408 function getMetadata( $file, $filename ) {
409 $metadata = [ 'version' => self
::SVG_METADATA_VERSION
];
411 $metadata +
= SVGMetadataExtractor
::getMetadata( $filename );
412 } catch ( Exception
$e ) { // @todo SVG specific exceptions
413 // File not found, broken, etc.
414 $metadata['error'] = [
415 'message' => $e->getMessage(),
416 'code' => $e->getCode()
418 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
421 return serialize( $metadata );
424 function unpackMetadata( $metadata ) {
425 Wikimedia\
suppressWarnings();
426 $unser = unserialize( $metadata );
427 Wikimedia\restoreWarnings
();
428 if ( isset( $unser['version'] ) && $unser['version'] == self
::SVG_METADATA_VERSION
) {
435 function getMetadataType( $image ) {
439 function isMetadataValid( $image, $metadata ) {
440 $meta = $this->unpackMetadata( $metadata );
441 if ( $meta === false ) {
442 return self
::METADATA_BAD
;
444 if ( !isset( $meta['originalWidth'] ) ) {
445 // Old but compatible
446 return self
::METADATA_COMPATIBLE
;
449 return self
::METADATA_GOOD
;
452 protected function visibleMetadataFields() {
453 $fields = [ 'objectname', 'imagedescription' ];
460 * @param bool|IContextSource $context Context to use (optional)
463 function formatMetadata( $file, $context = false ) {
468 $metadata = $file->getMetadata();
472 $metadata = $this->unpackMetadata( $metadata );
473 if ( !$metadata ||
isset( $metadata['error'] ) ) {
477 /* @todo Add a formatter
478 $format = new FormatSVG( $metadata );
479 $formatted = $format->getFormattedData();
482 // Sort fields into visible and collapsed
483 $visibleFields = $this->visibleMetadataFields();
486 foreach ( $metadata as $name => $value ) {
487 $tag = strtolower( $name );
488 if ( isset( self
::$metaConversion[$tag] ) ) {
489 $tag = strtolower( self
::$metaConversion[$tag] );
491 // Do not output other metadata not in list
495 self
::addMeta( $result,
496 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
503 return $showMeta ?
$result : false;
507 * @param string $name Parameter name
508 * @param mixed $value Parameter value
509 * @return bool Validity
511 public function validateParam( $name, $value ) {
512 if ( in_array( $name, [ 'width', 'height' ] ) ) {
513 // Reject negative heights, widths
514 return ( $value > 0 );
515 } elseif ( $name == 'lang' ) {
517 if ( $value === '' ||
!Language
::isValidCode( $value ) ) {
524 // Only lang, width and height are acceptable keys
529 * @param array $params Name=>value pairs of parameters
530 * @return string Filename to use
532 public function makeParamString( $params ) {
534 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
535 $lang = 'lang' . strtolower( $params['lang'] ) . '-';
537 if ( !isset( $params['width'] ) ) {
541 return "$lang{$params['width']}px";
544 public function parseParamString( $str ) {
546 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
547 return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
548 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
549 return [ 'width' => $m[1], 'lang' => 'en' ];
555 public function getParamMap() {
556 return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
560 * @param array $params
563 function getScriptParams( $params ) {
564 $scriptParams = [ 'width' => $params['width'] ];
565 if ( isset( $params['lang'] ) ) {
566 $scriptParams['lang'] = $params['lang'];
569 return $scriptParams;
572 public function getCommonMetaArray( File
$file ) {
573 $metadata = $file->getMetadata();
577 $metadata = $this->unpackMetadata( $metadata );
578 if ( !$metadata ||
isset( $metadata['error'] ) ) {
582 foreach ( $metadata as $name => $value ) {
583 $tag = strtolower( $name );
584 if ( $tag === 'originalwidth' ||
$tag === 'originalheight' ) {
585 // Skip these. In the exif metadata stuff, it is assumed these
586 // are measured in px, which is not the case here.
589 if ( isset( self
::$metaConversion[$tag] ) ) {
590 $tag = self
::$metaConversion[$tag];
591 $stdMetadata[$tag] = $value;