MediaWiki  master
SVGReader.php
Go to the documentation of this file.
1 <?php
2 
31 use Wikimedia\AtEase\AtEase;
32 
36 class SVGReader {
37  private const DEFAULT_WIDTH = 512;
38  private const DEFAULT_HEIGHT = 512;
39  private const NS_SVG = 'http://www.w3.org/2000/svg';
40  public const LANG_PREFIX_MATCH = 1;
41  public const LANG_FULL_MATCH = 2;
42 
44  private $reader;
45 
47  private $mDebug = false;
48 
50  private $metadata = [];
51  private $languages = [];
52  private $languagePrefixes = [];
53 
59  public function __construct( $source ) {
60  $svgMetadataCutoff = MediaWikiServices::getInstance()->getMainConfig()
61  ->get( MainConfigNames::SVGMetadataCutoff );
62  $this->reader = new XMLReader();
63 
64  // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
65  $size = filesize( $source );
66  if ( $size === false ) {
67  throw new MWException( "Error getting filesize of SVG." );
68  }
69 
70  if ( $size > $svgMetadataCutoff ) {
71  $this->debug( "SVG is $size bytes, which is bigger than {$svgMetadataCutoff}. Truncating." );
72  $contents = file_get_contents( $source, false, null, 0, $svgMetadataCutoff );
73  if ( $contents === false ) {
74  throw new MWException( 'Error reading SVG file.' );
75  }
76  $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
77  } else {
78  $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
79  }
80 
81  // Expand entities, since Adobe Illustrator uses them for xmlns
82  // attributes (T33719). Note that libxml2 has some protection
83  // against large recursive entity expansions so this is not as
84  // insecure as it might appear to be. However, it is still extremely
85  // insecure. It's necessary to wrap any read() calls with
86  // libxml_disable_entity_loader() to avoid arbitrary local file
87  // inclusion, or even arbitrary code execution if the expect
88  // extension is installed (T48859).
89  // phpcs:ignore Generic.PHP.NoSilencedErrors -- suppress deprecation per T268847
90  $oldDisable = @libxml_disable_entity_loader( true );
91  $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
92 
93  $this->metadata['width'] = self::DEFAULT_WIDTH;
94  $this->metadata['height'] = self::DEFAULT_HEIGHT;
95 
96  // The size in the units specified by the SVG file
97  // (for the metadata box)
98  // Per the SVG spec, if unspecified, default to '100%'
99  $this->metadata['originalWidth'] = '100%';
100  $this->metadata['originalHeight'] = '100%';
101 
102  // Because we cut off the end of the svg making an invalid one. Complicated
103  // try catch thing to make sure warnings get restored. Seems like there should
104  // be a better way.
105  AtEase::suppressWarnings();
106  try {
107  $this->read();
108  } catch ( Exception $e ) {
109  // Note, if this happens, the width/height will be taken to be 0x0.
110  // Should we consider it the default 512x512 instead?
111  throw $e;
112  } finally {
113  libxml_disable_entity_loader( $oldDisable );
114  AtEase::restoreWarnings();
115  }
116  }
117 
121  public function getMetadata() {
122  return $this->metadata;
123  }
124 
130  protected function read() {
131  $keepReading = $this->reader->read();
132 
133  /* Skip until first element */
134  while ( $keepReading && $this->reader->nodeType != XMLReader::ELEMENT ) {
135  $keepReading = $this->reader->read();
136  }
137 
138  if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
139  throw new MWException( "Expected <svg> tag, got " .
140  $this->reader->localName . " in NS " . $this->reader->namespaceURI );
141  }
142  $this->debug( "<svg> tag is correct." );
143  $this->handleSVGAttribs();
144 
145  $exitDepth = $this->reader->depth;
146  $keepReading = $this->reader->read();
147  while ( $keepReading ) {
148  $tag = $this->reader->localName;
149  $type = $this->reader->nodeType;
150  $isSVG = ( $this->reader->namespaceURI == self::NS_SVG );
151 
152  $this->debug( "$tag" );
153 
154  if ( $isSVG && $tag == 'svg' && $type == XMLReader::END_ELEMENT
155  && $this->reader->depth <= $exitDepth
156  ) {
157  break;
158  } elseif ( $isSVG && $tag == 'title' ) {
159  $this->readField( $tag, 'title' );
160  } elseif ( $isSVG && $tag == 'desc' ) {
161  $this->readField( $tag, 'description' );
162  } elseif ( $isSVG && $tag == 'metadata' && $type == XMLReader::ELEMENT ) {
163  $this->readXml( 'metadata' );
164  } elseif ( $isSVG && $tag == 'script' ) {
165  // We normally do not allow scripted svgs.
166  // However its possible to configure MW to let them
167  // in, and such files should be considered animated.
168  $this->metadata['animated'] = true;
169  } elseif ( $tag !== '#text' ) {
170  $this->debug( "Unhandled top-level XML tag $tag" );
171 
172  // Recurse into children of current tag, looking for animation and languages.
173  $this->animateFilterAndLang( $tag );
174  }
175 
176  // Goto next element, which is sibling of current (Skip children).
177  $keepReading = $this->reader->next();
178  }
179 
180  $this->reader->close();
181 
182  $this->metadata['translations'] = $this->languages + $this->languagePrefixes;
183 
184  return true;
185  }
186 
193  private function readField( $name, $metafield = null ) {
194  $this->debug( "Read field $metafield" );
195  if ( !$metafield || $this->reader->nodeType != XMLReader::ELEMENT ) {
196  return;
197  }
198  $keepReading = $this->reader->read();
199  while ( $keepReading ) {
200  if ( $this->reader->localName == $name
201  && $this->reader->namespaceURI == self::NS_SVG
202  && $this->reader->nodeType == XMLReader::END_ELEMENT
203  ) {
204  break;
205  } elseif ( $this->reader->nodeType == XMLReader::TEXT ) {
206  $this->metadata[$metafield] = trim( $this->reader->value );
207  }
208  $keepReading = $this->reader->read();
209  }
210  }
211 
218  private function readXml( $metafield = null ) {
219  $this->debug( "Read top level metadata" );
220  if ( !$metafield || $this->reader->nodeType != XMLReader::ELEMENT ) {
221  return;
222  }
223  // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
224  $this->metadata[$metafield] = trim( $this->reader->readInnerXml() );
225 
226  $this->reader->next();
227  }
228 
235  private function animateFilterAndLang( $name ) {
236  $this->debug( "animate filter for tag $name" );
237  if ( $this->reader->nodeType != XMLReader::ELEMENT ) {
238  return;
239  }
240  if ( $this->reader->isEmptyElement ) {
241  return;
242  }
243  $exitDepth = $this->reader->depth;
244  $keepReading = $this->reader->read();
245  while ( $keepReading ) {
246  if ( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
247  && $this->reader->nodeType == XMLReader::END_ELEMENT
248  ) {
249  break;
250  } elseif ( $this->reader->namespaceURI == self::NS_SVG
251  && $this->reader->nodeType == XMLReader::ELEMENT
252  ) {
253  $sysLang = $this->reader->getAttribute( 'systemLanguage' );
254  if ( $sysLang !== null && $sysLang !== '' ) {
255  // See https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
256  $langList = explode( ',', $sysLang );
257  foreach ( $langList as $langItem ) {
258  $langItem = trim( $langItem );
259  if ( Language::isWellFormedLanguageTag( $langItem ) ) {
260  $this->languages[$langItem] = self::LANG_FULL_MATCH;
261  }
262  // Note, the standard says that any prefix should work,
263  // here we do only the initial prefix, since that will catch
264  // 99% of cases, and we are going to compare against fallbacks.
265  // This differs mildly from how the spec says languages should be
266  // handled, however it matches better how the MediaWiki language
267  // preference is generally handled.
268  $dash = strpos( $langItem, '-' );
269  // Intentionally checking both !false and > 0 at the same time.
270  if ( $dash ) {
271  $itemPrefix = substr( $langItem, 0, $dash );
272  if ( Language::isWellFormedLanguageTag( $itemPrefix ) ) {
273  $this->languagePrefixes[$itemPrefix] = self::LANG_PREFIX_MATCH;
274  }
275  }
276  }
277  }
278  switch ( $this->reader->localName ) {
279  case 'script':
280  // Normally we disallow files with
281  // <script>, but its possible
282  // to configure MW to disable
283  // such checks.
284  case 'animate':
285  case 'set':
286  case 'animateMotion':
287  case 'animateColor':
288  case 'animateTransform':
289  $this->debug( "HOUSTON WE HAVE ANIMATION" );
290  $this->metadata['animated'] = true;
291  break;
292  }
293  }
294  $keepReading = $this->reader->read();
295  }
296  }
297 
298  private function debug( $data ) {
299  if ( $this->mDebug ) {
300  wfDebug( "SVGReader: $data" );
301  }
302  }
303 
309  private function handleSVGAttribs() {
310  $defaultWidth = self::DEFAULT_WIDTH;
311  $defaultHeight = self::DEFAULT_HEIGHT;
312  $aspect = 1.0;
313  $width = null;
314  $height = null;
315 
316  if ( $this->reader->getAttribute( 'viewBox' ) ) {
317  // min-x min-y width height
318  $viewBox = preg_split( '/\s*[\s,]\s*/', trim( $this->reader->getAttribute( 'viewBox' ) ?? '' ) );
319  if ( count( $viewBox ) == 4 ) {
320  $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
321  $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
322  if ( $viewWidth > 0 && $viewHeight > 0 ) {
323  $aspect = $viewWidth / $viewHeight;
324  $defaultHeight = $defaultWidth / $aspect;
325  }
326  }
327  }
328  if ( $this->reader->getAttribute( 'width' ) ) {
329  $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ) ?? '', $defaultWidth );
330  $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
331  }
332  if ( $this->reader->getAttribute( 'height' ) ) {
333  $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ) ?? '', $defaultHeight );
334  $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
335  }
336 
337  if ( !isset( $width ) && !isset( $height ) ) {
338  $width = $defaultWidth;
339  $height = $width / $aspect;
340  } elseif ( isset( $width ) && !isset( $height ) ) {
341  $height = $width / $aspect;
342  } elseif ( isset( $height ) && !isset( $width ) ) {
343  $width = $height * $aspect;
344  }
345 
346  if ( $width > 0 && $height > 0 ) {
347  $this->metadata['width'] = intval( round( $width ) );
348  $this->metadata['height'] = intval( round( $height ) );
349  }
350  }
351 
360  public static function scaleSVGUnit( $length, $viewportSize = 512 ) {
361  static $unitLength = [
362  'px' => 1.0,
363  'pt' => 1.25,
364  'pc' => 15.0,
365  'mm' => 3.543307,
366  'cm' => 35.43307,
367  'in' => 90.0,
368  'em' => 16.0, // fake it?
369  'ex' => 12.0, // fake it?
370  '' => 1.0, // "User units" pixels by default
371  ];
372  $matches = [];
373  if ( preg_match(
374  '/^\s*([-+]?\d*(?:\.\d+|\d+)(?:[Ee][-+]?\d+)?)\s*(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/',
375  $length,
376  $matches
377  ) ) {
378  $length = floatval( $matches[1] );
379  $unit = $matches[2];
380  if ( $unit == '%' ) {
381  return $length * 0.01 * $viewportSize;
382  } else {
383  return $length * $unitLength[$unit];
384  }
385  } else {
386  // Assume pixels
387  return floatval( $length );
388  }
389  }
390 }
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$matches
static isWellFormedLanguageTag( $code, $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
Definition: Language.php:317
MediaWiki exception.
Definition: MWException.php:29
A class containing constants representing the names of configuration variables.
MediaWikiServices is the service locator for the application scope of MediaWiki.
bool $mDebug
Definition: SVGReader.php:47
debug( $data)
Definition: SVGReader.php:298
const LANG_PREFIX_MATCH
Definition: SVGReader.php:40
const DEFAULT_WIDTH
Definition: SVGReader.php:37
static scaleSVGUnit( $length, $viewportSize=512)
Return a rounded pixel equivalent for a labeled CSS/SVG length.
Definition: SVGReader.php:360
handleSVGAttribs()
Parse the attributes of an SVG element.
Definition: SVGReader.php:309
read()
Read the SVG.
Definition: SVGReader.php:130
XMLReader $reader
Definition: SVGReader.php:44
const LANG_FULL_MATCH
Definition: SVGReader.php:41
$languagePrefixes
Definition: SVGReader.php:52
readXml( $metafield=null)
Read an XML snippet from an element.
Definition: SVGReader.php:218
animateFilterAndLang( $name)
Filter all children, looking for animated elements.
Definition: SVGReader.php:235
const NS_SVG
Definition: SVGReader.php:39
readField( $name, $metafield=null)
Read a textelement from an element.
Definition: SVGReader.php:193
array $metadata
Definition: SVGReader.php:50
__construct( $source)
Creates an SVGReader drawing from the source provided.
Definition: SVGReader.php:59
const DEFAULT_HEIGHT
Definition: SVGReader.php:38
$source