generalize BitmapHandler::logErrorForExternalProcess
[lhc/web/wiklou.git] / includes / media / SVG.php
1 <?php
2 /**
3 * Handler for SVG images.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24 /**
25 * Handler for SVG images.
26 *
27 * @ingroup Media
28 */
29 class SvgHandler extends ImageHandler {
30 const SVG_METADATA_VERSION = 2;
31
32 /**
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:..}}
36 */
37 private static $metaConversion = array(
38 'originalwidth' => 'ImageWidth',
39 'originalheight' => 'ImageLength',
40 'description' => 'ImageDescription',
41 'title' => 'ObjectName',
42 );
43
44 function isEnabled() {
45 global $wgSVGConverters, $wgSVGConverter;
46 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
47 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
48
49 return false;
50 } else {
51 return true;
52 }
53 }
54
55 function mustRender( $file ) {
56 return true;
57 }
58
59 function isVectorized( $file ) {
60 return true;
61 }
62
63 /**
64 * @param $file File
65 * @return bool
66 */
67 function isAnimatedImage( $file ) {
68 # TODO: detect animated SVGs
69 $metadata = $file->getMetadata();
70 if ( $metadata ) {
71 $metadata = $this->unpackMetadata( $metadata );
72 if ( isset( $metadata['animated'] ) ) {
73 return $metadata['animated'];
74 }
75 }
76
77 return false;
78 }
79
80 /**
81 * We do not support making animated svg thumbnails
82 */
83 function canAnimateThumb( $file ) {
84 return false;
85 }
86
87 /**
88 * @param $image File
89 * @param $params
90 * @return bool
91 */
92 function normaliseParams( $image, &$params ) {
93 global $wgSVGMaxSize;
94 if ( !parent::normaliseParams( $image, $params ) ) {
95 return false;
96 }
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 );
104 }
105 } else {
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;
111 }
112 }
113
114 return true;
115 }
116
117 /**
118 * @param $image File
119 * @param $dstPath
120 * @param $dstUrl
121 * @param $params
122 * @param int $flags
123 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
124 */
125 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
126 if ( !$this->normaliseParams( $image, $params ) ) {
127 return new TransformParameterError( $params );
128 }
129 $clientWidth = $params['width'];
130 $clientHeight = $params['height'];
131 $physicalWidth = $params['physicalWidth'];
132 $physicalHeight = $params['physicalHeight'];
133 $lang = isset( $params['lang'] ) ? $params['lang'] : 'en';
134
135 if ( $flags & self::TRANSFORM_LATER ) {
136 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
137 }
138
139 $metadata = $this->unpackMetadata( $image->getMetadata() );
140 if ( isset( $metadata['error'] ) ) { // sanity check
141 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
142
143 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
144 }
145
146 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
147 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
148 wfMessage( 'thumbnail_dest_directory' )->text() );
149 }
150
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 );
155 } else {
156 return $status; // MediaTransformError
157 }
158 }
159
160 /**
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
170 */
171 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
172 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
173 $err = false;
174 $retval = '';
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" );
183 }
184 $err = call_user_func_array( $func, $args );
185 $retval = (bool)$err;
186 } else {
187 // External command
188 $cmd = str_replace(
189 array( '$path/', '$width', '$height', '$input', '$output' ),
190 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
191 intval( $width ),
192 intval( $height ),
193 wfEscapeShellArg( $srcPath ),
194 wfEscapeShellArg( $dstPath ) ),
195 $wgSVGConverters[$wgSVGConverter]
196 );
197
198 $env = array();
199 if ( $lang !== false ) {
200 $env['LANG'] = $lang;
201 }
202
203 wfProfileIn( 'rsvg' );
204 wfDebug( __METHOD__ . ": $cmd\n" );
205 $err = wfShellExecWithStderr( $cmd, $retval, $env );
206 wfProfileOut( 'rsvg' );
207 }
208 }
209 $removed = $this->removeBadFile( $dstPath, $retval );
210 if ( $retval != 0 || $removed ) {
211 $this->logErrorForExternalProcess( $retval, $err, $cmd );
212 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
213 }
214
215 return true;
216 }
217
218 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
219 $im = new Imagick( $srcPath );
220 $im->setImageFormat( 'png' );
221 $im->setBackgroundColor( 'transparent' );
222 $im->setImageDepth( 8 );
223
224 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
225 return 'Could not resize image';
226 }
227 if ( !$im->writeImage( $dstPath ) ) {
228 return "Could not write to $dstPath";
229 }
230 }
231
232 /**
233 * @param $file File
234 * @param $path
235 * @param bool $metadata
236 * @return array
237 */
238 function getImageSize( $file, $path, $metadata = false ) {
239 if ( $metadata === false ) {
240 $metadata = $file->getMetaData();
241 }
242 $metadata = $this->unpackMetaData( $metadata );
243
244 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
245 return array( $metadata['width'], $metadata['height'], 'SVG',
246 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
247 } else { // error
248 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
249 }
250 }
251
252 function getThumbType( $ext, $mime, $params = null ) {
253 return array( 'png', 'image/png' );
254 }
255
256 /**
257 * Subtitle for the image. Different from the base
258 * class so it can be denoted that SVG's have
259 * a "nominal" resolution, and not a fixed one,
260 * as well as so animation can be denoted.
261 *
262 * @param $file File
263 * @return string
264 */
265 function getLongDesc( $file ) {
266 global $wgLang;
267
268 $metadata = $this->unpackMetadata( $file->getMetadata() );
269 if ( isset( $metadata['error'] ) ) {
270 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
271 }
272
273 $size = $wgLang->formatSize( $file->getSize() );
274
275 if ( $this->isAnimatedImage( $file ) ) {
276 $msg = wfMessage( 'svg-long-desc-animated' );
277 } else {
278 $msg = wfMessage( 'svg-long-desc' );
279 }
280
281 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
282
283 return $msg->parse();
284 }
285
286 function getMetadata( $file, $filename ) {
287 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
288 try {
289 $metadata += SVGMetadataExtractor::getMetadata( $filename );
290 } catch ( MWException $e ) { // @todo SVG specific exceptions
291 // File not found, broken, etc.
292 $metadata['error'] = array(
293 'message' => $e->getMessage(),
294 'code' => $e->getCode()
295 );
296 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
297 }
298
299 return serialize( $metadata );
300 }
301
302 function unpackMetadata( $metadata ) {
303 wfSuppressWarnings();
304 $unser = unserialize( $metadata );
305 wfRestoreWarnings();
306 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
307 return $unser;
308 } else {
309 return false;
310 }
311 }
312
313 function getMetadataType( $image ) {
314 return 'parsed-svg';
315 }
316
317 function isMetadataValid( $image, $metadata ) {
318 $meta = $this->unpackMetadata( $metadata );
319 if ( $meta === false ) {
320 return self::METADATA_BAD;
321 }
322 if ( !isset( $meta['originalWidth'] ) ) {
323 // Old but compatible
324 return self::METADATA_COMPATIBLE;
325 }
326
327 return self::METADATA_GOOD;
328 }
329
330 function visibleMetadataFields() {
331 $fields = array( 'objectname', 'imagedescription' );
332
333 return $fields;
334 }
335
336 /**
337 * @param $file File
338 * @return array|bool
339 */
340 function formatMetadata( $file ) {
341 $result = array(
342 'visible' => array(),
343 'collapsed' => array()
344 );
345 $metadata = $file->getMetadata();
346 if ( !$metadata ) {
347 return false;
348 }
349 $metadata = $this->unpackMetadata( $metadata );
350 if ( !$metadata || isset( $metadata['error'] ) ) {
351 return false;
352 }
353
354 /* TODO: add a formatter
355 $format = new FormatSVG( $metadata );
356 $formatted = $format->getFormattedData();
357 */
358
359 // Sort fields into visible and collapsed
360 $visibleFields = $this->visibleMetadataFields();
361
362 $showMeta = false;
363 foreach ( $metadata as $name => $value ) {
364 $tag = strtolower( $name );
365 if ( isset( self::$metaConversion[$tag] ) ) {
366 $tag = strtolower( self::$metaConversion[$tag] );
367 } else {
368 // Do not output other metadata not in list
369 continue;
370 }
371 $showMeta = true;
372 self::addMeta( $result,
373 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
374 'exif',
375 $tag,
376 $value
377 );
378 }
379
380 return $showMeta ? $result : false;
381 }
382
383 /**
384 * @param string $name Parameter name
385 * @param $string $value Parameter value
386 * @return bool Validity
387 */
388 function validateParam( $name, $value ) {
389 if ( in_array( $name, array( 'width', 'height' ) ) ) {
390 // Reject negative heights, widths
391 return ( $value > 0 );
392 } elseif ( $name == 'lang' ) {
393 // Validate $code
394 if ( !Language::isValidBuiltinCode( $value ) ) {
395 wfDebug( "Invalid user language code\n" );
396
397 return false;
398 }
399
400 return true;
401 }
402
403 // Only lang, width and height are acceptable keys
404 return false;
405 }
406
407 /**
408 * @param array $params name=>value pairs of parameters
409 * @return string Filename to use
410 */
411 function makeParamString( $params ) {
412 $lang = '';
413 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
414 $params['lang'] = mb_strtolower( $params['lang'] );
415 $lang = "lang{$params['lang']}-";
416 }
417 if ( !isset( $params['width'] ) ) {
418 return false;
419 }
420
421 return "$lang{$params['width']}px";
422 }
423
424 function parseParamString( $str ) {
425 $m = false;
426 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
427 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
428 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
429 return array( 'width' => $m[1], 'lang' => 'en' );
430 } else {
431 return false;
432 }
433 }
434
435 function getParamMap() {
436 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
437 }
438
439 /**
440 * @param $params
441 * @return array
442 */
443 function getScriptParams( $params ) {
444 return array(
445 'width' => $params['width'],
446 'lang' => $params['lang'],
447 );
448 }
449
450 public function getCommonMetaArray( File $file ) {
451 $metadata = $file->getMetadata();
452 if ( !$metadata ) {
453 return array();
454 }
455 $metadata = $this->unpackMetadata( $metadata );
456 if ( !$metadata || isset( $metadata['error'] ) ) {
457 return array();
458 }
459 $stdMetadata = array();
460 foreach ( $metadata as $name => $value ) {
461 $tag = strtolower( $name );
462 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
463 // Skip these. In the exif metadata stuff, it is assumed these
464 // are measured in px, which is not the case here.
465 continue;
466 }
467 if ( isset( self::$metaConversion[$tag] ) ) {
468 $tag = self::$metaConversion[$tag];
469 $stdMetadata[$tag] = $value;
470 }
471 }
472
473 return $stdMetadata;
474 }
475 }