MediaWiki  master
SvgHandler.php
Go to the documentation of this file.
1 <?php
27 use Wikimedia\AtEase\AtEase;
28 use Wikimedia\RequestTimeout\TimeoutException;
29 use Wikimedia\ScopedCallback;
30 
36 class SvgHandler extends ImageHandler {
37  public const SVG_METADATA_VERSION = 2;
38 
43  private static $metaConversion = [
44  'originalwidth' => 'ImageWidth',
45  'originalheight' => 'ImageLength',
46  'description' => 'ImageDescription',
47  'title' => 'ObjectName',
48  ];
49 
50  public function isEnabled() {
51  $svgConverters = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverters );
52  $svgConverter = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGConverter );
53  if ( !isset( $svgConverters[$svgConverter] ) ) {
54  wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering." );
55 
56  return false;
57  } else {
58  return true;
59  }
60  }
61 
62  public function mustRender( $file ) {
63  return true;
64  }
65 
66  public function isVectorized( $file ) {
67  return true;
68  }
69 
74  public function isAnimatedImage( $file ) {
75  # @todo Detect animated SVGs
76  $metadata = $this->validateMetadata( $file->getMetadataArray() );
77  if ( isset( $metadata['animated'] ) ) {
78  return $metadata['animated'];
79  }
80 
81  return false;
82  }
83 
96  public function getAvailableLanguages( File $file ) {
97  $langList = [];
98  $metadata = $this->validateMetadata( $file->getMetadataArray() );
99  if ( isset( $metadata['translations'] ) ) {
100  foreach ( $metadata['translations'] as $lang => $langType ) {
101  if ( $langType === SVGReader::LANG_FULL_MATCH ) {
102  $langList[] = strtolower( $lang );
103  }
104  }
105  }
106  return array_unique( $langList );
107  }
108 
124  public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
125  foreach ( $svgLanguages as $svgLang ) {
126  if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
127  return $svgLang;
128  }
129  $trimmedSvgLang = $svgLang;
130  while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
131  $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
132  if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
133  return $svgLang;
134  }
135  }
136  }
137  return null;
138  }
139 
146  protected function getLanguageFromParams( array $params ) {
147  return $params['lang'] ?? $params['targetlang'] ?? 'en';
148  }
149 
156  public function getDefaultRenderLanguage( File $file ) {
157  return 'en';
158  }
159 
165  public function canAnimateThumbnail( $file ) {
166  return false;
167  }
168 
174  public function normaliseParams( $image, &$params ) {
175  if ( parent::normaliseParams( $image, $params ) ) {
176  $params = $this->normaliseParamsInternal( $image, $params );
177  return true;
178  }
179 
180  return false;
181  }
182 
192  protected function normaliseParamsInternal( $image, $params ) {
193  $svgMaxSize = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::SVGMaxSize );
194 
195  # Don't make an image bigger than wgMaxSVGSize on the smaller side
196  if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
197  if ( $params['physicalWidth'] > $svgMaxSize ) {
198  $srcWidth = $image->getWidth( $params['page'] );
199  $srcHeight = $image->getHeight( $params['page'] );
200  $params['physicalWidth'] = $svgMaxSize;
201  $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $svgMaxSize );
202  }
203  } elseif ( $params['physicalHeight'] > $svgMaxSize ) {
204  $srcWidth = $image->getWidth( $params['page'] );
205  $srcHeight = $image->getHeight( $params['page'] );
206  $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $svgMaxSize );
207  $params['physicalHeight'] = $svgMaxSize;
208  }
209  // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
210  // explicitly forced by user.
211  if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) {
212  unset( $params['targetlang'] );
213  }
214 
215  return $params;
216  }
217 
226  public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
227  if ( !$this->normaliseParams( $image, $params ) ) {
228  return new TransformParameterError( $params );
229  }
230  $clientWidth = $params['width'];
231  $clientHeight = $params['height'];
232  $physicalWidth = $params['physicalWidth'];
233  $physicalHeight = $params['physicalHeight'];
234  $lang = $this->getLanguageFromParams( $params );
235 
236  if ( $flags & self::TRANSFORM_LATER ) {
237  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
238  }
239 
240  $metadata = $this->validateMetadata( $image->getMetadataArray() );
241  if ( isset( $metadata['error'] ) ) {
242  $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
243 
244  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
245  }
246 
247  if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
248  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
249  wfMessage( 'thumbnail_dest_directory' ) );
250  }
251 
252  $srcPath = $image->getLocalRefPath();
253  if ( $srcPath === false ) { // Failed to get local copy
254  wfDebugLog( 'thumbnail',
255  sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
256  wfHostname(), $image->getName() ) );
257 
258  return new MediaTransformError( 'thumbnail_error',
259  $params['width'], $params['height'],
260  wfMessage( 'filemissing' )
261  );
262  }
263 
264  // Make a temp dir with a symlink to the local copy in it.
265  // This plays well with rsvg-convert policy for external entities.
266  // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
267  $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
268  $lnPath = "$tmpDir/" . basename( $srcPath );
269  $ok = mkdir( $tmpDir, 0771 );
270  if ( !$ok ) {
271  wfDebugLog( 'thumbnail',
272  sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
273  wfHostname(), $tmpDir ) );
274  return new MediaTransformError( 'thumbnail_error',
275  $params['width'], $params['height'],
276  wfMessage( 'thumbnail-temp-create' )->text()
277  );
278  }
279  $ok = symlink( $srcPath, $lnPath );
281  $cleaner = new ScopedCallback( static function () use ( $tmpDir, $lnPath ) {
282  AtEase::suppressWarnings();
283  unlink( $lnPath );
284  rmdir( $tmpDir );
285  AtEase::restoreWarnings();
286  } );
287  if ( !$ok ) {
288  // Fallback because symlink often fails on Windows
289  $ok = copy( $srcPath, $lnPath );
290  }
291  if ( !$ok ) {
292  wfDebugLog( 'thumbnail',
293  sprintf( 'Thumbnail failed on %s: could not link %s to %s',
294  wfHostname(), $lnPath, $srcPath ) );
295  return new MediaTransformError( 'thumbnail_error',
296  $params['width'], $params['height'],
297  wfMessage( 'thumbnail-temp-create' )
298  );
299  }
300 
301  $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
302  if ( $status === true ) {
303  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
304  } else {
305  return $status; // MediaTransformError
306  }
307  }
308 
320  public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
321  $mainConfig = MediaWikiServices::getInstance()->getMainConfig();
322  $svgConverters = $mainConfig->get( MainConfigNames::SVGConverters );
323  $svgConverter = $mainConfig->get( MainConfigNames::SVGConverter );
324  $svgConverterPath = $mainConfig->get( MainConfigNames::SVGConverterPath );
325  $err = false;
326  $retval = '';
327  if ( isset( $svgConverters[$svgConverter] ) ) {
328  if ( is_array( $svgConverters[$svgConverter] ) ) {
329  // This is a PHP callable
330  $func = $svgConverters[$svgConverter][0];
331  if ( !is_callable( $func ) ) {
332  throw new MWException( "$func is not callable" );
333  }
334  $err = $func( $srcPath,
335  $dstPath,
336  $width,
337  $height,
338  $lang,
339  ...array_slice( $svgConverters[$svgConverter], 1 )
340  );
341  $retval = (bool)$err;
342  } else {
343  // External command
344  $cmd = str_replace(
345  [ '$path/', '$width', '$height', '$input', '$output' ],
346  [ $svgConverterPath ? Shell::escape( "{$svgConverterPath}/" ) : "",
347  intval( $width ),
348  intval( $height ),
349  Shell::escape( $srcPath ),
350  Shell::escape( $dstPath ) ],
351  $svgConverters[$svgConverter]
352  );
353 
354  $env = [];
355  if ( $lang !== false ) {
356  $env['LANG'] = $lang;
357  }
358 
359  wfDebug( __METHOD__ . ": $cmd" );
360  $err = wfShellExecWithStderr( $cmd, $retval, $env );
361  }
362  }
363  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable False positive
364  $removed = $this->removeBadFile( $dstPath, $retval );
365  if ( $retval != 0 || $removed ) {
366  // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable cmd is set when used
367  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable cmd is set when used
368  $this->logErrorForExternalProcess( $retval, $err, $cmd );
369  return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
370  }
371 
372  return true;
373  }
374 
375  public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
376  $im = new Imagick( $srcPath );
377  $im->setBackgroundColor( 'transparent' );
378  $im->readImage( $srcPath );
379  $im->setImageFormat( 'png' );
380  $im->setImageDepth( 8 );
381 
382  if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
383  return 'Could not resize image';
384  }
385  if ( !$im->writeImage( $dstPath ) ) {
386  return "Could not write to $dstPath";
387  }
388  }
389 
390  public function getThumbType( $ext, $mime, $params = null ) {
391  return [ 'png', 'image/png' ];
392  }
393 
403  public function getLongDesc( $file ) {
404  $metadata = $this->validateMetadata( $file->getMetadataArray() );
405  if ( isset( $metadata['error'] ) ) {
406  return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
407  }
408 
409  if ( $this->isAnimatedImage( $file ) ) {
410  $msg = wfMessage( 'svg-long-desc-animated' );
411  } else {
412  $msg = wfMessage( 'svg-long-desc' );
413  }
414 
415  return $msg->numParams( $file->getWidth(), $file->getHeight() )->sizeParams( $file->getSize() )->parse();
416  }
417 
423  public function getSizeAndMetadata( $state, $filename ) {
424  $metadata = [ 'version' => self::SVG_METADATA_VERSION ];
425 
426  try {
427  $svgReader = new SVGReader( $filename );
428  $metadata += $svgReader->getMetadata();
429  } catch ( TimeoutException $e ) {
430  throw $e;
431  } catch ( Exception $e ) { // @todo SVG specific exceptions
432  // File not found, broken, etc.
433  $metadata['error'] = [
434  'message' => $e->getMessage(),
435  'code' => $e->getCode()
436  ];
437  wfDebug( __METHOD__ . ': ' . $e->getMessage() );
438  }
439 
440  return [
441  'width' => $metadata['width'] ?? 0,
442  'height' => $metadata['height'] ?? 0,
443  'metadata' => $metadata
444  ];
445  }
446 
447  protected function validateMetadata( $unser ) {
448  if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
449  return $unser;
450  } else {
451  return null;
452  }
453  }
454 
455  public function getMetadataType( $image ) {
456  return 'parsed-svg';
457  }
458 
459  public function isFileMetadataValid( $image ) {
460  $meta = $this->validateMetadata( $image->getMetadataArray() );
461  if ( !$meta ) {
462  return self::METADATA_BAD;
463  }
464  if ( !isset( $meta['originalWidth'] ) ) {
465  // Old but compatible
467  }
468 
469  return self::METADATA_GOOD;
470  }
471 
472  protected function visibleMetadataFields() {
473  $fields = [ 'objectname', 'imagedescription' ];
474 
475  return $fields;
476  }
477 
483  public function formatMetadata( $file, $context = false ) {
484  $result = [
485  'visible' => [],
486  'collapsed' => []
487  ];
488  $metadata = $this->validateMetadata( $file->getMetadataArray() );
489  if ( !$metadata || isset( $metadata['error'] ) ) {
490  return false;
491  }
492 
493  /* @todo Add a formatter
494  $format = new FormatSVG( $metadata );
495  $formatted = $format->getFormattedData();
496  */
497 
498  // Sort fields into visible and collapsed
499  $visibleFields = $this->visibleMetadataFields();
500 
501  $showMeta = false;
502  foreach ( $metadata as $name => $value ) {
503  $tag = strtolower( $name );
504  if ( isset( self::$metaConversion[$tag] ) ) {
505  $tag = strtolower( self::$metaConversion[$tag] );
506  } else {
507  // Do not output other metadata not in list
508  continue;
509  }
510  $showMeta = true;
511  self::addMeta( $result,
512  in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
513  'exif',
514  $tag,
515  $value
516  );
517  }
518 
519  return $showMeta ? $result : false;
520  }
521 
527  public function validateParam( $name, $value ) {
528  if ( in_array( $name, [ 'width', 'height' ] ) ) {
529  // Reject negative heights, widths
530  return ( $value > 0 );
531  } elseif ( $name == 'lang' ) {
532  // Validate $code
533  if ( $value === ''
534  || !MediaWikiServices::getInstance()->getLanguageNameUtils()
535  ->isValidCode( $value )
536  ) {
537  return false;
538  }
539 
540  return true;
541  }
542 
543  // Only lang, width and height are acceptable keys
544  return false;
545  }
546 
551  public function makeParamString( $params ) {
552  $lang = '';
553  $code = $this->getLanguageFromParams( $params );
554  if ( $code !== 'en' ) {
555  $lang = 'lang' . strtolower( $code ) . '-';
556  }
557  if ( !isset( $params['width'] ) ) {
558  return false;
559  }
560 
561  return "$lang{$params['width']}px";
562  }
563 
564  public function parseParamString( $str ) {
565  $m = false;
566  if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
567  return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
568  } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
569  return [ 'width' => $m[1], 'lang' => 'en' ];
570  } else {
571  return false;
572  }
573  }
574 
575  public function getParamMap() {
576  return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
577  }
578 
583  protected function getScriptParams( $params ) {
584  $scriptParams = [ 'width' => $params['width'] ];
585  if ( isset( $params['lang'] ) ) {
586  $scriptParams['lang'] = $params['lang'];
587  }
588 
589  return $scriptParams;
590  }
591 
592  public function getCommonMetaArray( File $file ) {
593  $metadata = $this->validateMetadata( $file->getMetadataArray() );
594  if ( !$metadata || isset( $metadata['error'] ) ) {
595  return [];
596  }
597  $stdMetadata = [];
598  foreach ( $metadata as $name => $value ) {
599  $tag = strtolower( $name );
600  if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
601  // Skip these. In the exif metadata stuff, it is assumed these
602  // are measured in px, which is not the case here.
603  continue;
604  }
605  if ( isset( self::$metaConversion[$tag] ) ) {
606  $tag = self::$metaConversion[$tag];
607  $stdMetadata[$tag] = $value;
608  }
609  }
610 
611  return $stdMetadata;
612  }
613 }
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:68
getMetadataArray()
Get the unserialized handler-specific metadata STUB.
Definition: File.php:747
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Definition: File.php:2191
Media handler abstract base class for images.
MediaWiki exception.
Definition: MWException.php:29
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.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Executes shell commands.
Definition: Shell.php:46
const LANG_FULL_MATCH
Definition: SVGReader.php:41
Handler for SVG images.
Definition: SvgHandler.php:36
validateParam( $name, $value)
Definition: SvgHandler.php:527
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
Definition: SvgHandler.php:66
normaliseParams( $image, &$params)
Definition: SvgHandler.php:174
formatMetadata( $file, $context=false)
Definition: SvgHandler.php:483
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
Definition: SvgHandler.php:564
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
Definition: SvgHandler.php:62
getScriptParams( $params)
Definition: SvgHandler.php:583
makeParamString( $params)
Definition: SvgHandler.php:551
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
Definition: SvgHandler.php:592
static array $metaConversion
A list of metadata tags that can be converted to the commonly used exif tags.
Definition: SvgHandler.php:43
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Definition: SvgHandler.php:226
validateMetadata( $unser)
Definition: SvgHandler.php:447
getLanguageFromParams(array $params)
Determines render language from image parameters.
Definition: SvgHandler.php:146
getAvailableLanguages(File $file)
Which languages (systemLanguage attribute) is supported.
Definition: SvgHandler.php:96
getLongDesc( $file)
Subtitle for the image.
Definition: SvgHandler.php:403
normaliseParamsInternal( $image, $params)
Code taken out of normaliseParams() for testability.
Definition: SvgHandler.php:192
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: SvgHandler.php:455
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: SvgHandler.php:390
getDefaultRenderLanguage(File $file)
What language to render file in if none selected.
Definition: SvgHandler.php:156
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:320
getSizeAndMetadata( $state, $filename)
Definition: SvgHandler.php:423
isEnabled()
False if the handler is disabled for all files.
Definition: SvgHandler.php:50
canAnimateThumbnail( $file)
We do not support making animated svg thumbnails.
Definition: SvgHandler.php:165
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
Definition: SvgHandler.php:472
static rasterizeImagickExt( $srcPath, $dstPath, $width, $height)
Definition: SvgHandler.php:375
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: SvgHandler.php:459
isAnimatedImage( $file)
Definition: SvgHandler.php:74
getMatchedLanguage( $userPreferredLanguage, array $svgLanguages)
SVG's systemLanguage matching rules state: 'The systemLanguage attribute ...
Definition: SvgHandler.php:124
const SVG_METADATA_VERSION
Definition: SvgHandler.php:37
getParamMap()
Get an associative array mapping magic word IDs to parameter names.Will be used by the parser to iden...
Definition: SvgHandler.php:575
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
if(!isset( $args[0])) $lang