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
25 * Handler for SVG images.
29 class SvgHandler
extends ImageHandler
{
30 const SVG_METADATA_VERSION
= 2;
32 /** @var array A list of metadata tags that can be converted
33 * to the commonly used exif tags. This allows messages
34 * to be reused, and consistent tag names for {{#formatmetadata:..}}
36 private static $metaConversion = array(
37 'originalwidth' => 'ImageWidth',
38 'originalheight' => 'ImageLength',
39 'description' => 'ImageDescription',
40 'title' => 'ObjectName',
43 function isEnabled() {
44 global $wgSVGConverters, $wgSVGConverter;
45 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
46 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
54 function mustRender( $file ) {
58 function isVectorized( $file ) {
66 function isAnimatedImage( $file ) {
67 # @todo Detect animated SVGs
68 $metadata = $file->getMetadata();
70 $metadata = $this->unpackMetadata( $metadata );
71 if ( isset( $metadata['animated'] ) ) {
72 return $metadata['animated'];
80 * We do not support making animated svg thumbnails
82 function canAnimateThumb( $file ) {
88 * @param array $params
91 function normaliseParams( $image, &$params ) {
93 if ( !parent
::normaliseParams( $image, $params ) ) {
96 # Don't make an image bigger than wgMaxSVGSize on the smaller side
97 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
98 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
99 $srcWidth = $image->getWidth( $params['page'] );
100 $srcHeight = $image->getHeight( $params['page'] );
101 $params['physicalWidth'] = $wgSVGMaxSize;
102 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
105 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
106 $srcWidth = $image->getWidth( $params['page'] );
107 $srcHeight = $image->getHeight( $params['page'] );
108 $params['physicalWidth'] = File
::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
109 $params['physicalHeight'] = $wgSVGMaxSize;
118 * @param string $dstPath
119 * @param string $dstUrl
120 * @param array $params
122 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
124 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
125 if ( !$this->normaliseParams( $image, $params ) ) {
126 return new TransformParameterError( $params );
128 $clientWidth = $params['width'];
129 $clientHeight = $params['height'];
130 $physicalWidth = $params['physicalWidth'];
131 $physicalHeight = $params['physicalHeight'];
132 $lang = isset( $params['lang'] ) ?
$params['lang'] : 'en';
134 if ( $flags & self
::TRANSFORM_LATER
) {
135 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
138 $metadata = $this->unpackMetadata( $image->getMetadata() );
139 if ( isset( $metadata['error'] ) ) { // sanity check
140 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
142 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
145 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
146 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
147 wfMessage( 'thumbnail_dest_directory' )->text() );
150 $srcPath = $image->getLocalRefPath();
151 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
152 if ( $status === true ) {
153 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
155 return $status; // MediaTransformError
160 * Transform an SVG file to PNG
161 * This function can be called outside of thumbnail contexts
162 * @param string $srcPath
163 * @param string $dstPath
164 * @param string $width
165 * @param string $height
166 * @param bool|string $lang Language code of the language to render the SVG in
167 * @throws MWException
168 * @return bool|MediaTransformError
170 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
171 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
174 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
175 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
176 // This is a PHP callable
177 $func = $wgSVGConverters[$wgSVGConverter][0];
178 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
179 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
180 if ( !is_callable( $func ) ) {
181 throw new MWException( "$func is not callable" );
183 $err = call_user_func_array( $func, $args );
184 $retval = (bool)$err;
188 array( '$path/', '$width', '$height', '$input', '$output' ),
189 array( $wgSVGConverterPath ?
wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
192 wfEscapeShellArg( $srcPath ),
193 wfEscapeShellArg( $dstPath ) ),
194 $wgSVGConverters[$wgSVGConverter]
198 if ( $lang !== false ) {
199 $env['LANG'] = $lang;
202 wfProfileIn( 'rsvg' );
203 wfDebug( __METHOD__
. ": $cmd\n" );
204 $err = wfShellExecWithStderr( $cmd, $retval, $env );
205 wfProfileOut( 'rsvg' );
208 $removed = $this->removeBadFile( $dstPath, $retval );
209 if ( $retval != 0 ||
$removed ) {
210 $this->logErrorForExternalProcess( $retval, $err, $cmd );
211 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
217 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
218 $im = new Imagick( $srcPath );
219 $im->setImageFormat( 'png' );
220 $im->setBackgroundColor( 'transparent' );
221 $im->setImageDepth( 8 );
223 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
224 return 'Could not resize image';
226 if ( !$im->writeImage( $dstPath ) ) {
227 return "Could not write to $dstPath";
233 * @param string $path Unused
234 * @param bool|array $metadata
237 function getImageSize( $file, $path, $metadata = false ) {
238 if ( $metadata === false ) {
239 $metadata = $file->getMetaData();
241 $metadata = $this->unpackMetaData( $metadata );
243 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
244 return array( $metadata['width'], $metadata['height'], 'SVG',
245 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
247 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
251 function getThumbType( $ext, $mime, $params = null ) {
252 return array( 'png', 'image/png' );
256 * Subtitle for the image. Different from the base
257 * class so it can be denoted that SVG's have
258 * a "nominal" resolution, and not a fixed one,
259 * as well as so animation can be denoted.
264 function getLongDesc( $file ) {
267 $metadata = $this->unpackMetadata( $file->getMetadata() );
268 if ( isset( $metadata['error'] ) ) {
269 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
272 $size = $wgLang->formatSize( $file->getSize() );
274 if ( $this->isAnimatedImage( $file ) ) {
275 $msg = wfMessage( 'svg-long-desc-animated' );
277 $msg = wfMessage( 'svg-long-desc' );
280 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
282 return $msg->parse();
287 * @param string $filename
288 * @return string Serialised metadata
290 function getMetadata( $file, $filename ) {
291 $metadata = array( 'version' => self
::SVG_METADATA_VERSION
);
293 $metadata +
= SVGMetadataExtractor
::getMetadata( $filename );
294 } catch ( MWException
$e ) { // @todo SVG specific exceptions
295 // File not found, broken, etc.
296 $metadata['error'] = array(
297 'message' => $e->getMessage(),
298 'code' => $e->getCode()
300 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
303 return serialize( $metadata );
306 function unpackMetadata( $metadata ) {
307 wfSuppressWarnings();
308 $unser = unserialize( $metadata );
310 if ( isset( $unser['version'] ) && $unser['version'] == self
::SVG_METADATA_VERSION
) {
317 function getMetadataType( $image ) {
321 function isMetadataValid( $image, $metadata ) {
322 $meta = $this->unpackMetadata( $metadata );
323 if ( $meta === false ) {
324 return self
::METADATA_BAD
;
326 if ( !isset( $meta['originalWidth'] ) ) {
327 // Old but compatible
328 return self
::METADATA_COMPATIBLE
;
331 return self
::METADATA_GOOD
;
334 function visibleMetadataFields() {
335 $fields = array( 'objectname', 'imagedescription' );
344 function formatMetadata( $file ) {
346 'visible' => array(),
347 'collapsed' => array()
349 $metadata = $file->getMetadata();
353 $metadata = $this->unpackMetadata( $metadata );
354 if ( !$metadata ||
isset( $metadata['error'] ) ) {
358 /* @todo Add a formatter
359 $format = new FormatSVG( $metadata );
360 $formatted = $format->getFormattedData();
363 // Sort fields into visible and collapsed
364 $visibleFields = $this->visibleMetadataFields();
367 foreach ( $metadata as $name => $value ) {
368 $tag = strtolower( $name );
369 if ( isset( self
::$metaConversion[$tag] ) ) {
370 $tag = strtolower( self
::$metaConversion[$tag] );
372 // Do not output other metadata not in list
376 self
::addMeta( $result,
377 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
384 return $showMeta ?
$result : false;
388 * @param string $name Parameter name
389 * @param mixed $value Parameter value
390 * @return bool Validity
392 function validateParam( $name, $value ) {
393 if ( in_array( $name, array( 'width', 'height' ) ) ) {
394 // Reject negative heights, widths
395 return ( $value > 0 );
396 } elseif ( $name == 'lang' ) {
398 if ( !Language
::isValidBuiltinCode( $value ) ) {
399 wfDebug( "Invalid user language code\n" );
407 // Only lang, width and height are acceptable keys
412 * @param array $params name=>value pairs of parameters
413 * @return string Filename to use
415 function makeParamString( $params ) {
417 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
418 $params['lang'] = mb_strtolower( $params['lang'] );
419 $lang = "lang{$params['lang']}-";
421 if ( !isset( $params['width'] ) ) {
425 return "$lang{$params['width']}px";
428 function parseParamString( $str ) {
430 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
431 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
432 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
433 return array( 'width' => $m[1], 'lang' => 'en' );
439 function getParamMap() {
440 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
444 * @param array $params
447 function getScriptParams( $params ) {
449 'width' => $params['width'],
450 'lang' => $params['lang'],
454 public function getCommonMetaArray( File
$file ) {
455 $metadata = $file->getMetadata();
459 $metadata = $this->unpackMetadata( $metadata );
460 if ( !$metadata ||
isset( $metadata['error'] ) ) {
463 $stdMetadata = array();
464 foreach ( $metadata as $name => $value ) {
465 $tag = strtolower( $name );
466 if ( $tag === 'originalwidth' ||
$tag === 'originalheight' ) {
467 // Skip these. In the exif metadata stuff, it is assumed these
468 // are measured in px, which is not the case here.
471 if ( isset( self
::$metaConversion[$tag] ) ) {
472 $tag = self
::$metaConversion[$tag];
473 $stdMetadata[$tag] = $value;