Merge "Only expand `{{...}}` in messages once (part 2)"
[lhc/web/wiklou.git] / includes / media / SvgHandler.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 use Wikimedia\ScopedCallback;
24
25 /**
26 * Handler for SVG images.
27 *
28 * @ingroup Media
29 */
30 class SvgHandler extends ImageHandler {
31 const SVG_METADATA_VERSION = 2;
32
33 /** @var array 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 = [
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 public 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 * Which languages (systemLanguage attribute) is supported.
82 *
83 * @note This list is not guaranteed to be exhaustive.
84 * To avoid OOM errors, we only look at first bit of a file.
85 * Thus all languages on this list are present in the file,
86 * but its possible for the file to have a language not on
87 * this list.
88 *
89 * @param File $file
90 * @return array Array of language codes, or empty if no language switching supported.
91 */
92 public function getAvailableLanguages( File $file ) {
93 $metadata = $file->getMetadata();
94 $langList = [];
95 if ( $metadata ) {
96 $metadata = $this->unpackMetadata( $metadata );
97 if ( isset( $metadata['translations'] ) ) {
98 foreach ( $metadata['translations'] as $lang => $langType ) {
99 if ( $langType === SVGReader::LANG_FULL_MATCH ) {
100 $langList[] = strtolower( $lang );
101 }
102 }
103 }
104 }
105 return array_unique( $langList );
106 }
107
108 /**
109 * SVG's systemLanguage matching rules state:
110 * 'The `systemLanguage` attribute ... [e]valuates to "true" if one of the languages indicated
111 * by user preferences exactly equals one of the languages given in the value of this parameter,
112 * or if one of the languages indicated by user preferences exactly equals a prefix of one of
113 * the languages given in the value of this parameter such that the first tag character
114 * following the prefix is "-".'
115 *
116 * Return the first element of $svgLanguages that matches $userPreferredLanguage
117 *
118 * @see https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
119 * @param string $userPreferredLanguage
120 * @param array $svgLanguages
121 * @return string|null
122 */
123 public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
124 foreach ( $svgLanguages as $svgLang ) {
125 if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
126 return $svgLang;
127 }
128 $trimmedSvgLang = $svgLang;
129 while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
130 $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
131 if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
132 return $svgLang;
133 }
134 }
135 }
136 return null;
137 }
138
139 /**
140 * Determines render language from image parameters
141 *
142 * @param array $params
143 * @return string
144 */
145 protected function getLanguageFromParams( array $params ) {
146 return $params['lang'] ?? $params['targetlang'] ?? 'en';
147 }
148
149 /**
150 * What language to render file in if none selected
151 *
152 * @param File $file Language code
153 * @return string
154 */
155 public function getDefaultRenderLanguage( File $file ) {
156 return 'en';
157 }
158
159 /**
160 * We do not support making animated svg thumbnails
161 * @param File $file
162 * @return bool
163 */
164 function canAnimateThumbnail( $file ) {
165 return false;
166 }
167
168 /**
169 * @param File $image
170 * @param array &$params
171 * @return bool
172 */
173 public function normaliseParams( $image, &$params ) {
174 if ( parent::normaliseParams( $image, $params ) ) {
175 $params = $this->normaliseParamsInternal( $image, $params );
176 return true;
177 }
178
179 return false;
180 }
181
182 /**
183 * Code taken out of normaliseParams() for testability
184 *
185 * @since 1.33
186 *
187 * @param File $image
188 * @param array $params
189 * @return array Modified $params
190 */
191 protected function normaliseParamsInternal( $image, $params ) {
192 global $wgSVGMaxSize;
193
194 # Don't make an image bigger than wgMaxSVGSize on the smaller side
195 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
196 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
197 $srcWidth = $image->getWidth( $params['page'] );
198 $srcHeight = $image->getHeight( $params['page'] );
199 $params['physicalWidth'] = $wgSVGMaxSize;
200 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
201 }
202 } else {
203 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
204 $srcWidth = $image->getWidth( $params['page'] );
205 $srcHeight = $image->getHeight( $params['page'] );
206 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
207 $params['physicalHeight'] = $wgSVGMaxSize;
208 }
209 }
210 // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
211 // explicitly forced by user.
212 if ( isset( $params['targetlang'] ) ) {
213 if ( !$image->getMatchedLanguage( $params['targetlang'] ) ) {
214 unset( $params['targetlang'] );
215 }
216 }
217
218 return $params;
219 }
220
221 /**
222 * @param File $image
223 * @param string $dstPath
224 * @param string $dstUrl
225 * @param array $params
226 * @param int $flags
227 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
228 */
229 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
230 if ( !$this->normaliseParams( $image, $params ) ) {
231 return new TransformParameterError( $params );
232 }
233 $clientWidth = $params['width'];
234 $clientHeight = $params['height'];
235 $physicalWidth = $params['physicalWidth'];
236 $physicalHeight = $params['physicalHeight'];
237 $lang = $this->getLanguageFromParams( $params );
238
239 if ( $flags & self::TRANSFORM_LATER ) {
240 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
241 }
242
243 $metadata = $this->unpackMetadata( $image->getMetadata() );
244 if ( isset( $metadata['error'] ) ) { // sanity check
245 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
246
247 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
248 }
249
250 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
251 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
252 wfMessage( 'thumbnail_dest_directory' ) );
253 }
254
255 $srcPath = $image->getLocalRefPath();
256 if ( $srcPath === false ) { // Failed to get local copy
257 wfDebugLog( 'thumbnail',
258 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
259 wfHostname(), $image->getName() ) );
260
261 return new MediaTransformError( 'thumbnail_error',
262 $params['width'], $params['height'],
263 wfMessage( 'filemissing' )
264 );
265 }
266
267 // Make a temp dir with a symlink to the local copy in it.
268 // This plays well with rsvg-convert policy for external entities.
269 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
270 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
271 $lnPath = "$tmpDir/" . basename( $srcPath );
272 $ok = mkdir( $tmpDir, 0771 );
273 if ( !$ok ) {
274 wfDebugLog( 'thumbnail',
275 sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
276 wfHostname(), $tmpDir ) );
277 return new MediaTransformError( 'thumbnail_error',
278 $params['width'], $params['height'],
279 wfMessage( 'thumbnail-temp-create' )->text()
280 );
281 }
282 $ok = symlink( $srcPath, $lnPath );
283 /** @noinspection PhpUnusedLocalVariableInspection */
284 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
285 Wikimedia\suppressWarnings();
286 unlink( $lnPath );
287 rmdir( $tmpDir );
288 Wikimedia\restoreWarnings();
289 } );
290 if ( !$ok ) {
291 wfDebugLog( 'thumbnail',
292 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
293 wfHostname(), $lnPath, $srcPath ) );
294 return new MediaTransformError( 'thumbnail_error',
295 $params['width'], $params['height'],
296 wfMessage( 'thumbnail-temp-create' )
297 );
298 }
299
300 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
301 if ( $status === true ) {
302 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
303 } else {
304 return $status; // MediaTransformError
305 }
306 }
307
308 /**
309 * Transform an SVG file to PNG
310 * This function can be called outside of thumbnail contexts
311 * @param string $srcPath
312 * @param string $dstPath
313 * @param string $width
314 * @param string $height
315 * @param bool|string $lang Language code of the language to render the SVG in
316 * @throws MWException
317 * @return bool|MediaTransformError
318 */
319 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
320 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
321 $err = false;
322 $retval = '';
323 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
324 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
325 // This is a PHP callable
326 $func = $wgSVGConverters[$wgSVGConverter][0];
327 if ( !is_callable( $func ) ) {
328 throw new MWException( "$func is not callable" );
329 }
330 $err = $func( $srcPath,
331 $dstPath,
332 $width,
333 $height,
334 $lang,
335 ...array_slice( $wgSVGConverters[$wgSVGConverter], 1 )
336 );
337 $retval = (bool)$err;
338 } else {
339 // External command
340 $cmd = str_replace(
341 [ '$path/', '$width', '$height', '$input', '$output' ],
342 [ $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
343 intval( $width ),
344 intval( $height ),
345 wfEscapeShellArg( $srcPath ),
346 wfEscapeShellArg( $dstPath ) ],
347 $wgSVGConverters[$wgSVGConverter]
348 );
349
350 $env = [];
351 if ( $lang !== false ) {
352 $env['LANG'] = $lang;
353 }
354
355 wfDebug( __METHOD__ . ": $cmd\n" );
356 $err = wfShellExecWithStderr( $cmd, $retval, $env );
357 }
358 }
359 $removed = $this->removeBadFile( $dstPath, $retval );
360 if ( $retval != 0 || $removed ) {
361 $this->logErrorForExternalProcess( $retval, $err, $cmd );
362 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
363 }
364
365 return true;
366 }
367
368 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
369 $im = new Imagick( $srcPath );
370 $im->setImageFormat( 'png' );
371 $im->setBackgroundColor( 'transparent' );
372 $im->setImageDepth( 8 );
373
374 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
375 return 'Could not resize image';
376 }
377 if ( !$im->writeImage( $dstPath ) ) {
378 return "Could not write to $dstPath";
379 }
380 }
381
382 /**
383 * @param File|FSFile $file
384 * @param string $path Unused
385 * @param bool|array $metadata
386 * @return array
387 */
388 function getImageSize( $file, $path, $metadata = false ) {
389 if ( $metadata === false && $file instanceof File ) {
390 $metadata = $file->getMetadata();
391 }
392 $metadata = $this->unpackMetadata( $metadata );
393
394 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
395 return [ $metadata['width'], $metadata['height'], 'SVG',
396 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" ];
397 } else { // error
398 return [ 0, 0, 'SVG', "width=\"0\" height=\"0\"" ];
399 }
400 }
401
402 function getThumbType( $ext, $mime, $params = null ) {
403 return [ 'png', 'image/png' ];
404 }
405
406 /**
407 * Subtitle for the image. Different from the base
408 * class so it can be denoted that SVG's have
409 * a "nominal" resolution, and not a fixed one,
410 * as well as so animation can be denoted.
411 *
412 * @param File $file
413 * @return string
414 */
415 function getLongDesc( $file ) {
416 global $wgLang;
417
418 $metadata = $this->unpackMetadata( $file->getMetadata() );
419 if ( isset( $metadata['error'] ) ) {
420 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
421 }
422
423 $size = $wgLang->formatSize( $file->getSize() );
424
425 if ( $this->isAnimatedImage( $file ) ) {
426 $msg = wfMessage( 'svg-long-desc-animated' );
427 } else {
428 $msg = wfMessage( 'svg-long-desc' );
429 }
430
431 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
432
433 return $msg->parse();
434 }
435
436 /**
437 * @param File|FSFile $file
438 * @param string $filename
439 * @return string Serialised metadata
440 */
441 function getMetadata( $file, $filename ) {
442 $metadata = [ 'version' => self::SVG_METADATA_VERSION ];
443 try {
444 $metadata += SVGMetadataExtractor::getMetadata( $filename );
445 } catch ( Exception $e ) { // @todo SVG specific exceptions
446 // File not found, broken, etc.
447 $metadata['error'] = [
448 'message' => $e->getMessage(),
449 'code' => $e->getCode()
450 ];
451 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
452 }
453
454 return serialize( $metadata );
455 }
456
457 function unpackMetadata( $metadata ) {
458 Wikimedia\suppressWarnings();
459 $unser = unserialize( $metadata );
460 Wikimedia\restoreWarnings();
461 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
462 return $unser;
463 } else {
464 return false;
465 }
466 }
467
468 function getMetadataType( $image ) {
469 return 'parsed-svg';
470 }
471
472 function isMetadataValid( $image, $metadata ) {
473 $meta = $this->unpackMetadata( $metadata );
474 if ( $meta === false ) {
475 return self::METADATA_BAD;
476 }
477 if ( !isset( $meta['originalWidth'] ) ) {
478 // Old but compatible
479 return self::METADATA_COMPATIBLE;
480 }
481
482 return self::METADATA_GOOD;
483 }
484
485 protected function visibleMetadataFields() {
486 $fields = [ 'objectname', 'imagedescription' ];
487
488 return $fields;
489 }
490
491 /**
492 * @param File $file
493 * @param bool|IContextSource $context Context to use (optional)
494 * @return array|bool
495 */
496 function formatMetadata( $file, $context = false ) {
497 $result = [
498 'visible' => [],
499 'collapsed' => []
500 ];
501 $metadata = $file->getMetadata();
502 if ( !$metadata ) {
503 return false;
504 }
505 $metadata = $this->unpackMetadata( $metadata );
506 if ( !$metadata || isset( $metadata['error'] ) ) {
507 return false;
508 }
509
510 /* @todo Add a formatter
511 $format = new FormatSVG( $metadata );
512 $formatted = $format->getFormattedData();
513 */
514
515 // Sort fields into visible and collapsed
516 $visibleFields = $this->visibleMetadataFields();
517
518 $showMeta = false;
519 foreach ( $metadata as $name => $value ) {
520 $tag = strtolower( $name );
521 if ( isset( self::$metaConversion[$tag] ) ) {
522 $tag = strtolower( self::$metaConversion[$tag] );
523 } else {
524 // Do not output other metadata not in list
525 continue;
526 }
527 $showMeta = true;
528 self::addMeta( $result,
529 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
530 'exif',
531 $tag,
532 $value
533 );
534 }
535
536 return $showMeta ? $result : false;
537 }
538
539 /**
540 * @param string $name Parameter name
541 * @param mixed $value Parameter value
542 * @return bool Validity
543 */
544 public function validateParam( $name, $value ) {
545 if ( in_array( $name, [ 'width', 'height' ] ) ) {
546 // Reject negative heights, widths
547 return ( $value > 0 );
548 } elseif ( $name == 'lang' ) {
549 // Validate $code
550 if ( $value === '' || !Language::isValidCode( $value ) ) {
551 return false;
552 }
553
554 return true;
555 }
556
557 // Only lang, width and height are acceptable keys
558 return false;
559 }
560
561 /**
562 * @param array $params Name=>value pairs of parameters
563 * @return string Filename to use
564 */
565 public function makeParamString( $params ) {
566 $lang = '';
567 $code = $this->getLanguageFromParams( $params );
568 if ( $code !== 'en' ) {
569 $lang = 'lang' . strtolower( $code ) . '-';
570 }
571 if ( !isset( $params['width'] ) ) {
572 return false;
573 }
574
575 return "$lang{$params['width']}px";
576 }
577
578 public function parseParamString( $str ) {
579 $m = false;
580 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
581 return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
582 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
583 return [ 'width' => $m[1], 'lang' => 'en' ];
584 } else {
585 return false;
586 }
587 }
588
589 public function getParamMap() {
590 return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
591 }
592
593 /**
594 * @param array $params
595 * @return array
596 */
597 function getScriptParams( $params ) {
598 $scriptParams = [ 'width' => $params['width'] ];
599 if ( isset( $params['lang'] ) ) {
600 $scriptParams['lang'] = $params['lang'];
601 }
602
603 return $scriptParams;
604 }
605
606 public function getCommonMetaArray( File $file ) {
607 $metadata = $file->getMetadata();
608 if ( !$metadata ) {
609 return [];
610 }
611 $metadata = $this->unpackMetadata( $metadata );
612 if ( !$metadata || isset( $metadata['error'] ) ) {
613 return [];
614 }
615 $stdMetadata = [];
616 foreach ( $metadata as $name => $value ) {
617 $tag = strtolower( $name );
618 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
619 // Skip these. In the exif metadata stuff, it is assumed these
620 // are measured in px, which is not the case here.
621 continue;
622 }
623 if ( isset( self::$metaConversion[$tag] ) ) {
624 $tag = self::$metaConversion[$tag];
625 $stdMetadata[$tag] = $value;
626 }
627 }
628
629 return $stdMetadata;
630 }
631 }