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;
33 * 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 = array(
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" );
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'];
79 * We do not support making animated svg thumbnails
81 function canAnimateThumb( $file ) {
90 function normaliseParams( $image, &$params ) {
92 if ( !parent
::normaliseParams( $image, $params ) ) {
95 # Don't make an image bigger than wgMaxSVGSize on the smaller side
96 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
97 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
98 $srcWidth = $image->getWidth( $params['page'] );
99 $srcHeight = $image->getHeight( $params['page'] );
100 $params['physicalWidth'] = $wgSVGMaxSize;
101 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
104 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
105 $srcWidth = $image->getWidth( $params['page'] );
106 $srcHeight = $image->getHeight( $params['page'] );
107 $params['physicalWidth'] = File
::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
108 $params['physicalHeight'] = $wgSVGMaxSize;
120 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
122 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
123 if ( !$this->normaliseParams( $image, $params ) ) {
124 return new TransformParameterError( $params );
126 $clientWidth = $params['width'];
127 $clientHeight = $params['height'];
128 $physicalWidth = $params['physicalWidth'];
129 $physicalHeight = $params['physicalHeight'];
130 $lang = isset( $params['lang'] ) ?
$params['lang'] : 'en';
132 if ( $flags & self
::TRANSFORM_LATER
) {
133 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
136 $metadata = $this->unpackMetadata( $image->getMetadata() );
137 if ( isset( $metadata['error'] ) ) { // sanity check
138 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
139 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
142 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
143 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
144 wfMessage( 'thumbnail_dest_directory' )->text() );
147 $srcPath = $image->getLocalRefPath();
148 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
149 if ( $status === true ) {
150 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
152 return $status; // MediaTransformError
157 * Transform an SVG file to PNG
158 * This function can be called outside of thumbnail contexts
159 * @param string $srcPath
160 * @param string $dstPath
161 * @param string $width
162 * @param string $height
163 * @param string $lang Language code of the language to render the SVG in
164 * @throws MWException
165 * @return bool|MediaTransformError
167 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
168 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
171 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
172 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
173 // This is a PHP callable
174 $func = $wgSVGConverters[$wgSVGConverter][0];
175 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
176 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
177 if ( !is_callable( $func ) ) {
178 throw new MWException( "$func is not callable" );
180 $err = call_user_func_array( $func, $args );
181 $retval = (bool)$err;
185 array( '$path/', '$width', '$height', '$input', '$output' ),
186 array( $wgSVGConverterPath ?
wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
189 wfEscapeShellArg( $srcPath ),
190 wfEscapeShellArg( $dstPath ) ),
191 $wgSVGConverters[$wgSVGConverter]
195 if ( $lang !== false ) {
196 $env['LANG'] = $lang;
199 wfProfileIn( 'rsvg' );
200 wfDebug( __METHOD__
. ": $cmd\n" );
201 $err = wfShellExecWithStderr( $cmd, $retval, $env );
202 wfProfileOut( 'rsvg' );
205 $removed = $this->removeBadFile( $dstPath, $retval );
206 if ( $retval != 0 ||
$removed ) {
207 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
208 wfHostname(), $retval, trim( $err ), $cmd ) );
209 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
214 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
215 $im = new Imagick( $srcPath );
216 $im->setImageFormat( 'png' );
217 $im->setBackgroundColor( 'transparent' );
218 $im->setImageDepth( 8 );
220 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
221 return 'Could not resize image';
223 if ( !$im->writeImage( $dstPath ) ) {
224 return "Could not write to $dstPath";
231 * @param bool $metadata
234 function getImageSize( $file, $path, $metadata = false ) {
235 if ( $metadata === false ) {
236 $metadata = $file->getMetaData();
238 $metadata = $this->unpackMetaData( $metadata );
240 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
241 return array( $metadata['width'], $metadata['height'], 'SVG',
242 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
244 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
248 function getThumbType( $ext, $mime, $params = null ) {
249 return array( 'png', 'image/png' );
253 * Subtitle for the image. Different from the base
254 * class so it can be denoted that SVG's have
255 * a "nominal" resolution, and not a fixed one,
256 * as well as so animation can be denoted.
261 function getLongDesc( $file ) {
264 $metadata = $this->unpackMetadata( $file->getMetadata() );
265 if ( isset( $metadata['error'] ) ) {
266 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
269 $size = $wgLang->formatSize( $file->getSize() );
271 if ( $this->isAnimatedImage( $file ) ) {
272 $msg = wfMessage( 'svg-long-desc-animated' );
274 $msg = wfMessage( 'svg-long-desc' );
277 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
279 return $msg->parse();
282 function getMetadata( $file, $filename ) {
283 $metadata = array( 'version' => self
::SVG_METADATA_VERSION
);
285 $metadata +
= SVGMetadataExtractor
::getMetadata( $filename );
286 } catch ( MWException
$e ) { // @todo SVG specific exceptions
287 // File not found, broken, etc.
288 $metadata['error'] = array(
289 'message' => $e->getMessage(),
290 'code' => $e->getCode()
292 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
294 return serialize( $metadata );
297 function unpackMetadata( $metadata ) {
298 wfSuppressWarnings();
299 $unser = unserialize( $metadata );
301 if ( isset( $unser['version'] ) && $unser['version'] == self
::SVG_METADATA_VERSION
) {
308 function getMetadataType( $image ) {
312 function isMetadataValid( $image, $metadata ) {
313 $meta = $this->unpackMetadata( $metadata );
314 if ( $meta === false ) {
315 return self
::METADATA_BAD
;
317 if ( !isset( $meta['originalWidth'] ) ) {
318 // Old but compatible
319 return self
::METADATA_COMPATIBLE
;
321 return self
::METADATA_GOOD
;
324 function visibleMetadataFields() {
325 $fields = array( 'objectname', 'imagedescription' );
333 function formatMetadata( $file ) {
335 'visible' => array(),
336 'collapsed' => array()
338 $metadata = $file->getMetadata();
342 $metadata = $this->unpackMetadata( $metadata );
343 if ( !$metadata ||
isset( $metadata['error'] ) ) {
347 /* TODO: add a formatter
348 $format = new FormatSVG( $metadata );
349 $formatted = $format->getFormattedData();
352 // Sort fields into visible and collapsed
353 $visibleFields = $this->visibleMetadataFields();
356 foreach ( $metadata as $name => $value ) {
357 $tag = strtolower( $name );
358 if ( isset( self
::$metaConversion[$tag] ) ) {
359 $tag = strtolower( self
::$metaConversion[$tag] );
361 // Do not output other metadata not in list
365 self
::addMeta( $result,
366 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
372 return $showMeta ?
$result : false;
376 * @param string $name Parameter name
377 * @param $string $value Parameter value
378 * @return bool Validity
380 function validateParam( $name, $value ) {
381 if ( in_array( $name, array( 'width', 'height' ) ) ) {
382 // Reject negative heights, widths
383 return ( $value > 0 );
384 } elseif ( $name == 'lang' ) {
386 if ( !Language
::isValidBuiltinCode( $value ) ) {
387 wfDebug( "Invalid user language code\n" );
392 // Only lang, width and height are acceptable keys
397 * @param array $params name=>value pairs of parameters
398 * @return string Filename to use
400 function makeParamString( $params ) {
402 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
403 $params['lang'] = mb_strtolower( $params['lang'] );
404 $lang = "lang{$params['lang']}-";
406 if ( !isset( $params['width'] ) ) {
409 return "$lang{$params['width']}px";
412 function parseParamString( $str ) {
414 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
415 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
416 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
417 return array( 'width' => $m[1], 'lang' => 'en' );
423 function getParamMap() {
424 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
431 function getScriptParams( $params ) {
433 'width' => $params['width'],
434 'lang' => $params['lang'],
438 public function getCommonMetaArray( File
$file ) {
439 $metadata = $file->getMetadata();
443 $metadata = $this->unpackMetadata( $metadata );
444 if ( !$metadata ||
isset( $metadata['error'] ) ) {
447 $stdMetadata = array();
448 foreach ( $metadata as $name => $value ) {
449 $tag = strtolower( $name );
450 if ( $tag === 'originalwidth' ||
$tag === 'originalheight' ) {
451 // Skip these. In the exif metadata stuff, it is assumed these
452 // are measured in px, which is not the case here.
455 if ( isset( self
::$metaConversion[$tag] ) ) {
456 $tag = self
::$metaConversion[$tag];
457 $stdMetadata[$tag] = $value;