MediaWiki  master
SvgHandler.php
Go to the documentation of this file.
1 <?php
26 use Wikimedia\ScopedCallback;
27 
33 class SvgHandler extends ImageHandler {
34  public const SVG_METADATA_VERSION = 2;
35 
40  private static $metaConversion = [
41  'originalwidth' => 'ImageWidth',
42  'originalheight' => 'ImageLength',
43  'description' => 'ImageDescription',
44  'title' => 'ObjectName',
45  ];
46 
47  public function isEnabled() {
49  if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
50  wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering." );
51 
52  return false;
53  } else {
54  return true;
55  }
56  }
57 
58  public function mustRender( $file ) {
59  return true;
60  }
61 
62  public function isVectorized( $file ) {
63  return true;
64  }
65 
70  public function isAnimatedImage( $file ) {
71  # @todo Detect animated SVGs
72  $metadata = $this->validateMetadata( $file->getMetadataArray() );
73  if ( isset( $metadata['animated'] ) ) {
74  return $metadata['animated'];
75  }
76 
77  return false;
78  }
79 
92  public function getAvailableLanguages( File $file ) {
93  $langList = [];
94  $metadata = $this->validateMetadata( $file->getMetadataArray() );
95  if ( isset( $metadata['translations'] ) ) {
96  foreach ( $metadata['translations'] as $lang => $langType ) {
97  if ( $langType === SVGReader::LANG_FULL_MATCH ) {
98  $langList[] = strtolower( $lang );
99  }
100  }
101  }
102  return array_unique( $langList );
103  }
104 
120  public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
121  foreach ( $svgLanguages as $svgLang ) {
122  if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
123  return $svgLang;
124  }
125  $trimmedSvgLang = $svgLang;
126  while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
127  $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
128  if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
129  return $svgLang;
130  }
131  }
132  }
133  return null;
134  }
135 
142  protected function getLanguageFromParams( array $params ) {
143  return $params['lang'] ?? $params['targetlang'] ?? 'en';
144  }
145 
152  public function getDefaultRenderLanguage( File $file ) {
153  return 'en';
154  }
155 
161  public function canAnimateThumbnail( $file ) {
162  return false;
163  }
164 
170  public function normaliseParams( $image, &$params ) {
171  if ( parent::normaliseParams( $image, $params ) ) {
172  $params = $this->normaliseParamsInternal( $image, $params );
173  return true;
174  }
175 
176  return false;
177  }
178 
188  protected function normaliseParamsInternal( $image, $params ) {
189  global $wgSVGMaxSize;
190 
191  # Don't make an image bigger than wgMaxSVGSize on the smaller side
192  if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
193  if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
194  $srcWidth = $image->getWidth( $params['page'] );
195  $srcHeight = $image->getHeight( $params['page'] );
196  $params['physicalWidth'] = $wgSVGMaxSize;
197  $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
198  }
199  } elseif ( $params['physicalHeight'] > $wgSVGMaxSize ) {
200  $srcWidth = $image->getWidth( $params['page'] );
201  $srcHeight = $image->getHeight( $params['page'] );
202  $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
203  $params['physicalHeight'] = $wgSVGMaxSize;
204  }
205  // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
206  // explicitly forced by user.
207  if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) {
208  unset( $params['targetlang'] );
209  }
210 
211  return $params;
212  }
213 
222  public function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
223  if ( !$this->normaliseParams( $image, $params ) ) {
224  return new TransformParameterError( $params );
225  }
226  $clientWidth = $params['width'];
227  $clientHeight = $params['height'];
228  $physicalWidth = $params['physicalWidth'];
229  $physicalHeight = $params['physicalHeight'];
230  $lang = $this->getLanguageFromParams( $params );
231 
232  if ( $flags & self::TRANSFORM_LATER ) {
233  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
234  }
235 
236  $metadata = $this->validateMetadata( $image->getMetadataArray() );
237  if ( isset( $metadata['error'] ) ) {
238  $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
239 
240  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
241  }
242 
243  if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
244  return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
245  wfMessage( 'thumbnail_dest_directory' ) );
246  }
247 
248  $srcPath = $image->getLocalRefPath();
249  if ( $srcPath === false ) { // Failed to get local copy
250  wfDebugLog( 'thumbnail',
251  sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
252  wfHostname(), $image->getName() ) );
253 
254  return new MediaTransformError( 'thumbnail_error',
255  $params['width'], $params['height'],
256  wfMessage( 'filemissing' )
257  );
258  }
259 
260  // Make a temp dir with a symlink to the local copy in it.
261  // This plays well with rsvg-convert policy for external entities.
262  // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
263  $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
264  $lnPath = "$tmpDir/" . basename( $srcPath );
265  $ok = mkdir( $tmpDir, 0771 );
266  if ( !$ok ) {
267  wfDebugLog( 'thumbnail',
268  sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
269  wfHostname(), $tmpDir ) );
270  return new MediaTransformError( 'thumbnail_error',
271  $params['width'], $params['height'],
272  wfMessage( 'thumbnail-temp-create' )->text()
273  );
274  }
275  $ok = symlink( $srcPath, $lnPath );
277  $cleaner = new ScopedCallback( static function () use ( $tmpDir, $lnPath ) {
278  Wikimedia\suppressWarnings();
279  unlink( $lnPath );
280  rmdir( $tmpDir );
281  Wikimedia\restoreWarnings();
282  } );
283  if ( !$ok ) {
284  wfDebugLog( 'thumbnail',
285  sprintf( 'Thumbnail failed on %s: could not link %s to %s',
286  wfHostname(), $lnPath, $srcPath ) );
287  return new MediaTransformError( 'thumbnail_error',
288  $params['width'], $params['height'],
289  wfMessage( 'thumbnail-temp-create' )
290  );
291  }
292 
293  $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
294  if ( $status === true ) {
295  return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
296  } else {
297  return $status; // MediaTransformError
298  }
299  }
300 
312  public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
314  $err = false;
315  $retval = '';
316  if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
317  if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
318  // This is a PHP callable
319  $func = $wgSVGConverters[$wgSVGConverter][0];
320  if ( !is_callable( $func ) ) {
321  throw new MWException( "$func is not callable" );
322  }
323  $err = $func( $srcPath,
324  $dstPath,
325  $width,
326  $height,
327  $lang,
328  ...array_slice( $wgSVGConverters[$wgSVGConverter], 1 )
329  );
330  $retval = (bool)$err;
331  } else {
332  // External command
333  $cmd = str_replace(
334  [ '$path/', '$width', '$height', '$input', '$output' ],
335  [ $wgSVGConverterPath ? Shell::escape( "$wgSVGConverterPath/" ) : "",
336  intval( $width ),
337  intval( $height ),
338  Shell::escape( $srcPath ),
339  Shell::escape( $dstPath ) ],
341  );
342 
343  $env = [];
344  if ( $lang !== false ) {
345  $env['LANG'] = $lang;
346  }
347 
348  wfDebug( __METHOD__ . ": $cmd" );
349  $err = wfShellExecWithStderr( $cmd, $retval, $env );
350  }
351  }
352  $removed = $this->removeBadFile( $dstPath, $retval );
353  if ( $retval != 0 || $removed ) {
354  $this->logErrorForExternalProcess( $retval, $err, $cmd );
355  return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
356  }
357 
358  return true;
359  }
360 
361  public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
362  $im = new Imagick( $srcPath );
363  $im->setImageFormat( 'png' );
364  $im->setBackgroundColor( 'transparent' );
365  $im->setImageDepth( 8 );
366 
367  if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
368  return 'Could not resize image';
369  }
370  if ( !$im->writeImage( $dstPath ) ) {
371  return "Could not write to $dstPath";
372  }
373  }
374 
375  public function getThumbType( $ext, $mime, $params = null ) {
376  return [ 'png', 'image/png' ];
377  }
378 
388  public function getLongDesc( $file ) {
389  $metadata = $this->validateMetadata( $file->getMetadataArray() );
390  if ( isset( $metadata['error'] ) ) {
391  return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
392  }
393 
394  if ( $this->isAnimatedImage( $file ) ) {
395  $msg = wfMessage( 'svg-long-desc-animated' );
396  } else {
397  $msg = wfMessage( 'svg-long-desc' );
398  }
399 
400  return $msg->numParams( $file->getWidth(), $file->getHeight() )->sizeParams( $file->getSize() )->parse();
401  }
402 
408  public function getSizeAndMetadata( $state, $filename ) {
409  $metadata = [ 'version' => self::SVG_METADATA_VERSION ];
410 
411  try {
412  $svgReader = new SVGReader( $filename );
413  $metadata += $svgReader->getMetadata();
414  } catch ( Exception $e ) { // @todo SVG specific exceptions
415  // File not found, broken, etc.
416  $metadata['error'] = [
417  'message' => $e->getMessage(),
418  'code' => $e->getCode()
419  ];
420  wfDebug( __METHOD__ . ': ' . $e->getMessage() );
421  }
422 
423  return [
424  'width' => $metadata['width'] ?? 0,
425  'height' => $metadata['height'] ?? 0,
426  'metadata' => $metadata
427  ];
428  }
429 
430  protected function validateMetadata( $unser ) {
431  if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
432  return $unser;
433  } else {
434  return null;
435  }
436  }
437 
438  public function getMetadataType( $image ) {
439  return 'parsed-svg';
440  }
441 
442  public function isFileMetadataValid( $image ) {
443  $meta = $this->validateMetadata( $image->getMetadataArray() );
444  if ( !$meta ) {
445  return self::METADATA_BAD;
446  }
447  if ( !isset( $meta['originalWidth'] ) ) {
448  // Old but compatible
450  }
451 
452  return self::METADATA_GOOD;
453  }
454 
455  protected function visibleMetadataFields() {
456  $fields = [ 'objectname', 'imagedescription' ];
457 
458  return $fields;
459  }
460 
466  public function formatMetadata( $file, $context = false ) {
467  $result = [
468  'visible' => [],
469  'collapsed' => []
470  ];
471  $metadata = $this->validateMetadata( $file->getMetadataArray() );
472  if ( !$metadata || isset( $metadata['error'] ) ) {
473  return false;
474  }
475 
476  /* @todo Add a formatter
477  $format = new FormatSVG( $metadata );
478  $formatted = $format->getFormattedData();
479  */
480 
481  // Sort fields into visible and collapsed
482  $visibleFields = $this->visibleMetadataFields();
483 
484  $showMeta = false;
485  foreach ( $metadata as $name => $value ) {
486  $tag = strtolower( $name );
487  if ( isset( self::$metaConversion[$tag] ) ) {
488  $tag = strtolower( self::$metaConversion[$tag] );
489  } else {
490  // Do not output other metadata not in list
491  continue;
492  }
493  $showMeta = true;
494  self::addMeta( $result,
495  in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
496  'exif',
497  $tag,
498  $value
499  );
500  }
501 
502  return $showMeta ? $result : false;
503  }
504 
510  public function validateParam( $name, $value ) {
511  if ( in_array( $name, [ 'width', 'height' ] ) ) {
512  // Reject negative heights, widths
513  return ( $value > 0 );
514  } elseif ( $name == 'lang' ) {
515  // Validate $code
516  if ( $value === ''
517  || !MediaWikiServices::getInstance()->getLanguageNameUtils()
518  ->isValidCode( $value )
519  ) {
520  return false;
521  }
522 
523  return true;
524  }
525 
526  // Only lang, width and height are acceptable keys
527  return false;
528  }
529 
534  public function makeParamString( $params ) {
535  $lang = '';
536  $code = $this->getLanguageFromParams( $params );
537  if ( $code !== 'en' ) {
538  $lang = 'lang' . strtolower( $code ) . '-';
539  }
540  if ( !isset( $params['width'] ) ) {
541  return false;
542  }
543 
544  return "$lang{$params['width']}px";
545  }
546 
547  public function parseParamString( $str ) {
548  $m = false;
549  if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
550  return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
551  } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
552  return [ 'width' => $m[1], 'lang' => 'en' ];
553  } else {
554  return false;
555  }
556  }
557 
558  public function getParamMap() {
559  return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
560  }
561 
566  protected function getScriptParams( $params ) {
567  $scriptParams = [ 'width' => $params['width'] ];
568  if ( isset( $params['lang'] ) ) {
569  $scriptParams['lang'] = $params['lang'];
570  }
571 
572  return $scriptParams;
573  }
574 
575  public function getCommonMetaArray( File $file ) {
576  $metadata = $this->validateMetadata( $file->getMetadataArray() );
577  if ( !$metadata || isset( $metadata['error'] ) ) {
578  return [];
579  }
580  $stdMetadata = [];
581  foreach ( $metadata as $name => $value ) {
582  $tag = strtolower( $name );
583  if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
584  // Skip these. In the exif metadata stuff, it is assumed these
585  // are measured in px, which is not the case here.
586  continue;
587  }
588  if ( isset( self::$metaConversion[$tag] ) ) {
589  $tag = self::$metaConversion[$tag];
590  $stdMetadata[$tag] = $value;
591  }
592  }
593 
594  return $stdMetadata;
595  }
596 }
MediaHandler\removeBadFile
removeBadFile( $dstPath, $retval=0)
Check for zero-sized thumbnails.
Definition: MediaHandler.php:924
SVGReader
Definition: SVGReader.php:31
SvgHandler\validateParam
validateParam( $name, $value)
Definition: SvgHandler.php:510
SvgHandler\rasterizeImagickExt
static rasterizeImagickExt( $srcPath, $dstPath, $width, $height)
Definition: SvgHandler.php:361
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:45
MediaTransformError
Basic media transform error class.
Definition: MediaTransformError.php:31
ThumbnailImage
Media transform output for images.
Definition: ThumbnailImage.php:29
SvgHandler\$metaConversion
static array $metaConversion
A list of metadata tags that can be converted to the commonly used exif tags.
Definition: SvgHandler.php:40
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:1747
SvgHandler\parseParamString
parseParamString( $str)
Parse a param string made with makeParamString back into an array.The parameter string without file n...
Definition: SvgHandler.php:547
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:202
$lang
if(!isset( $args[0])) $lang
Definition: testCompression.php:37
SvgHandler\formatMetadata
formatMetadata( $file, $context=false)
Definition: SvgHandler.php:466
SvgHandler\getMetadataType
getMetadataType( $image)
Get a string describing the type of metadata, for display purposes.
Definition: SvgHandler.php:438
SvgHandler\getMatchedLanguage
getMatchedLanguage( $userPreferredLanguage, array $svgLanguages)
SVG's systemLanguage matching rules state: 'The systemLanguage attribute ...
Definition: SvgHandler.php:120
$wgSVGMaxSize
$wgSVGMaxSize
Don't scale a SVG larger than this.
Definition: DefaultSettings.php:1383
SvgHandler\isAnimatedImage
isAnimatedImage( $file)
Definition: SvgHandler.php:70
SvgHandler\mustRender
mustRender( $file)
True if handled types cannot be displayed directly in a browser but can be rendered.
Definition: SvgHandler.php:58
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1246
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1183
SvgHandler\getThumbType
getThumbType( $ext, $mime, $params=null)
Get the thumbnail extension and MIME type for a given source MIME type.
Definition: SvgHandler.php:375
File\getMetadataArray
getMetadataArray()
Get the unserialized handler-specific metadata STUB.
Definition: File.php:744
SvgHandler\getScriptParams
getScriptParams( $params)
Definition: SvgHandler.php:566
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:958
SvgHandler\getLanguageFromParams
getLanguageFromParams(array $params)
Determines render language from image parameters.
Definition: SvgHandler.php:142
SvgHandler\validateMetadata
validateMetadata( $unser)
Definition: SvgHandler.php:430
SvgHandler\normaliseParamsInternal
normaliseParamsInternal( $image, $params)
Code taken out of normaliseParams() for testability.
Definition: SvgHandler.php:188
SvgHandler\rasterize
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:312
SvgHandler\getLongDesc
getLongDesc( $file)
Subtitle for the image.
Definition: SvgHandler.php:388
MediaHandler\METADATA_COMPATIBLE
const METADATA_COMPATIBLE
Definition: MediaHandler.php:41
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:67
$wgSVGConverterPath
$wgSVGConverterPath
If not in the executable PATH, specify the SVG converter path.
Definition: DefaultSettings.php:1378
MWException
MediaWiki exception.
Definition: MWException.php:29
SvgHandler\normaliseParams
normaliseParams( $image, &$params)
Definition: SvgHandler.php:170
SvgHandler\isEnabled
isEnabled()
False if the handler is disabled for all files.
Definition: SvgHandler.php:47
ImageHandler
Media handler abstract base class for images.
Definition: ImageHandler.php:31
MediaHandler\addMeta
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...
Definition: MediaHandler.php:786
SvgHandler
Handler for SVG images.
Definition: SvgHandler.php:33
SvgHandler\isFileMetadataValid
isFileMetadataValid( $image)
Check if the metadata is valid for this handler.
Definition: SvgHandler.php:442
SVGReader\LANG_FULL_MATCH
const LANG_FULL_MATCH
Definition: SVGReader.php:36
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
SvgHandler\doTransform
doTransform( $image, $dstPath, $dstUrl, $params, $flags=0)
Definition: SvgHandler.php:222
TransformParameterError
Shortcut class for parameter validation errors.
Definition: TransformParameterError.php:30
SvgHandler\canAnimateThumbnail
canAnimateThumbnail( $file)
We do not support making animated svg thumbnails.
Definition: SvgHandler.php:161
SvgHandler\getAvailableLanguages
getAvailableLanguages(File $file)
Which languages (systemLanguage attribute) is supported.
Definition: SvgHandler.php:92
File\scaleHeight
static scaleHeight( $srcWidth, $srcHeight, $dstWidth)
Calculate the height of a thumbnail using the source and destination width.
Definition: File.php:2158
SvgHandler\getCommonMetaArray
getCommonMetaArray(File $file)
Get an array of standard (FormatMetadata type) metadata values.
Definition: SvgHandler.php:575
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:1728
SvgHandler\getDefaultRenderLanguage
getDefaultRenderLanguage(File $file)
What language to render file in if none selected.
Definition: SvgHandler.php:152
MediaHandler\logErrorForExternalProcess
logErrorForExternalProcess( $retval, $err, $cmd)
Log an error that occurred in an external process.
Definition: MediaHandler.php:1007
SvgHandler\visibleMetadataFields
visibleMetadataFields()
Get a list of metadata items which should be displayed when the metadata table is collapsed.
Definition: SvgHandler.php:455
MediaHandler\METADATA_BAD
const METADATA_BAD
Definition: MediaHandler.php:40
$wgSVGConverters
$wgSVGConverters
Scalable Vector Graphics (SVG) may be uploaded as images.
Definition: DefaultSettings.php:1358
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
SvgHandler\SVG_METADATA_VERSION
const SVG_METADATA_VERSION
Definition: SvgHandler.php:34
$mime
$mime
Definition: router.php:60
SvgHandler\makeParamString
makeParamString( $params)
Definition: SvgHandler.php:534
SvgHandler\getParamMap
getParamMap()
Get an associative array mapping magic word IDs to parameter names.Will be used by the parser to iden...
Definition: SvgHandler.php:558
$wgSVGConverter
$wgSVGConverter
Pick a converter defined in $wgSVGConverters.
Definition: DefaultSettings.php:1373
SvgHandler\isVectorized
isVectorized( $file)
The material is vectorized and thus scaling is lossless.
Definition: SvgHandler.php:62
MediaHandler\METADATA_GOOD
const METADATA_GOOD
Definition: MediaHandler.php:39
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:1963
SvgHandler\getSizeAndMetadata
getSizeAndMetadata( $state, $filename)
Definition: SvgHandler.php:408
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:257