Note that jquery.json will be removed in 1.25
[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 /** @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:..}}
35 */
36 private static $metaConversion = array(
37 'originalwidth' => 'ImageWidth',
38 'originalheight' => 'ImageLength',
39 'description' => 'ImageDescription',
40 'title' => 'ObjectName',
41 );
42
43 function isEnabled() {
44 global $wgSVGConverters, $wgSVGConverter;
45 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
46 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
47
48 return false;
49 } else {
50 return true;
51 }
52 }
53
54 function mustRender( $file ) {
55 return true;
56 }
57
58 function isVectorized( $file ) {
59 return true;
60 }
61
62 /**
63 * @param File $file
64 * @return bool
65 */
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'];
73 }
74 }
75
76 return false;
77 }
78
79 /**
80 * Which languages (systemLanguage attribute) is supported.
81 *
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.
87 *
88 * @param File $file
89 * @return array Array of language codes, or empty if no language switching supported.
90 */
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;
100 }
101 }
102 }
103 }
104 return $langList;
105 }
106
107 /**
108 * What language to render file in if none selected.
109 *
110 * @return string Language code.
111 */
112 public function getDefaultRenderLanguage( File $file ) {
113 return 'en';
114 }
115
116 /**
117 * We do not support making animated svg thumbnails
118 */
119 function canAnimateThumbnail( $file ) {
120 return false;
121 }
122
123 /**
124 * @param File $image
125 * @param array $params
126 * @return bool
127 */
128 function normaliseParams( $image, &$params ) {
129 global $wgSVGMaxSize;
130 if ( !parent::normaliseParams( $image, $params ) ) {
131 return false;
132 }
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 );
140 }
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;
147 }
148 }
149
150 return true;
151 }
152
153 /**
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
160 */
161 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
162 if ( !$this->normaliseParams( $image, $params ) ) {
163 return new TransformParameterError( $params );
164 }
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 );
170
171 if ( $flags & self::TRANSFORM_LATER ) {
172 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
173 }
174
175 $metadata = $this->unpackMetadata( $image->getMetadata() );
176 if ( isset( $metadata['error'] ) ) { // sanity check
177 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
178
179 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
180 }
181
182 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
183 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
184 wfMessage( 'thumbnail_dest_directory' )->text() );
185 }
186
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
193 }
194 }
195
196 /**
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
206 */
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" );
219 }
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]
232 );
233
234 $env = array();
235 if ( $lang !== false ) {
236 $env['LANG'] = $lang;
237 }
238
239 wfProfileIn( 'rsvg' );
240 wfDebug( __METHOD__ . ": $cmd\n" );
241 $err = wfShellExecWithStderr( $cmd, $retval, $env );
242 wfProfileOut( 'rsvg' );
243 }
244 }
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 );
249 }
250
251 return true;
252 }
253
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 );
259
260 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
261 return 'Could not resize image';
262 }
263 if ( !$im->writeImage( $dstPath ) ) {
264 return "Could not write to $dstPath";
265 }
266 }
267
268 /**
269 * @param File $file
270 * @param string $path Unused
271 * @param bool|array $metadata
272 * @return array
273 */
274 function getImageSize( $file, $path, $metadata = false ) {
275 if ( $metadata === false ) {
276 $metadata = $file->getMetaData();
277 }
278 $metadata = $this->unpackMetaData( $metadata );
279
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\"" );
285 }
286 }
287
288 function getThumbType( $ext, $mime, $params = null ) {
289 return array( 'png', 'image/png' );
290 }
291
292 /**
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.
297 *
298 * @param File $file
299 * @return string
300 */
301 function getLongDesc( $file ) {
302 global $wgLang;
303
304 $metadata = $this->unpackMetadata( $file->getMetadata() );
305 if ( isset( $metadata['error'] ) ) {
306 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
307 }
308
309 $size = $wgLang->formatSize( $file->getSize() );
310
311 if ( $this->isAnimatedImage( $file ) ) {
312 $msg = wfMessage( 'svg-long-desc-animated' );
313 } else {
314 $msg = wfMessage( 'svg-long-desc' );
315 }
316
317 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
318
319 return $msg->parse();
320 }
321
322 /**
323 * @param File $file
324 * @param string $filename
325 * @return string Serialised metadata
326 */
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()
336 );
337 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
338 }
339
340 return serialize( $metadata );
341 }
342
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;
351 }
352 }
353
354 function getMetadataType( $image ) {
355 return 'parsed-svg';
356 }
357
358 function isMetadataValid( $image, $metadata ) {
359 $meta = $this->unpackMetadata( $metadata );
360 if ( $meta === false ) {
361 return self::METADATA_BAD;
362 }
363 if ( !isset( $meta['originalWidth'] ) ) {
364 // Old but compatible
365 return self::METADATA_COMPATIBLE;
366 }
367
368 return self::METADATA_GOOD;
369 }
370
371 protected function visibleMetadataFields() {
372 $fields = array( 'objectname', 'imagedescription' );
373
374 return $fields;
375 }
376
377 /**
378 * @param File $file
379 * @return array|bool
380 */
381 function formatMetadata( $file ) {
382 $result = array(
383 'visible' => array(),
384 'collapsed' => array()
385 );
386 $metadata = $file->getMetadata();
387 if ( !$metadata ) {
388 return false;
389 }
390 $metadata = $this->unpackMetadata( $metadata );
391 if ( !$metadata || isset( $metadata['error'] ) ) {
392 return false;
393 }
394
395 /* @todo Add a formatter
396 $format = new FormatSVG( $metadata );
397 $formatted = $format->getFormattedData();
398 */
399
400 // Sort fields into visible and collapsed
401 $visibleFields = $this->visibleMetadataFields();
402
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;
411 }
412 $showMeta = true;
413 self::addMeta( $result,
414 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
415 'exif',
416 $tag,
417 $value
418 );
419 }
420
421 return $showMeta ? $result : false;
422 }
423
424 /**
425 * @param string $name Parameter name
426 * @param mixed $value Parameter value
427 * @return bool Validity
428 */
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 ( $value === '' || !Language::isValidBuiltinCode( $value ) ) {
436 wfDebug( "Invalid user language code\n" );
437
438 return false;
439 }
440
441 return true;
442 }
443
444 // Only lang, width and height are acceptable keys
445 return false;
446 }
447
448 /**
449 * @param array $params name=>value pairs of parameters
450 * @return string Filename to use
451 */
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']}-";
457 }
458 if ( !isset( $params['width'] ) ) {
459 return false;
460 }
461
462 return "$lang{$params['width']}px";
463 }
464
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;
473 }
474 }
475
476 function getParamMap() {
477 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
478 }
479
480 /**
481 * @param array $params
482 * @return array
483 */
484 function getScriptParams( $params ) {
485 $scriptParams = array( 'width' => $params['width'] );
486 if ( isset( $params['lang'] ) ) {
487 $scriptParams['lang'] = $params['lang'];
488 }
489
490 return $scriptParams;
491 }
492
493 public function getCommonMetaArray( File $file ) {
494 $metadata = $file->getMetadata();
495 if ( !$metadata ) {
496 return array();
497 }
498 $metadata = $this->unpackMetadata( $metadata );
499 if ( !$metadata || isset( $metadata['error'] ) ) {
500 return array();
501 }
502 $stdMetadata = array();
503 foreach ( $metadata as $name => $value ) {
504 $tag = strtolower( $name );
505 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
506 // Skip these. In the exif metadata stuff, it is assumed these
507 // are measured in px, which is not the case here.
508 continue;
509 }
510 if ( isset( self::$metaConversion[$tag] ) ) {
511 $tag = self::$metaConversion[$tag];
512 $stdMetadata[$tag] = $value;
513 }
514 }
515
516 return $stdMetadata;
517 }
518 }