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" );
55 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 * We do not support making animated svg thumbnails
83 function canAnimateThumb( $file ) {
92 function normaliseParams( $image, &$params ) {
94 if ( !parent
::normaliseParams( $image, $params ) ) {
97 # Don't make an image bigger than wgMaxSVGSize on the smaller side
98 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
99 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
100 $srcWidth = $image->getWidth( $params['page'] );
101 $srcHeight = $image->getHeight( $params['page'] );
102 $params['physicalWidth'] = $wgSVGMaxSize;
103 $params['physicalHeight'] = File
::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
106 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
107 $srcWidth = $image->getWidth( $params['page'] );
108 $srcHeight = $image->getHeight( $params['page'] );
109 $params['physicalWidth'] = File
::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
110 $params['physicalHeight'] = $wgSVGMaxSize;
123 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
125 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
126 if ( !$this->normaliseParams( $image, $params ) ) {
127 return new TransformParameterError( $params );
129 $clientWidth = $params['width'];
130 $clientHeight = $params['height'];
131 $physicalWidth = $params['physicalWidth'];
132 $physicalHeight = $params['physicalHeight'];
133 $lang = isset( $params['lang'] ) ?
$params['lang'] : 'en';
135 if ( $flags & self
::TRANSFORM_LATER
) {
136 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
139 $metadata = $this->unpackMetadata( $image->getMetadata() );
140 if ( isset( $metadata['error'] ) ) { // sanity check
141 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
143 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
146 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__
) ) {
147 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
148 wfMessage( 'thumbnail_dest_directory' )->text() );
151 $srcPath = $image->getLocalRefPath();
152 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
153 if ( $status === true ) {
154 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
156 return $status; // MediaTransformError
161 * Transform an SVG file to PNG
162 * This function can be called outside of thumbnail contexts
163 * @param string $srcPath
164 * @param string $dstPath
165 * @param string $width
166 * @param string $height
167 * @param string $lang Language code of the language to render the SVG in
168 * @throws MWException
169 * @return bool|MediaTransformError
171 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
172 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
175 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
176 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
177 // This is a PHP callable
178 $func = $wgSVGConverters[$wgSVGConverter][0];
179 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
180 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
181 if ( !is_callable( $func ) ) {
182 throw new MWException( "$func is not callable" );
184 $err = call_user_func_array( $func, $args );
185 $retval = (bool)$err;
189 array( '$path/', '$width', '$height', '$input', '$output' ),
190 array( $wgSVGConverterPath ?
wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
193 wfEscapeShellArg( $srcPath ),
194 wfEscapeShellArg( $dstPath ) ),
195 $wgSVGConverters[$wgSVGConverter]
199 if ( $lang !== false ) {
200 $env['LANG'] = $lang;
203 wfProfileIn( 'rsvg' );
204 wfDebug( __METHOD__
. ": $cmd\n" );
205 $err = wfShellExecWithStderr( $cmd, $retval, $env );
206 wfProfileOut( 'rsvg' );
209 $removed = $this->removeBadFile( $dstPath, $retval );
210 if ( $retval != 0 ||
$removed ) {
211 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
212 wfHostname(), $retval, trim( $err ), $cmd ) );
214 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
220 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
221 $im = new Imagick( $srcPath );
222 $im->setImageFormat( 'png' );
223 $im->setBackgroundColor( 'transparent' );
224 $im->setImageDepth( 8 );
226 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
227 return 'Could not resize image';
229 if ( !$im->writeImage( $dstPath ) ) {
230 return "Could not write to $dstPath";
237 * @param bool $metadata
240 function getImageSize( $file, $path, $metadata = false ) {
241 if ( $metadata === false ) {
242 $metadata = $file->getMetaData();
244 $metadata = $this->unpackMetaData( $metadata );
246 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
247 return array( $metadata['width'], $metadata['height'], 'SVG',
248 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
250 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
254 function getThumbType( $ext, $mime, $params = null ) {
255 return array( 'png', 'image/png' );
259 * Subtitle for the image. Different from the base
260 * class so it can be denoted that SVG's have
261 * a "nominal" resolution, and not a fixed one,
262 * as well as so animation can be denoted.
267 function getLongDesc( $file ) {
270 $metadata = $this->unpackMetadata( $file->getMetadata() );
271 if ( isset( $metadata['error'] ) ) {
272 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
275 $size = $wgLang->formatSize( $file->getSize() );
277 if ( $this->isAnimatedImage( $file ) ) {
278 $msg = wfMessage( 'svg-long-desc-animated' );
280 $msg = wfMessage( 'svg-long-desc' );
283 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
285 return $msg->parse();
288 function getMetadata( $file, $filename ) {
289 $metadata = array( 'version' => self
::SVG_METADATA_VERSION
);
291 $metadata +
= SVGMetadataExtractor
::getMetadata( $filename );
292 } catch ( MWException
$e ) { // @todo SVG specific exceptions
293 // File not found, broken, etc.
294 $metadata['error'] = array(
295 'message' => $e->getMessage(),
296 'code' => $e->getCode()
298 wfDebug( __METHOD__
. ': ' . $e->getMessage() . "\n" );
301 return serialize( $metadata );
304 function unpackMetadata( $metadata ) {
305 wfSuppressWarnings();
306 $unser = unserialize( $metadata );
308 if ( isset( $unser['version'] ) && $unser['version'] == self
::SVG_METADATA_VERSION
) {
315 function getMetadataType( $image ) {
319 function isMetadataValid( $image, $metadata ) {
320 $meta = $this->unpackMetadata( $metadata );
321 if ( $meta === false ) {
322 return self
::METADATA_BAD
;
324 if ( !isset( $meta['originalWidth'] ) ) {
325 // Old but compatible
326 return self
::METADATA_COMPATIBLE
;
329 return self
::METADATA_GOOD
;
332 function visibleMetadataFields() {
333 $fields = array( 'objectname', 'imagedescription' );
342 function formatMetadata( $file ) {
344 'visible' => array(),
345 'collapsed' => array()
347 $metadata = $file->getMetadata();
351 $metadata = $this->unpackMetadata( $metadata );
352 if ( !$metadata ||
isset( $metadata['error'] ) ) {
356 /* TODO: add a formatter
357 $format = new FormatSVG( $metadata );
358 $formatted = $format->getFormattedData();
361 // Sort fields into visible and collapsed
362 $visibleFields = $this->visibleMetadataFields();
365 foreach ( $metadata as $name => $value ) {
366 $tag = strtolower( $name );
367 if ( isset( self
::$metaConversion[$tag] ) ) {
368 $tag = strtolower( self
::$metaConversion[$tag] );
370 // Do not output other metadata not in list
374 self
::addMeta( $result,
375 in_array( $tag, $visibleFields ) ?
'visible' : 'collapsed',
382 return $showMeta ?
$result : false;
386 * @param string $name Parameter name
387 * @param $string $value Parameter value
388 * @return bool Validity
390 function validateParam( $name, $value ) {
391 if ( in_array( $name, array( 'width', 'height' ) ) ) {
392 // Reject negative heights, widths
393 return ( $value > 0 );
394 } elseif ( $name == 'lang' ) {
396 if ( !Language
::isValidBuiltinCode( $value ) ) {
397 wfDebug( "Invalid user language code\n" );
405 // Only lang, width and height are acceptable keys
410 * @param array $params name=>value pairs of parameters
411 * @return string Filename to use
413 function makeParamString( $params ) {
415 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
416 $params['lang'] = mb_strtolower( $params['lang'] );
417 $lang = "lang{$params['lang']}-";
419 if ( !isset( $params['width'] ) ) {
423 return "$lang{$params['width']}px";
426 function parseParamString( $str ) {
428 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
429 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
430 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
431 return array( 'width' => $m[1], 'lang' => 'en' );
437 function getParamMap() {
438 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
445 function getScriptParams( $params ) {
447 'width' => $params['width'],
448 'lang' => $params['lang'],
452 public function getCommonMetaArray( File
$file ) {
453 $metadata = $file->getMetadata();
457 $metadata = $this->unpackMetadata( $metadata );
458 if ( !$metadata ||
isset( $metadata['error'] ) ) {
461 $stdMetadata = array();
462 foreach ( $metadata as $name => $value ) {
463 $tag = strtolower( $name );
464 if ( $tag === 'originalwidth' ||
$tag === 'originalheight' ) {
465 // Skip these. In the exif metadata stuff, it is assumed these
466 // are measured in px, which is not the case here.
469 if ( isset( self
::$metaConversion[$tag] ) ) {
470 $tag = self
::$metaConversion[$tag];
471 $stdMetadata[$tag] = $value;