d06acd87b1ff0b03f52c369b3f3557152efa3eb2
[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 wfDebugLog( 'thumbnail', sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
212 wfHostname(), $retval, trim( $err ), $cmd ) );
213
214 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
215 }
216
217 return true;
218 }
219
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 );
225
226 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
227 return 'Could not resize image';
228 }
229 if ( !$im->writeImage( $dstPath ) ) {
230 return "Could not write to $dstPath";
231 }
232 }
233
234 /**
235 * @param $file File
236 * @param $path
237 * @param bool $metadata
238 * @return array
239 */
240 function getImageSize( $file, $path, $metadata = false ) {
241 if ( $metadata === false ) {
242 $metadata = $file->getMetaData();
243 }
244 $metadata = $this->unpackMetaData( $metadata );
245
246 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
247 return array( $metadata['width'], $metadata['height'], 'SVG',
248 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
249 } else { // error
250 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
251 }
252 }
253
254 function getThumbType( $ext, $mime, $params = null ) {
255 return array( 'png', 'image/png' );
256 }
257
258 /**
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.
263 *
264 * @param $file File
265 * @return string
266 */
267 function getLongDesc( $file ) {
268 global $wgLang;
269
270 $metadata = $this->unpackMetadata( $file->getMetadata() );
271 if ( isset( $metadata['error'] ) ) {
272 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
273 }
274
275 $size = $wgLang->formatSize( $file->getSize() );
276
277 if ( $this->isAnimatedImage( $file ) ) {
278 $msg = wfMessage( 'svg-long-desc-animated' );
279 } else {
280 $msg = wfMessage( 'svg-long-desc' );
281 }
282
283 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
284
285 return $msg->parse();
286 }
287
288 function getMetadata( $file, $filename ) {
289 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
290 try {
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()
297 );
298 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
299 }
300
301 return serialize( $metadata );
302 }
303
304 function unpackMetadata( $metadata ) {
305 wfSuppressWarnings();
306 $unser = unserialize( $metadata );
307 wfRestoreWarnings();
308 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
309 return $unser;
310 } else {
311 return false;
312 }
313 }
314
315 function getMetadataType( $image ) {
316 return 'parsed-svg';
317 }
318
319 function isMetadataValid( $image, $metadata ) {
320 $meta = $this->unpackMetadata( $metadata );
321 if ( $meta === false ) {
322 return self::METADATA_BAD;
323 }
324 if ( !isset( $meta['originalWidth'] ) ) {
325 // Old but compatible
326 return self::METADATA_COMPATIBLE;
327 }
328
329 return self::METADATA_GOOD;
330 }
331
332 function visibleMetadataFields() {
333 $fields = array( 'objectname', 'imagedescription' );
334
335 return $fields;
336 }
337
338 /**
339 * @param $file File
340 * @return array|bool
341 */
342 function formatMetadata( $file ) {
343 $result = array(
344 'visible' => array(),
345 'collapsed' => array()
346 );
347 $metadata = $file->getMetadata();
348 if ( !$metadata ) {
349 return false;
350 }
351 $metadata = $this->unpackMetadata( $metadata );
352 if ( !$metadata || isset( $metadata['error'] ) ) {
353 return false;
354 }
355
356 /* TODO: add a formatter
357 $format = new FormatSVG( $metadata );
358 $formatted = $format->getFormattedData();
359 */
360
361 // Sort fields into visible and collapsed
362 $visibleFields = $this->visibleMetadataFields();
363
364 $showMeta = false;
365 foreach ( $metadata as $name => $value ) {
366 $tag = strtolower( $name );
367 if ( isset( self::$metaConversion[$tag] ) ) {
368 $tag = strtolower( self::$metaConversion[$tag] );
369 } else {
370 // Do not output other metadata not in list
371 continue;
372 }
373 $showMeta = true;
374 self::addMeta( $result,
375 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
376 'exif',
377 $tag,
378 $value
379 );
380 }
381
382 return $showMeta ? $result : false;
383 }
384
385 /**
386 * @param string $name Parameter name
387 * @param $string $value Parameter value
388 * @return bool Validity
389 */
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' ) {
395 // Validate $code
396 if ( !Language::isValidBuiltinCode( $value ) ) {
397 wfDebug( "Invalid user language code\n" );
398
399 return false;
400 }
401
402 return true;
403 }
404
405 // Only lang, width and height are acceptable keys
406 return false;
407 }
408
409 /**
410 * @param array $params name=>value pairs of parameters
411 * @return string Filename to use
412 */
413 function makeParamString( $params ) {
414 $lang = '';
415 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
416 $params['lang'] = mb_strtolower( $params['lang'] );
417 $lang = "lang{$params['lang']}-";
418 }
419 if ( !isset( $params['width'] ) ) {
420 return false;
421 }
422
423 return "$lang{$params['width']}px";
424 }
425
426 function parseParamString( $str ) {
427 $m = false;
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' );
432 } else {
433 return false;
434 }
435 }
436
437 function getParamMap() {
438 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
439 }
440
441 /**
442 * @param $params
443 * @return array
444 */
445 function getScriptParams( $params ) {
446 return array(
447 'width' => $params['width'],
448 'lang' => $params['lang'],
449 );
450 }
451
452 public function getCommonMetaArray( File $file ) {
453 $metadata = $file->getMetadata();
454 if ( !$metadata ) {
455 return array();
456 }
457 $metadata = $this->unpackMetadata( $metadata );
458 if ( !$metadata || isset( $metadata['error'] ) ) {
459 return array();
460 }
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.
467 continue;
468 }
469 if ( isset( self::$metaConversion[$tag] ) ) {
470 $tag = self::$metaConversion[$tag];
471 $stdMetadata[$tag] = $value;
472 }
473 }
474
475 return $stdMetadata;
476 }
477 }