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