Add UI to discover translated SVG files.
[mediawiki.git] / includes / media / SVG.php
blob5a61bcc336ded669f5bf9e0297c3dbc998e3f652
1 <?php
2 /**
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
20 * @file
21 * @ingroup Media
24 /**
25 * Handler for SVG images.
27 * @ingroup Media
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" );
48 return false;
49 } else {
50 return true;
54 function mustRender( $file ) {
55 return true;
58 function isVectorized( $file ) {
59 return true;
62 /**
63 * @param File $file
64 * @return bool
66 function isAnimatedImage( $file ) {
67 # @todo Detect animated SVGs
68 $metadata = $file->getMetadata();
69 if ( $metadata ) {
70 $metadata = $this->unpackMetadata( $metadata );
71 if ( isset( $metadata['animated'] ) ) {
72 return $metadata['animated'];
76 return false;
79 /**
80 * Which languages (systemLanguage attribute) is supported.
82 * @note This list is not guaranteed to be exhaustive.
83 * To avoid OOM errors, we only look at first bit of a file.
84 * Thus all languages on this list are present in the file,
85 * but its possible for the file to have a language not on
86 * this list.
88 * @param File $file
89 * @return Array of language codes, or empty if no language switching supported.
91 public function getAvailableLanguages( File $file ) {
92 $metadata = $file->getMetadata();
93 $langList = array();
94 if ( $metadata ) {
95 $metadata = $this->unpackMetadata( $metadata );
96 if ( isset( $metadata['translations'] ) ) {
97 foreach( $metadata['translations'] as $lang => $langType ) {
98 if ( $langType === SvgReader::LANG_FULL_MATCH ) {
99 $langList[] = $lang;
104 return $langList;
108 * What language to render file in if none selected.
110 * @return String language code.
112 public function getDefaultRenderLanguage( File $file ) {
113 return 'en';
117 * We do not support making animated svg thumbnails
119 function canAnimateThumb( $file ) {
120 return false;
124 * @param File $image
125 * @param array $params
126 * @return bool
128 function normaliseParams( $image, &$params ) {
129 global $wgSVGMaxSize;
130 if ( !parent::normaliseParams( $image, $params ) ) {
131 return false;
133 # Don't make an image bigger than wgMaxSVGSize on the smaller side
134 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
135 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
136 $srcWidth = $image->getWidth( $params['page'] );
137 $srcHeight = $image->getHeight( $params['page'] );
138 $params['physicalWidth'] = $wgSVGMaxSize;
139 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
141 } else {
142 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
143 $srcWidth = $image->getWidth( $params['page'] );
144 $srcHeight = $image->getHeight( $params['page'] );
145 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
146 $params['physicalHeight'] = $wgSVGMaxSize;
150 return true;
154 * @param File $image
155 * @param string $dstPath
156 * @param string $dstUrl
157 * @param array $params
158 * @param int $flags
159 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
161 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
162 if ( !$this->normaliseParams( $image, $params ) ) {
163 return new TransformParameterError( $params );
165 $clientWidth = $params['width'];
166 $clientHeight = $params['height'];
167 $physicalWidth = $params['physicalWidth'];
168 $physicalHeight = $params['physicalHeight'];
169 $lang = isset( $params['lang'] ) ? $params['lang'] : $this->getDefaultRenderLanguage( $image );
171 if ( $flags & self::TRANSFORM_LATER ) {
172 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
175 $metadata = $this->unpackMetadata( $image->getMetadata() );
176 if ( isset( $metadata['error'] ) ) { // sanity check
177 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
179 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
182 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
183 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
184 wfMessage( 'thumbnail_dest_directory' )->text() );
187 $srcPath = $image->getLocalRefPath();
188 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
189 if ( $status === true ) {
190 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
191 } else {
192 return $status; // MediaTransformError
197 * Transform an SVG file to PNG
198 * This function can be called outside of thumbnail contexts
199 * @param string $srcPath
200 * @param string $dstPath
201 * @param string $width
202 * @param string $height
203 * @param bool|string $lang Language code of the language to render the SVG in
204 * @throws MWException
205 * @return bool|MediaTransformError
207 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
208 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
209 $err = false;
210 $retval = '';
211 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
212 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
213 // This is a PHP callable
214 $func = $wgSVGConverters[$wgSVGConverter][0];
215 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
216 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
217 if ( !is_callable( $func ) ) {
218 throw new MWException( "$func is not callable" );
220 $err = call_user_func_array( $func, $args );
221 $retval = (bool)$err;
222 } else {
223 // External command
224 $cmd = str_replace(
225 array( '$path/', '$width', '$height', '$input', '$output' ),
226 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
227 intval( $width ),
228 intval( $height ),
229 wfEscapeShellArg( $srcPath ),
230 wfEscapeShellArg( $dstPath ) ),
231 $wgSVGConverters[$wgSVGConverter]
234 $env = array();
235 if ( $lang !== false ) {
236 $env['LANG'] = $lang;
239 wfProfileIn( 'rsvg' );
240 wfDebug( __METHOD__ . ": $cmd\n" );
241 $err = wfShellExecWithStderr( $cmd, $retval, $env );
242 wfProfileOut( 'rsvg' );
245 $removed = $this->removeBadFile( $dstPath, $retval );
246 if ( $retval != 0 || $removed ) {
247 $this->logErrorForExternalProcess( $retval, $err, $cmd );
248 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
251 return true;
254 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
255 $im = new Imagick( $srcPath );
256 $im->setImageFormat( 'png' );
257 $im->setBackgroundColor( 'transparent' );
258 $im->setImageDepth( 8 );
260 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
261 return 'Could not resize image';
263 if ( !$im->writeImage( $dstPath ) ) {
264 return "Could not write to $dstPath";
269 * @param File $file
270 * @param string $path Unused
271 * @param bool|array $metadata
272 * @return array
274 function getImageSize( $file, $path, $metadata = false ) {
275 if ( $metadata === false ) {
276 $metadata = $file->getMetaData();
278 $metadata = $this->unpackMetaData( $metadata );
280 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
281 return array( $metadata['width'], $metadata['height'], 'SVG',
282 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
283 } else { // error
284 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
288 function getThumbType( $ext, $mime, $params = null ) {
289 return array( 'png', 'image/png' );
293 * Subtitle for the image. Different from the base
294 * class so it can be denoted that SVG's have
295 * a "nominal" resolution, and not a fixed one,
296 * as well as so animation can be denoted.
298 * @param File $file
299 * @return string
301 function getLongDesc( $file ) {
302 global $wgLang;
304 $metadata = $this->unpackMetadata( $file->getMetadata() );
305 if ( isset( $metadata['error'] ) ) {
306 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
309 $size = $wgLang->formatSize( $file->getSize() );
311 if ( $this->isAnimatedImage( $file ) ) {
312 $msg = wfMessage( 'svg-long-desc-animated' );
313 } else {
314 $msg = wfMessage( 'svg-long-desc' );
317 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
319 return $msg->parse();
323 * @param File $file
324 * @param string $filename
325 * @return string Serialised metadata
327 function getMetadata( $file, $filename ) {
328 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
329 try {
330 $metadata += SVGMetadataExtractor::getMetadata( $filename );
331 } catch ( MWException $e ) { // @todo SVG specific exceptions
332 // File not found, broken, etc.
333 $metadata['error'] = array(
334 'message' => $e->getMessage(),
335 'code' => $e->getCode()
337 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
340 return serialize( $metadata );
343 function unpackMetadata( $metadata ) {
344 wfSuppressWarnings();
345 $unser = unserialize( $metadata );
346 wfRestoreWarnings();
347 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
348 return $unser;
349 } else {
350 return false;
354 function getMetadataType( $image ) {
355 return 'parsed-svg';
358 function isMetadataValid( $image, $metadata ) {
359 $meta = $this->unpackMetadata( $metadata );
360 if ( $meta === false ) {
361 return self::METADATA_BAD;
363 if ( !isset( $meta['originalWidth'] ) ) {
364 // Old but compatible
365 return self::METADATA_COMPATIBLE;
368 return self::METADATA_GOOD;
371 function visibleMetadataFields() {
372 $fields = array( 'objectname', 'imagedescription' );
374 return $fields;
378 * @param File $file
379 * @return array|bool
381 function formatMetadata( $file ) {
382 $result = array(
383 'visible' => array(),
384 'collapsed' => array()
386 $metadata = $file->getMetadata();
387 if ( !$metadata ) {
388 return false;
390 $metadata = $this->unpackMetadata( $metadata );
391 if ( !$metadata || isset( $metadata['error'] ) ) {
392 return false;
395 /* @todo Add a formatter
396 $format = new FormatSVG( $metadata );
397 $formatted = $format->getFormattedData();
400 // Sort fields into visible and collapsed
401 $visibleFields = $this->visibleMetadataFields();
403 $showMeta = false;
404 foreach ( $metadata as $name => $value ) {
405 $tag = strtolower( $name );
406 if ( isset( self::$metaConversion[$tag] ) ) {
407 $tag = strtolower( self::$metaConversion[$tag] );
408 } else {
409 // Do not output other metadata not in list
410 continue;
412 $showMeta = true;
413 self::addMeta( $result,
414 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
415 'exif',
416 $tag,
417 $value
421 return $showMeta ? $result : false;
425 * @param string $name Parameter name
426 * @param mixed $value Parameter value
427 * @return bool Validity
429 function validateParam( $name, $value ) {
430 if ( in_array( $name, array( 'width', 'height' ) ) ) {
431 // Reject negative heights, widths
432 return ( $value > 0 );
433 } elseif ( $name == 'lang' ) {
434 // Validate $code
435 if ( !Language::isValidBuiltinCode( $value ) ) {
436 wfDebug( "Invalid user language code\n" );
438 return false;
441 return true;
444 // Only lang, width and height are acceptable keys
445 return false;
449 * @param array $params name=>value pairs of parameters
450 * @return string Filename to use
452 function makeParamString( $params ) {
453 $lang = '';
454 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
455 $params['lang'] = mb_strtolower( $params['lang'] );
456 $lang = "lang{$params['lang']}-";
458 if ( !isset( $params['width'] ) ) {
459 return false;
462 return "$lang{$params['width']}px";
465 function parseParamString( $str ) {
466 $m = false;
467 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
468 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
469 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
470 return array( 'width' => $m[1], 'lang' => 'en' );
471 } else {
472 return false;
476 function getParamMap() {
477 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
481 * @param array $params
482 * @return array
484 function getScriptParams( $params ) {
485 return array(
486 'width' => $params['width'],
487 'lang' => $params['lang'],
491 public function getCommonMetaArray( File $file ) {
492 $metadata = $file->getMetadata();
493 if ( !$metadata ) {
494 return array();
496 $metadata = $this->unpackMetadata( $metadata );
497 if ( !$metadata || isset( $metadata['error'] ) ) {
498 return array();
500 $stdMetadata = array();
501 foreach ( $metadata as $name => $value ) {
502 $tag = strtolower( $name );
503 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
504 // Skip these. In the exif metadata stuff, it is assumed these
505 // are measured in px, which is not the case here.
506 continue;
508 if ( isset( self::$metaConversion[$tag] ) ) {
509 $tag = self::$metaConversion[$tag];
510 $stdMetadata[$tag] = $value;
514 return $stdMetadata;