Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / media / SVG.php
blobf0356f51fdec3a79fba9d8f70db1e61d5da89592
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 function isEnabled() {
33 global $wgSVGConverters, $wgSVGConverter;
34 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
35 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
36 return false;
37 } else {
38 return true;
42 function mustRender( $file ) {
43 return true;
46 function isVectorized( $file ) {
47 return true;
50 /**
51 * @param $file File
52 * @return bool
54 function isAnimatedImage( $file ) {
55 # TODO: detect animated SVGs
56 $metadata = $file->getMetadata();
57 if ( $metadata ) {
58 $metadata = $this->unpackMetadata( $metadata );
59 if ( isset( $metadata['animated'] ) ) {
60 return $metadata['animated'];
63 return false;
66 /**
67 * We do not support making animated svg thumbnails
69 function canAnimateThumb( $file ) {
70 return false;
73 /**
74 * @param $image File
75 * @param $params
76 * @return bool
78 function normaliseParams( $image, &$params ) {
79 global $wgSVGMaxSize;
80 if ( !parent::normaliseParams( $image, $params ) ) {
81 return false;
83 # Don't make an image bigger than wgMaxSVGSize on the smaller side
84 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
85 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
86 $srcWidth = $image->getWidth( $params['page'] );
87 $srcHeight = $image->getHeight( $params['page'] );
88 $params['physicalWidth'] = $wgSVGMaxSize;
89 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
91 } else {
92 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
93 $srcWidth = $image->getWidth( $params['page'] );
94 $srcHeight = $image->getHeight( $params['page'] );
95 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
96 $params['physicalHeight'] = $wgSVGMaxSize;
99 return true;
103 * @param $image File
104 * @param $dstPath
105 * @param $dstUrl
106 * @param $params
107 * @param int $flags
108 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
110 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
111 if ( !$this->normaliseParams( $image, $params ) ) {
112 return new TransformParameterError( $params );
114 $clientWidth = $params['width'];
115 $clientHeight = $params['height'];
116 $physicalWidth = $params['physicalWidth'];
117 $physicalHeight = $params['physicalHeight'];
118 $lang = isset( $params['lang'] ) ? $params['lang'] : 'en';
120 if ( $flags & self::TRANSFORM_LATER ) {
121 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
124 $metadata = $this->unpackMetadata( $image->getMetadata() );
125 if ( isset( $metadata['error'] ) ) { // sanity check
126 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
127 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
130 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
131 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
132 wfMessage( 'thumbnail_dest_directory' )->text() );
135 $srcPath = $image->getLocalRefPath();
136 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
137 if ( $status === true ) {
138 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
139 } else {
140 return $status; // MediaTransformError
145 * Transform an SVG file to PNG
146 * This function can be called outside of thumbnail contexts
147 * @param string $srcPath
148 * @param string $dstPath
149 * @param string $width
150 * @param string $height
151 * @param string $lang Language code of the language to render the SVG in
152 * @throws MWException
153 * @return bool|MediaTransformError
155 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
156 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
157 $err = false;
158 $retval = '';
159 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
160 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
161 // This is a PHP callable
162 $func = $wgSVGConverters[$wgSVGConverter][0];
163 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
164 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
165 if ( !is_callable( $func ) ) {
166 throw new MWException( "$func is not callable" );
168 $err = call_user_func_array( $func, $args );
169 $retval = (bool)$err;
170 } else {
171 // External command
172 $cmd = str_replace(
173 array( '$path/', '$width', '$height', '$input', '$output' ),
174 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
175 intval( $width ),
176 intval( $height ),
177 wfEscapeShellArg( $srcPath ),
178 wfEscapeShellArg( $dstPath ) ),
179 $wgSVGConverters[$wgSVGConverter]
180 ) . " 2>&1";
182 $env = array();
183 if( $lang !== false ) {
184 $env['LANG'] = $lang;
187 wfProfileIn( 'rsvg' );
188 wfDebug( __METHOD__ . ": $cmd\n" );
189 $err = wfShellExec( $cmd, $retval, $env );
190 wfProfileOut( 'rsvg' );
193 $removed = $this->removeBadFile( $dstPath, $retval );
194 if ( $retval != 0 || $removed ) {
195 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
196 wfHostname(), $retval, trim( $err ), $cmd ) );
197 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
199 return true;
202 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
203 $im = new Imagick( $srcPath );
204 $im->setImageFormat( 'png' );
205 $im->setBackgroundColor( 'transparent' );
206 $im->setImageDepth( 8 );
208 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
209 return 'Could not resize image';
211 if ( !$im->writeImage( $dstPath ) ) {
212 return "Could not write to $dstPath";
217 * @param $file File
218 * @param $path
219 * @param bool $metadata
220 * @return array
222 function getImageSize( $file, $path, $metadata = false ) {
223 if ( $metadata === false ) {
224 $metadata = $file->getMetaData();
226 $metadata = $this->unpackMetaData( $metadata );
228 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
229 return array( $metadata['width'], $metadata['height'], 'SVG',
230 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
231 } else { // error
232 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
236 function getThumbType( $ext, $mime, $params = null ) {
237 return array( 'png', 'image/png' );
241 * Subtitle for the image. Different from the base
242 * class so it can be denoted that SVG's have
243 * a "nominal" resolution, and not a fixed one,
244 * as well as so animation can be denoted.
246 * @param $file File
247 * @return string
249 function getLongDesc( $file ) {
250 global $wgLang;
252 $metadata = $this->unpackMetadata( $file->getMetadata() );
253 if ( isset( $metadata['error'] ) ) {
254 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
257 $size = $wgLang->formatSize( $file->getSize() );
259 if ( $this->isAnimatedImage( $file ) ) {
260 $msg = wfMessage( 'svg-long-desc-animated' );
261 } else {
262 $msg = wfMessage( 'svg-long-desc' );
265 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
267 return $msg->parse();
270 function getMetadata( $file, $filename ) {
271 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
272 try {
273 $metadata += SVGMetadataExtractor::getMetadata( $filename );
274 } catch ( MWException $e ) { // @todo SVG specific exceptions
275 // File not found, broken, etc.
276 $metadata['error'] = array(
277 'message' => $e->getMessage(),
278 'code' => $e->getCode()
280 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
282 return serialize( $metadata );
285 function unpackMetadata( $metadata ) {
286 wfSuppressWarnings();
287 $unser = unserialize( $metadata );
288 wfRestoreWarnings();
289 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
290 return $unser;
291 } else {
292 return false;
296 function getMetadataType( $image ) {
297 return 'parsed-svg';
300 function isMetadataValid( $image, $metadata ) {
301 $meta = $this->unpackMetadata( $metadata );
302 if ( $meta === false ) {
303 return self::METADATA_BAD;
305 if ( !isset( $meta['originalWidth'] ) ) {
306 // Old but compatible
307 return self::METADATA_COMPATIBLE;
309 return self::METADATA_GOOD;
312 function visibleMetadataFields() {
313 $fields = array( 'objectname', 'imagedescription' );
314 return $fields;
318 * @param $file File
319 * @return array|bool
321 function formatMetadata( $file ) {
322 $result = array(
323 'visible' => array(),
324 'collapsed' => array()
326 $metadata = $file->getMetadata();
327 if ( !$metadata ) {
328 return false;
330 $metadata = $this->unpackMetadata( $metadata );
331 if ( !$metadata || isset( $metadata['error'] ) ) {
332 return false;
335 /* TODO: add a formatter
336 $format = new FormatSVG( $metadata );
337 $formatted = $format->getFormattedData();
340 // Sort fields into visible and collapsed
341 $visibleFields = $this->visibleMetadataFields();
343 // Rename fields to be compatible with exif, so that
344 // the labels for these fields work and reuse existing messages.
345 $conversion = array(
346 'originalwidth' => 'imagewidth',
347 'originalheight' => 'imagelength',
348 'description' => 'imagedescription',
349 'title' => 'objectname',
351 foreach ( $metadata as $name => $value ) {
352 $tag = strtolower( $name );
353 if ( isset( $conversion[$tag] ) ) {
354 $tag = $conversion[$tag];
355 } else {
356 // Do not output other metadata not in list
357 continue;
359 self::addMeta( $result,
360 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
361 'exif',
362 $tag,
363 $value
366 return $result;
371 * @param string $name Parameter name
372 * @param $string $value Parameter value
373 * @return bool Validity
375 function validateParam( $name, $value ) {
376 if ( in_array( $name, array( 'width', 'height' ) ) ) {
377 // Reject negative heights, widths
378 return ( $value > 0 );
379 } elseif( $name == 'lang' ) {
380 // Validate $code
381 if( !Language::isValidBuiltinCode( $value ) ) {
382 wfDebug( "Invalid user language code\n" );
383 return false;
385 return true;
387 // Only lang, width and height are acceptable keys
388 return false;
392 * @param array $params name=>value pairs of parameters
393 * @return string Filename to use
395 function makeParamString( $params ) {
396 $lang = '';
397 if( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
398 $params['lang'] = mb_strtolower( $params['lang'] );
399 $lang = "lang{$params['lang']}-";
401 if ( !isset( $params['width'] ) ) {
402 return false;
404 return "$lang{$params['width']}px";
407 function parseParamString( $str ) {
408 $m = false;
409 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
410 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
411 } elseif( preg_match( '/^(\d+)px$/', $str, $m ) ) {
412 return array( 'width' => $m[1], 'lang' => 'en' );
413 } else {
414 return false;
418 function getParamMap() {
419 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
423 * @param $params
424 * @return array
426 function getScriptParams( $params ) {
427 return array(
428 'width' => $params['width'],
429 'lang' => $params['lang'],