MediaWiki  master
SvgHandler.php
Go to the documentation of this file.
1 <?php
27 use Wikimedia\AtEase\AtEase;
28 use Wikimedia\ScopedCallback;
29 
35 class SvgHandler extends ImageHandler {
36  public const SVG_METADATA_VERSION = 2;
37 
38  private const SVG_DEFAULT_RENDER_LANG = 'en';
39 
44  private static $metaConversion = [
45  'originalwidth' => 'ImageWidth',
46  'originalheight' => 'ImageLength',
47  'description' => 'ImageDescription',
48  'title' => 'ObjectName',
49  ];
50 
51  public function isEnabled() {
52  $config = MediaWikiServices::getInstance()->getMainConfig();
53  $svgConverters = $config->get( MainConfigNames::SVGConverters );
54  $svgConverter = $config->get( MainConfigNames::SVGConverter );
55  if ( $config->get( MainConfigNames::SVGNativeRendering ) === true ) {
56  return true;
57  }
58  if ( !isset( $svgConverters[$svgConverter] ) ) {
59  wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering." );
60 
61  return false;
62  }
63 
64  return true;
65  }
66 
67  public function allowRenderingByUserAgent( $file ) {
68  $svgNativeRendering = MediaWikiServices::getInstance()
69  ->getMainConfig()->get( MainConfigNames::SVGNativeRendering );
70  if ( $svgNativeRendering === true ) {
71  // Don't do any transform for any SVG.
72  return true;
73  }
74  if ( $svgNativeRendering !== 'partial' ) {
75  // SVG images are always rasterized to PNG
76  return false;
77  }
78  $maxSVGFilesize = MediaWikiServices::getInstance()
79  ->getMainConfig()->get( MainConfigNames::SVGNativeRenderingSizeLimit );
80  // Browsers don't really support SVG translations, so always render them to PNG
81  // Files bigger than the limit are also rendered as PNG, as big files might be a tax on the user agent
82  return count( $this->getAvailableLanguages( $file ) ) <= 1
83  && $file->getSize() <= $maxSVGFilesize;
84  }
85 
86  public function mustRender( $file ) {
87  return !$this->allowRenderingByUserAgent( $file );
88  }
89 
90  public function isVectorized( $file ) {
91  return true;
92  }
93 
98  public function isAnimatedImage( $file ) {
99  # @todo Detect animated SVGs
100  $metadata = $this->validateMetadata( $file->getMetadataArray() );
101  if ( isset( $metadata['animated'] ) ) {
102  return $metadata['animated'];
103  }
104 
105  return false;
106  }
107 
120  public function getAvailableLanguages( File $file ) {
121  $langList = [];
122  $metadata = $this->validateMetadata( $file->getMetadataArray() );
123  if ( isset( $metadata['translations'] ) ) {
124  foreach ( $metadata['translations'] as $lang => $langType ) {
125  if ( $langType === SVGReader::LANG_FULL_MATCH ) {
126  $langList[] = strtolower( $lang );
127  }
128  }
129  }
130  return array_unique( $langList );
131  }
132 
148  public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
149  // Explicitly requested undetermined language (text without svg systemLanguage attribute)
150  if ( $userPreferredLanguage === 'und' ) {
151  return 'und';
152  }
153  foreach ( $svgLanguages as $svgLang ) {
154  if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
155  return $svgLang;
156  }
157  $trimmedSvgLang = $svgLang;
158  while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
159  $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
160  if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
161  return $svgLang;
162  }
163  }
164  }
165  return null;
166  }
167 
175  protected function getLanguageFromParams( array $params ) {
176  return $params['lang'] ?? $params['targetlang'] ?? self::SVG_DEFAULT_RENDER_LANG;
177  }
178 
185  public function getDefaultRenderLanguage( File $file ) {
186  return self::SVG_DEFAULT_RENDER_LANG;
187  }
188 
194  public function canAnimateThumbnail( $file ) {
195  return $this->allowRenderingByUserAgent( $file );
196  }
197 
203  public function normaliseParams( $image, &$params ) {
204  if ( parent::normaliseParams( $image, $params ) ) {
205  $params = $this->normaliseParamsInternal( $image, $params );
206  return true;
207  }
208 
209  return false;
210  }
211 
221  protected function normaliseParamsInternal( $image, $params ) {
222  $svgMaxSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGMaxSize );
223 
224  # Don't make an image bigger than wgMaxSVGSize on the smaller side
225  if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
226  if ( $params['physicalWidth'] > $svgMaxSize ) {
227  $srcWidth = $image->getWidth( $params['page'] );
228  $srcHeight = $image->getHeight( $params['page'] );
229  $params['physicalWidth'] = $svgMaxSize;
230  $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $svgMaxSize );
231  }
232  } elseif ( $params['physicalHeight'] > $svgMaxSize ) {
233  $srcWidth = $image->getWidth( $params['page'] );
234  $srcHeight = $image->getHeight( $params['page'] );
235  $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $svgMaxSize );
236  $params['physicalHeight'] = $svgMaxSize;
237  }
238  // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
239  // explicitly forced by user.
240  if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) {
241  unset( $params['targetlang'] );
242  }
243 
244  return $params;
245  }
246 
255  public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
256  if ( !$this->normaliseParams( $image, $params ) ) {
257  return new TransformParameterError( $params );
258  }
259  $clientWidth = $params['width'];
260  $clientHeight = $params['height'];
261  $physicalWidth = $params['physicalWidth'];
262  $physicalHeight = $params['physicalHeight'];
263  $lang = $this->getLanguageFromParams( $params );
264 
265  if ( $this->allowRenderingByUserAgent( $image ) ) {
266  // No transformation required for native rendering
267  return new ThumbnailImage( $image, $image->getURL(), false, $params );
268  }
269 
270  if ( $flags & self::TRANSFORM_LATER ) {
271  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
272  }
273 
274  $metadata = $this->validateMetadata( $image->getMetadataArray() );
275  if ( isset( $metadata['error'] ) ) {
276  $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
277 
278  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
279  }
280 
281  if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
282  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
283  wfMessage( 'thumbnail_dest_directory' ) );
284  }
285 
286  $srcPath = $image->getLocalRefPath();
287  if ( $srcPath === false ) { // Failed to get local copy
288  wfDebugLog( 'thumbnail',
289  sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
290  wfHostname(), $image->getName() ) );
291 
292  return new MediaTransformError( 'thumbnail_error',
293  $params['width'], $params['height'],
294  wfMessage( 'filemissing' )
295  );
296  }
297 
298  // Make a temp dir with a symlink to the local copy in it.
299  // This plays well with rsvg-convert policy for external entities.
300  // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
301  $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
302  $lnPath = "$tmpDir/" . basename( $srcPath );
303  $ok = mkdir( $tmpDir, 0771 );
304  if ( !$ok ) {
305  wfDebugLog( 'thumbnail',
306  sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
307  wfHostname(), $tmpDir ) );
308  return new MediaTransformError( 'thumbnail_error',
309  $params['width'], $params['height'],
310  wfMessage( 'thumbnail-temp-create' )->text()
311  );
312  }
313  $ok = symlink( $srcPath, $lnPath );
315  $cleaner = new ScopedCallback( static function () use ( $tmpDir, $lnPath ) {
316  AtEase::suppressWarnings();
317  unlink( $lnPath );
318  rmdir( $tmpDir );
319  AtEase::restoreWarnings();
320  } );
321  if ( !$ok ) {
322  // Fallback because symlink often fails on Windows
323  $ok = copy( $srcPath, $lnPath );
324  }
325  if ( !$ok ) {
326  wfDebugLog( 'thumbnail',
327  sprintf( 'Thumbnail failed on %s: could not link %s to %s',
328  wfHostname(), $lnPath, $srcPath ) );
329  return new MediaTransformError( 'thumbnail_error',
330  $params['width'], $params['height'],
331  wfMessage( 'thumbnail-temp-create' )
332  );
333  }
334 
335  $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
336  if ( $status === true ) {
337  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
338  }
339 
340  return $status; // MediaTransformError
341  }
342 
353  public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
354  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
355  $svgConverters = $mainConfig->get( MainConfigNames::SVGConverters );
356  $svgConverter = $mainConfig->get( MainConfigNames::SVGConverter );
357  $svgConverterPath = $mainConfig->get( MainConfigNames::SVGConverterPath );
358  $err = false;
359  $retval = '';
360  if ( isset( $svgConverters[$svgConverter] ) ) {
361  if ( is_array( $svgConverters[$svgConverter] ) ) {
362  // This is a PHP callable
363  $func = $svgConverters[$svgConverter][0];
364  if ( !is_callable( $func ) ) {
365  throw new UnexpectedValueException( "$func is not callable" );
366  }
367  $err = $func( $srcPath,
368  $dstPath,
369  $width,
370  $height,
371  $lang,
372  ...array_slice( $svgConverters[$svgConverter], 1 )
373  );
374  $retval = (bool)$err;
375  } else {
376  // External command
377  $path = $svgConverterPath ? Shell::escape( "{$svgConverterPath}/" ) : '';
378  $cmd = preg_replace_callback( '/\$(path\/|width|height|input|output)/',
379  static function ( $m ) use ( $path, $width, $height, $srcPath, $dstPath ) {
380  return [
381  '$path/' => $path,
382  '$width' => intval( $width ),
383  '$height' => intval( $height ),
384  '$input' => Shell::escape( $srcPath ),
385  '$output' => Shell::escape( $dstPath ),
386  ][$m[0]];
387  },
388  $svgConverters[$svgConverter]
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 
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 
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
501  }
502 
503  return self::METADATA_GOOD;
504  }
505 
506  protected function visibleMetadataFields() {
507  return [ 'objectname', 'imagedescription' ];
508  }
509 
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 
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 === ''
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 
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  if ( !isset( $params['width'] ) ) {
590  return false;
591  }
592 
593  return "$lang{$params['width']}px";
594  }
595 
596  public function parseParamString( $str ) {
597  $m = false;
598  // Language codes are supposed to be lowercase
599  if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
600  if ( LanguageCode::isWellFormedLanguageTag( $m[1] ) ) {
601  return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
602  }
603  return [ 'width' => array_pop( $m ), 'lang' => self::SVG_DEFAULT_RENDER_LANG ];
604  }
605  if ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
606  return [ 'width' => $m[1], 'lang' => self::SVG_DEFAULT_RENDER_LANG ];
607  }
608  return false;
609  }
610 
611  public function getParamMap() {
612  return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
613  }
614 
619  protected function getScriptParams( $params ) {
620  $scriptParams = [ 'width' => $params['width'] ];
621  if ( isset( $params['lang'] ) ) {
622  $scriptParams['lang'] = $params['lang'];
623  }
624 
625  return $scriptParams;
626  }
627 
628  public function getCommonMetaArray( File $file ) {
629  $metadata = $this->validateMetadata( $file->getMetadataArray() );
630  if ( !$metadata || isset( $metadata['error'] ) ) {
631  return [];
632  }
633  $stdMetadata = [];
634  foreach ( $metadata as $name => $value ) {
635  $tag = strtolower( $name );
636  if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
637  // Skip these. In the exif metadata stuff, it is assumed these
638  // are measured in px, which is not the case here.
639  continue;
640  }
641  if ( isset( self::$metaConversion[$tag] ) ) {
642  $tag = self::$metaConversion[$tag];
643  $stdMetadata[$tag] = $value;
644  }
645  }
646 
647  return $stdMetadata;
648  }
649 }
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTempDir()
Tries to get the system directory for temporary files.
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:70
getMetadataArray()
Get the unserialized handler-specific metadata STUB.
Definition: File.php:752
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Definition: File.php:2189
Media handler abstract base class for images.
static isWellFormedLanguageTag(string $code, bool $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
const METADATA_COMPATIBLE
static addMeta(&$array, $visibility, $type, $id, $value, $param=false)
This is used to generate an array element for each metadata value That array is then used to generate...
const METADATA_BAD
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
const METADATA_GOOD
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Basic media transform error class.
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
Executes shell commands.
Definition: Shell.php:46
const LANG_FULL_MATCH
Definition: SVGReader.php:41
Handler for SVG images.
Definition: SvgHandler.php:35
validateParam( $name, $value)
Definition: SvgHandler.php:559
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
Definition: SvgHandler.php:90
normaliseParams( $image, &$params)
Definition: SvgHandler.php:203
formatMetadata( $file, $context=false)
Definition: SvgHandler.php:515
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
Definition: SvgHandler.php:596
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
Definition: SvgHandler.php:86
getScriptParams( $params)
Definition: SvgHandler.php:619
makeParamString( $params)
Definition: SvgHandler.php:583
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
Definition: SvgHandler.php:628
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Definition: SvgHandler.php:255
validateMetadata( $unser)
Definition: SvgHandler.php:481
getLanguageFromParams(array $params)
Determines render language from image parameters This is a lowercase IETF language.
Definition: SvgHandler.php:175
getAvailableLanguages(File $file)
Which languages (systemLanguage attribute) is supported.
Definition: SvgHandler.php:120
getLongDesc( $file)
Subtitle for the image.
Definition: SvgHandler.php:439
normaliseParamsInternal( $image, $params)
Code taken out of normaliseParams() for testability.
Definition: SvgHandler.php:221
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: SvgHandler.php:489
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: SvgHandler.php:426
getDefaultRenderLanguage(File $file)
What language to render file in if none selected.
Definition: SvgHandler.php:185
rasterize( $srcPath, $dstPath, $width, $height, $lang=false)
Transform an SVG file to PNG This function can be called outside of thumbnail contexts.
Definition: SvgHandler.php:353
getSizeAndMetadata( $state, $filename)
Definition: SvgHandler.php:459
isEnabled()
False if the handler is disabled for all files.
Definition: SvgHandler.php:51
canAnimateThumbnail( $file)
We do not support making animated svg thumbnails.
Definition: SvgHandler.php:194
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
Definition: SvgHandler.php:506
static rasterizeImagickExt( $srcPath, $dstPath, $width, $height)
Definition: SvgHandler.php:411
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: SvgHandler.php:493
isAnimatedImage( $file)
Definition: SvgHandler.php:98
getMatchedLanguage( $userPreferredLanguage, array $svgLanguages)
SVG's systemLanguage matching rules state: 'The systemLanguage attribute ...
Definition: SvgHandler.php:148
const SVG_METADATA_VERSION
Definition: SvgHandler.php:36
allowRenderingByUserAgent( $file)
Definition: SvgHandler.php:67
getParamMap()
Get an associative array mapping magic word IDs to parameter names.Will be used by the parser to iden...
Definition: SvgHandler.php:611
Media transform output for images.
Shortcut class for parameter validation errors.
$mime
Definition: router.php:60
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
if(!is_readable( $file)) $ext
Definition: router.php:48