Debian Codegraph @

includes/media/SvgHandler.php

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