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
) {
109 * What language to render file in if none selected.
112 * @return string Language code.
114 public function getDefaultRenderLanguage( File
$file ) {
119 * We do not support making animated svg thumbnails
123 function canAnimateThumbnail( $file ) {
129 * @param array $params
132 function normaliseParams( $image, &$params ) {
133 global $wgSVGMaxSize;
134 if ( !parent
::normaliseParams( $image, $params ) ) {
137 # Don't make an image bigger than wgMaxSVGSize on the smaller side
138 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
139 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
140 $srcWidth = $image->getWidth( $params['page'] );
141 $srcHeight = $image->getHeight( $params['page'] );
142 $params['physicalWidth'] = $wgSVGMaxSize;
143 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
146 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
147 $srcWidth = $image->getWidth( $params['page'] );
148 $srcHeight = $image->getHeight( $params['page'] );
149 $params['physicalWidth'] = File
::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
150 $params['physicalHeight'] = $wgSVGMaxSize;
159 * @param string $dstPath
160 * @param string $dstUrl
161 * @param array $params
163 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
165 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
166 if ( !$this->normaliseParams( $image, $params ) ) {
167 return new TransformParameterError( $params );
169 $clientWidth = $params['width'];
170 $clientHeight = $params['height'];
171 $physicalWidth = $params['physicalWidth'];
172 $physicalHeight = $params['physicalHeight'];
173 $lang = isset( $params['lang'] ) ?
$params['lang'] : $this->getDefaultRenderLanguage( $image );
175 if ( $flags & self
::TRANSFORM_LATER
) {
176 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
179 $metadata = $this->unpackMetadata( $image->getMetadata() );
180 if ( isset( $metadata['error'] ) ) { // sanity check
181 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
183 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
186 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
187 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
188 wfMessage( 'thumbnail_dest_directory' ) );
191 $srcPath = $image->getLocalRefPath();
192 if ( $srcPath === false ) { // Failed to get local copy
193 wfDebugLog( 'thumbnail',
194 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
195 wfHostname(), $image->getName() ) );
197 return new MediaTransformError( 'thumbnail_error',
198 $params['width'], $params['height'],
199 wfMessage( 'filemissing' )
203 // Make a temp dir with a symlink to the local copy in it.
204 // This plays well with rsvg-convert policy for external entities.
205 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
206 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
207 $lnPath = "$tmpDir/" . basename( $srcPath );
208 $ok = mkdir( $tmpDir, 0771 ) && symlink( $srcPath, $lnPath );
209 /** @noinspection PhpUnusedLocalVariableInspection */
210 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
211 MediaWiki\
suppressWarnings();
214 MediaWiki\restoreWarnings
();
217 wfDebugLog( 'thumbnail',
218 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
219 wfHostname(), $lnPath, $srcPath ) );
220 return new MediaTransformError( 'thumbnail_error',
221 $params['width'], $params['height'],
222 wfMessage( 'thumbnail-temp-create' )
226 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
227 if ( $status === true ) {
228 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
230 return $status; // MediaTransformError
235 * Transform an SVG file to PNG
236 * This function can be called outside of thumbnail contexts
237 * @param string $srcPath
238 * @param string $dstPath
239 * @param string $width
240 * @param string $height
241 * @param bool|string $lang Language code of the language to render the SVG in
242 * @throws MWException
243 * @return bool|MediaTransformError
245 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
246 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
249 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
250 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
251 // This is a PHP callable
252 $func = $wgSVGConverters[$wgSVGConverter][0];
253 $args = array_merge( [ $srcPath, $dstPath, $width, $height, $lang ],
254 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
255 if ( !is_callable( $func ) ) {
256 throw new MWException( "$func is not callable" );
258 $err = call_user_func_array( $func, $args );
259 $retval = (bool)$err;
263 [ '$path/', '$width', '$height', '$input', '$output' ],
264 [ $wgSVGConverterPath ?
wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
267 wfEscapeShellArg( $srcPath ),
268 wfEscapeShellArg( $dstPath ) ],
269 $wgSVGConverters[$wgSVGConverter]
273 if ( $lang !== false ) {
274 $env['LANG'] = $lang;
277 wfDebug( __METHOD__
. ": $cmd\n" );
278 $err = wfShellExecWithStderr( $cmd, $retval, $env );
281 $removed = $this->removeBadFile( $dstPath, $retval );
282 if ( $retval != 0 ||
$removed ) {
283 $this->logErrorForExternalProcess( $retval, $err, $cmd );
284 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
290 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
291 $im = new Imagick( $srcPath );
292 $im->setImageFormat( 'png' );
293 $im->setBackgroundColor( 'transparent' );
294 $im->setImageDepth( 8 );
296 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
297 return 'Could not resize image';
299 if ( !$im->writeImage( $dstPath ) ) {
300 return "Could not write to $dstPath";
305 * @param File|FSFile $file
306 * @param string $path Unused
307 * @param bool|array $metadata
310 function getImageSize( $file, $path, $metadata = false ) {
311 if ( $metadata === false && $file instanceof File
) {
312 $metadata = $file->getMetadata();
314 $metadata = $this->unpackMetadata( $metadata );
316 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
317 return [ $metadata['width'], $metadata['height'], 'SVG',
318 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" ];
320 return [ 0, 0, 'SVG', "width=\"0\" height=\"0\"" ];
324 function getThumbType( $ext, $mime, $params = null ) {
325 return [ 'png', 'image/png' ];
329 * Subtitle for the image. Different from the base
330 * class so it can be denoted that SVG's have
331 * a "nominal" resolution, and not a fixed one,
332 * as well as so animation can be denoted.
337 function getLongDesc( $file ) {
340 $metadata = $this->unpackMetadata( $file->getMetadata() );
341 if ( isset( $metadata['error'] ) ) {
342 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
345 $size = $wgLang->formatSize( $file->getSize() );
347 if ( $this->isAnimatedImage( $file ) ) {
348 $msg = wfMessage( 'svg-long-desc-animated' );
350 $msg = wfMessage( 'svg-long-desc' );
353 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
355 return $msg->parse();
359 * @param File|FSFile $file
360 * @param string $filename
361 * @return string Serialised metadata
363 function getMetadata( $file, $filename ) {
364 $metadata = [ 'version' => self
::SVG_METADATA_VERSION
];
366 $metadata +
= SVGMetadataExtractor
::getMetadata( $filename );
367 } catch ( Exception
$e ) { // @todo SVG specific exceptions
368 // File not found, broken, etc.
369 $metadata['error'] = [
370 'message' => $e->getMessage(),
371 'code' => $e->getCode()
373 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
376 return serialize( $metadata );
379 function unpackMetadata( $metadata ) {
380 MediaWiki\
suppressWarnings();
381 $unser = unserialize( $metadata );
382 MediaWiki\restoreWarnings
();
383 if ( isset( $unser['version'] ) && $unser['version'] == self
::SVG_METADATA_VERSION
) {
390 function getMetadataType( $image ) {
394 function isMetadataValid( $image, $metadata ) {
395 $meta = $this->unpackMetadata( $metadata );
396 if ( $meta === false ) {
397 return self
::METADATA_BAD
;
399 if ( !isset( $meta['originalWidth'] ) ) {
400 // Old but compatible
401 return self
::METADATA_COMPATIBLE
;
404 return self
::METADATA_GOOD
;
407 protected function visibleMetadataFields() {
408 $fields = [ 'objectname', 'imagedescription' ];
415 * @param bool|IContextSource $context Context to use (optional)
418 function formatMetadata( $file, $context = false ) {
423 $metadata = $file->getMetadata();
427 $metadata = $this->unpackMetadata( $metadata );
428 if ( !$metadata ||
isset( $metadata['error'] ) ) {
432 /* @todo Add a formatter
433 $format = new FormatSVG( $metadata );
434 $formatted = $format->getFormattedData();
437 // Sort fields into visible and collapsed
438 $visibleFields = $this->visibleMetadataFields();
441 foreach ( $metadata as $name => $value ) {
442 $tag = strtolower( $name );
443 if ( isset( self
::$metaConversion[$tag] ) ) {
444 $tag = strtolower( self
::$metaConversion[$tag] );
446 // Do not output other metadata not in list
450 self
::addMeta( $result,
451 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
458 return $showMeta ?
$result : false;
462 * @param string $name Parameter name
463 * @param mixed $value Parameter value
464 * @return bool Validity
466 public function validateParam( $name, $value ) {
467 if ( in_array( $name, [ 'width', 'height' ] ) ) {
468 // Reject negative heights, widths
469 return ( $value > 0 );
470 } elseif ( $name == 'lang' ) {
472 if ( $value === '' ||
!Language
::isValidBuiltInCode( $value ) ) {
473 wfDebug( "Invalid user language code\n" );
481 // Only lang, width and height are acceptable keys
486 * @param array $params Name=>value pairs of parameters
487 * @return string Filename to use
489 public function makeParamString( $params ) {
491 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
492 $params['lang'] = strtolower( $params['lang'] );
493 $lang = "lang{$params['lang']}-";
495 if ( !isset( $params['width'] ) ) {
499 return "$lang{$params['width']}px";
502 public function parseParamString( $str ) {
504 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
505 return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
506 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
507 return [ 'width' => $m[1], 'lang' => 'en' ];
513 public function getParamMap() {
514 return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
518 * @param array $params
521 function getScriptParams( $params ) {
522 $scriptParams = [ 'width' => $params['width'] ];
523 if ( isset( $params['lang'] ) ) {
524 $scriptParams['lang'] = $params['lang'];
527 return $scriptParams;
530 public function getCommonMetaArray( File
$file ) {
531 $metadata = $file->getMetadata();
535 $metadata = $this->unpackMetadata( $metadata );
536 if ( !$metadata ||
isset( $metadata['error'] ) ) {
540 foreach ( $metadata as $name => $value ) {
541 $tag = strtolower( $name );
542 if ( $tag === 'originalwidth' ||
$tag === 'originalheight' ) {
543 // Skip these. In the exif metadata stuff, it is assumed these
544 // are measured in px, which is not the case here.
547 if ( isset( self
::$metaConversion[$tag] ) ) {
548 $tag = self
::$metaConversion[$tag];
549 $stdMetadata[$tag] = $value;