457137bd58f4e6002ff9650db86249e622ee26fe
[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 * @param File $file
111 * @return string Language code.
112 */
113 public function getDefaultRenderLanguage( File $file ) {
114 return 'en';
115 }
116
117 /**
118 * We do not support making animated svg thumbnails
119 * @param File $file
120 * @return bool
121 */
122 function canAnimateThumbnail( $file ) {
123 return false;
124 }
125
126 /**
127 * @param File $image
128 * @param array $params
129 * @return bool
130 */
131 function normaliseParams( $image, &$params ) {
132 global $wgSVGMaxSize;
133 if ( !parent::normaliseParams( $image, $params ) ) {
134 return false;
135 }
136 # Don't make an image bigger than wgMaxSVGSize on the smaller side
137 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
138 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
139 $srcWidth = $image->getWidth( $params['page'] );
140 $srcHeight = $image->getHeight( $params['page'] );
141 $params['physicalWidth'] = $wgSVGMaxSize;
142 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
143 }
144 } else {
145 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
146 $srcWidth = $image->getWidth( $params['page'] );
147 $srcHeight = $image->getHeight( $params['page'] );
148 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
149 $params['physicalHeight'] = $wgSVGMaxSize;
150 }
151 }
152
153 return true;
154 }
155
156 /**
157 * @param File $image
158 * @param string $dstPath
159 * @param string $dstUrl
160 * @param array $params
161 * @param int $flags
162 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
163 */
164 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
165 if ( !$this->normaliseParams( $image, $params ) ) {
166 return new TransformParameterError( $params );
167 }
168 $clientWidth = $params['width'];
169 $clientHeight = $params['height'];
170 $physicalWidth = $params['physicalWidth'];
171 $physicalHeight = $params['physicalHeight'];
172 $lang = isset( $params['lang'] ) ? $params['lang'] : $this->getDefaultRenderLanguage( $image );
173
174 if ( $flags & self::TRANSFORM_LATER ) {
175 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
176 }
177
178 $metadata = $this->unpackMetadata( $image->getMetadata() );
179 if ( isset( $metadata['error'] ) ) { // sanity check
180 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
181
182 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
183 }
184
185 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
186 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
187 wfMessage( 'thumbnail_dest_directory' )->text() );
188 }
189
190 $srcPath = $image->getLocalRefPath();
191 if ( $srcPath === false ) { // Failed to get local copy
192 wfDebugLog( 'thumbnail',
193 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
194 wfHostname(), $image->getName() ) );
195
196 return new MediaTransformError( 'thumbnail_error',
197 $params['width'], $params['height'],
198 wfMessage( 'filemissing' )->text()
199 );
200 }
201
202 // Make a temp dir with a symlink to the local copy in it.
203 // This plays well with rsvg-convert policy for external entities.
204 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
205 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
206 $lnPath = "$tmpDir/" . basename( $srcPath );
207 $ok = mkdir( $tmpDir, 0771 );
208 if ( !$ok ) {
209 wfDebugLog( 'thumbnail',
210 sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
211 wfHostname(), $tmpDir ) );
212 return new MediaTransformError( 'thumbnail_error',
213 $params['width'], $params['height'],
214 wfMessage( 'thumbnail-temp-create' )->text()
215 );
216 }
217 $ok = symlink( $srcPath, $lnPath );
218 /** @noinspection PhpUnusedLocalVariableInspection */
219 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
220 MediaWiki\suppressWarnings();
221 unlink( $lnPath );
222 rmdir( $tmpDir );
223 MediaWiki\restoreWarnings();
224 } );
225 if ( !$ok ) {
226 wfDebugLog( 'thumbnail',
227 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
228 wfHostname(), $lnPath, $srcPath ) );
229 return new MediaTransformError( 'thumbnail_error',
230 $params['width'], $params['height'],
231 wfMessage( 'thumbnail-temp-create' )->text()
232 );
233 }
234
235 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
236 if ( $status === true ) {
237 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
238 } else {
239 return $status; // MediaTransformError
240 }
241 }
242
243 /**
244 * Transform an SVG file to PNG
245 * This function can be called outside of thumbnail contexts
246 * @param string $srcPath
247 * @param string $dstPath
248 * @param string $width
249 * @param string $height
250 * @param bool|string $lang Language code of the language to render the SVG in
251 * @throws MWException
252 * @return bool|MediaTransformError
253 */
254 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
255 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
256 $err = false;
257 $retval = '';
258 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
259 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
260 // This is a PHP callable
261 $func = $wgSVGConverters[$wgSVGConverter][0];
262 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
263 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
264 if ( !is_callable( $func ) ) {
265 throw new MWException( "$func is not callable" );
266 }
267 $err = call_user_func_array( $func, $args );
268 $retval = (bool)$err;
269 } else {
270 // External command
271 $cmd = str_replace(
272 array( '$path/', '$width', '$height', '$input', '$output' ),
273 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
274 intval( $width ),
275 intval( $height ),
276 wfEscapeShellArg( $srcPath ),
277 wfEscapeShellArg( $dstPath ) ),
278 $wgSVGConverters[$wgSVGConverter]
279 );
280
281 $env = array();
282 if ( $lang !== false ) {
283 $env['LANG'] = $lang;
284 }
285
286 wfDebug( __METHOD__ . ": $cmd\n" );
287 $err = wfShellExecWithStderr( $cmd, $retval, $env );
288 }
289 }
290 $removed = $this->removeBadFile( $dstPath, $retval );
291 if ( $retval != 0 || $removed ) {
292 $this->logErrorForExternalProcess( $retval, $err, $cmd );
293 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
294 }
295
296 return true;
297 }
298
299 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
300 $im = new Imagick( $srcPath );
301 $im->setImageFormat( 'png' );
302 $im->setBackgroundColor( 'transparent' );
303 $im->setImageDepth( 8 );
304
305 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
306 return 'Could not resize image';
307 }
308 if ( !$im->writeImage( $dstPath ) ) {
309 return "Could not write to $dstPath";
310 }
311 }
312
313 /**
314 * @param File $file
315 * @param string $path Unused
316 * @param bool|array $metadata
317 * @return array
318 */
319 function getImageSize( $file, $path, $metadata = false ) {
320 if ( $metadata === false ) {
321 $metadata = $file->getMetadata();
322 }
323 $metadata = $this->unpackMetadata( $metadata );
324
325 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
326 return array( $metadata['width'], $metadata['height'], 'SVG',
327 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
328 } else { // error
329 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
330 }
331 }
332
333 function getThumbType( $ext, $mime, $params = null ) {
334 return array( 'png', 'image/png' );
335 }
336
337 /**
338 * Subtitle for the image. Different from the base
339 * class so it can be denoted that SVG's have
340 * a "nominal" resolution, and not a fixed one,
341 * as well as so animation can be denoted.
342 *
343 * @param File $file
344 * @return string
345 */
346 function getLongDesc( $file ) {
347 global $wgLang;
348
349 $metadata = $this->unpackMetadata( $file->getMetadata() );
350 if ( isset( $metadata['error'] ) ) {
351 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
352 }
353
354 $size = $wgLang->formatSize( $file->getSize() );
355
356 if ( $this->isAnimatedImage( $file ) ) {
357 $msg = wfMessage( 'svg-long-desc-animated' );
358 } else {
359 $msg = wfMessage( 'svg-long-desc' );
360 }
361
362 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
363
364 return $msg->parse();
365 }
366
367 /**
368 * @param File $file
369 * @param string $filename
370 * @return string Serialised metadata
371 */
372 function getMetadata( $file, $filename ) {
373 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
374 try {
375 $metadata += SVGMetadataExtractor::getMetadata( $filename );
376 } catch ( Exception $e ) { // @todo SVG specific exceptions
377 // File not found, broken, etc.
378 $metadata['error'] = array(
379 'message' => $e->getMessage(),
380 'code' => $e->getCode()
381 );
382 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
383 }
384
385 return serialize( $metadata );
386 }
387
388 function unpackMetadata( $metadata ) {
389 MediaWiki\suppressWarnings();
390 $unser = unserialize( $metadata );
391 MediaWiki\restoreWarnings();
392 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
393 return $unser;
394 } else {
395 return false;
396 }
397 }
398
399 function getMetadataType( $image ) {
400 return 'parsed-svg';
401 }
402
403 function isMetadataValid( $image, $metadata ) {
404 $meta = $this->unpackMetadata( $metadata );
405 if ( $meta === false ) {
406 return self::METADATA_BAD;
407 }
408 if ( !isset( $meta['originalWidth'] ) ) {
409 // Old but compatible
410 return self::METADATA_COMPATIBLE;
411 }
412
413 return self::METADATA_GOOD;
414 }
415
416 protected function visibleMetadataFields() {
417 $fields = array( 'objectname', 'imagedescription' );
418
419 return $fields;
420 }
421
422 /**
423 * @param File $file
424 * @param bool|IContextSource $context Context to use (optional)
425 * @return array|bool
426 */
427 function formatMetadata( $file, $context = false ) {
428 $result = array(
429 'visible' => array(),
430 'collapsed' => array()
431 );
432 $metadata = $file->getMetadata();
433 if ( !$metadata ) {
434 return false;
435 }
436 $metadata = $this->unpackMetadata( $metadata );
437 if ( !$metadata || isset( $metadata['error'] ) ) {
438 return false;
439 }
440
441 /* @todo Add a formatter
442 $format = new FormatSVG( $metadata );
443 $formatted = $format->getFormattedData();
444 */
445
446 // Sort fields into visible and collapsed
447 $visibleFields = $this->visibleMetadataFields();
448
449 $showMeta = false;
450 foreach ( $metadata as $name => $value ) {
451 $tag = strtolower( $name );
452 if ( isset( self::$metaConversion[$tag] ) ) {
453 $tag = strtolower( self::$metaConversion[$tag] );
454 } else {
455 // Do not output other metadata not in list
456 continue;
457 }
458 $showMeta = true;
459 self::addMeta( $result,
460 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
461 'exif',
462 $tag,
463 $value
464 );
465 }
466
467 return $showMeta ? $result : false;
468 }
469
470 /**
471 * @param string $name Parameter name
472 * @param mixed $value Parameter value
473 * @return bool Validity
474 */
475 function validateParam( $name, $value ) {
476 if ( in_array( $name, array( 'width', 'height' ) ) ) {
477 // Reject negative heights, widths
478 return ( $value > 0 );
479 } elseif ( $name == 'lang' ) {
480 // Validate $code
481 if ( $value === '' || !Language::isValidBuiltinCode( $value ) ) {
482 wfDebug( "Invalid user language code\n" );
483
484 return false;
485 }
486
487 return true;
488 }
489
490 // Only lang, width and height are acceptable keys
491 return false;
492 }
493
494 /**
495 * @param array $params Name=>value pairs of parameters
496 * @return string Filename to use
497 */
498 function makeParamString( $params ) {
499 $lang = '';
500 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
501 $params['lang'] = strtolower( $params['lang'] );
502 $lang = "lang{$params['lang']}-";
503 }
504 if ( !isset( $params['width'] ) ) {
505 return false;
506 }
507
508 return "$lang{$params['width']}px";
509 }
510
511 function parseParamString( $str ) {
512 $m = false;
513 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
514 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
515 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
516 return array( 'width' => $m[1], 'lang' => 'en' );
517 } else {
518 return false;
519 }
520 }
521
522 function getParamMap() {
523 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
524 }
525
526 /**
527 * @param array $params
528 * @return array
529 */
530 function getScriptParams( $params ) {
531 $scriptParams = array( 'width' => $params['width'] );
532 if ( isset( $params['lang'] ) ) {
533 $scriptParams['lang'] = $params['lang'];
534 }
535
536 return $scriptParams;
537 }
538
539 public function getCommonMetaArray( File $file ) {
540 $metadata = $file->getMetadata();
541 if ( !$metadata ) {
542 return array();
543 }
544 $metadata = $this->unpackMetadata( $metadata );
545 if ( !$metadata || isset( $metadata['error'] ) ) {
546 return array();
547 }
548 $stdMetadata = array();
549 foreach ( $metadata as $name => $value ) {
550 $tag = strtolower( $name );
551 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
552 // Skip these. In the exif metadata stuff, it is assumed these
553 // are measured in px, which is not the case here.
554 continue;
555 }
556 if ( isset( self::$metaConversion[$tag] ) ) {
557 $tag = self::$metaConversion[$tag];
558 $stdMetadata[$tag] = $value;
559 }
560 }
561
562 return $stdMetadata;
563 }
564 }