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  $status = $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
77  } else {
78  $status = $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
79  }
80  if ( !$status ) {
81  throw new MWException( "Error getting xml of SVG." );
82  }
83 
84  // Expand entities, since Adobe Illustrator uses them for xmlns
85  // attributes (T33719). Note that libxml2 has some protection
86  // against large recursive entity expansions so this is not as
87  // insecure as it might appear to be. However, it is still extremely
88  // insecure. It's necessary to wrap any read() calls with
89  // libxml_disable_entity_loader() to avoid arbitrary local file
90  // inclusion, or even arbitrary code execution if the expect
91  // extension is installed (T48859).
92  // phpcs:ignore Generic.PHP.NoSilencedErrors -- suppress deprecation per T268847
93  $oldDisable = @libxml_disable_entity_loader( true );
94  $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
95 
96  $this->metadata['width'] = self::DEFAULT_WIDTH;
97  $this->metadata['height'] = self::DEFAULT_HEIGHT;
98 
99  // The size in the units specified by the SVG file
100  // (for the metadata box)
101  // Per the SVG spec, if unspecified, default to '100%'
102  $this->metadata['originalWidth'] = '100%';
103  $this->metadata['originalHeight'] = '100%';
104 
105  // Because we cut off the end of the svg making an invalid one. Complicated
106  // try catch thing to make sure warnings get restored. Seems like there should
107  // be a better way.
108  AtEase::suppressWarnings();
109  try {
110  $this->read();
111  } catch ( Exception $e ) {
112  // Note, if this happens, the width/height will be taken to be 0x0.
113  // Should we consider it the default 512x512 instead?
114  throw $e;
115  } finally {
116  libxml_disable_entity_loader( $oldDisable );
117  AtEase::restoreWarnings();
118  }
119  }
120 
124  public function getMetadata() {
125  return $this->metadata;
126  }
127 
133  protected function read() {
134  $keepReading = $this->reader->read();
135 
136  /* Skip until first element */
137  while ( $keepReading && $this->reader->nodeType !== XMLReader::ELEMENT ) {
138  $keepReading = $this->reader->read();
139  }
140 
141  if ( $this->reader->localName !== 'svg' || $this->reader->namespaceURI !== self::NS_SVG ) {
142  throw new MWException( "Expected <svg> tag, got " .
143  $this->reader->localName . " in NS " . $this->reader->namespaceURI );
144  }
145  $this->debug( '<svg> tag is correct.' );
146  $this->handleSVGAttribs();
147 
148  $exitDepth = $this->reader->depth;
149  $keepReading = $this->reader->read();
150  while ( $keepReading ) {
151  $tag = $this->reader->localName;
152  $type = $this->reader->nodeType;
153  $isSVG = ( $this->reader->namespaceURI === self::NS_SVG );
154 
155  $this->debug( "$tag" );
156 
157  if ( $isSVG && $tag === 'svg' && $type === XMLReader::END_ELEMENT
158  && $this->reader->depth <= $exitDepth
159  ) {
160  break;
161  }
162 
163  if ( $isSVG && $tag === 'title' ) {
164  $this->readField( $tag, 'title' );
165  } elseif ( $isSVG && $tag === 'desc' ) {
166  $this->readField( $tag, 'description' );
167  } elseif ( $isSVG && $tag === 'metadata' && $type === XMLReader::ELEMENT ) {
168  $this->readXml( 'metadata' );
169  } elseif ( $isSVG && $tag === 'script' ) {
170  // We normally do not allow scripted svgs.
171  // However its possible to configure MW to let them
172  // in, and such files should be considered animated.
173  $this->metadata['animated'] = true;
174  } elseif ( $tag !== '#text' ) {
175  $this->debug( "Unhandled top-level XML tag $tag" );
176 
177  // Recurse into children of current tag, looking for animation and languages.
178  $this->animateFilterAndLang( $tag );
179  }
180 
181  // Goto next element, which is sibling of current (Skip children).
182  $keepReading = $this->reader->next();
183  }
184 
185  $this->reader->close();
186 
187  $this->metadata['translations'] = $this->languages + $this->languagePrefixes;
188 
189  return true;
190  }
191 
198  private function readField( $name, $metafield = null ) {
199  $this->debug( "Read field $metafield" );
200  if ( !$metafield || $this->reader->nodeType !== XMLReader::ELEMENT ) {
201  return;
202  }
203  $keepReading = $this->reader->read();
204  while ( $keepReading ) {
205  if ( $this->reader->localName === $name
206  && $this->reader->namespaceURI === self::NS_SVG
207  && $this->reader->nodeType === XMLReader::END_ELEMENT
208  ) {
209  break;
210  }
211 
212  if ( $this->reader->nodeType === XMLReader::TEXT ) {
213  $this->metadata[$metafield] = trim( $this->reader->value );
214  }
215  $keepReading = $this->reader->read();
216  }
217  }
218 
225  private function readXml( $metafield = null ) {
226  $this->debug( "Read top level metadata" );
227  if ( !$metafield || $this->reader->nodeType !== XMLReader::ELEMENT ) {
228  return;
229  }
230  // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
231  $this->metadata[$metafield] = trim( $this->reader->readInnerXml() );
232 
233  $this->reader->next();
234  }
235 
242  private function animateFilterAndLang( $name ) {
243  $this->debug( "animate filter for tag $name" );
244  if ( $this->reader->nodeType !== XMLReader::ELEMENT ) {
245  return;
246  }
247  if ( $this->reader->isEmptyElement ) {
248  return;
249  }
250  $exitDepth = $this->reader->depth;
251  $keepReading = $this->reader->read();
252  while ( $keepReading ) {
253  if ( $this->reader->localName === $name && $this->reader->depth <= $exitDepth
254  && $this->reader->nodeType === XMLReader::END_ELEMENT
255  ) {
256  break;
257  }
258 
259  if ( $this->reader->namespaceURI === self::NS_SVG
260  && $this->reader->nodeType === XMLReader::ELEMENT
261  ) {
262  $sysLang = $this->reader->getAttribute( 'systemLanguage' );
263  if ( $sysLang !== null && $sysLang !== '' ) {
264  // See https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
265  $langList = explode( ',', $sysLang );
266  foreach ( $langList as $langItem ) {
267  $langItem = trim( $langItem );
268  if ( LanguageCode::isWellFormedLanguageTag( $langItem ) ) {
269  $this->languages[$langItem] = self::LANG_FULL_MATCH;
270  }
271  // Note, the standard says that any prefix should work,
272  // here we do only the initial prefix, since that will catch
273  // 99% of cases, and we are going to compare against fallbacks.
274  // This differs mildly from how the spec says languages should be
275  // handled, however it matches better how the MediaWiki language
276  // preference is generally handled.
277  $dash = strpos( $langItem, '-' );
278  // Intentionally checking both !false and > 0 at the same time.
279  if ( $dash ) {
280  $itemPrefix = substr( $langItem, 0, $dash );
281  if ( LanguageCode::isWellFormedLanguageTag( $itemPrefix ) ) {
282  $this->languagePrefixes[$itemPrefix] = self::LANG_PREFIX_MATCH;
283  }
284  }
285  }
286  }
287  switch ( $this->reader->localName ) {
288  case 'script':
289  // Normally we disallow files with
290  // <script>, but its possible
291  // to configure MW to disable
292  // such checks.
293  case 'animate':
294  case 'set':
295  case 'animateMotion':
296  case 'animateColor':
297  case 'animateTransform':
298  $this->debug( "HOUSTON WE HAVE ANIMATION" );
299  $this->metadata['animated'] = true;
300  break;
301  }
302  }
303  $keepReading = $this->reader->read();
304  }
305  }
306 
307  private function debug( $data ) {
308  if ( $this->mDebug ) {
309  wfDebug( "SVGReader: $data" );
310  }
311  }
312 
318  private function handleSVGAttribs() {
319  $defaultWidth = self::DEFAULT_WIDTH;
320  $defaultHeight = self::DEFAULT_HEIGHT;
321  $aspect = 1.0;
322  $width = null;
323  $height = null;
324 
325  if ( $this->reader->getAttribute( 'viewBox' ) ) {
326  // min-x min-y width height
327  $viewBox = preg_split( '/\s*[\s,]\s*/', trim( $this->reader->getAttribute( 'viewBox' ) ?? '' ) );
328  if ( count( $viewBox ) === 4 ) {
329  $viewWidth = self::scaleSVGUnit( $viewBox[2] );
330  $viewHeight = self::scaleSVGUnit( $viewBox[3] );
331  if ( $viewWidth > 0 && $viewHeight > 0 ) {
332  $aspect = $viewWidth / $viewHeight;
333  $defaultHeight = $defaultWidth / $aspect;
334  }
335  }
336  }
337  if ( $this->reader->getAttribute( 'width' ) ) {
338  $width = self::scaleSVGUnit( $this->reader->getAttribute( 'width' ) ?? '', $defaultWidth );
339  $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
340  }
341  if ( $this->reader->getAttribute( 'height' ) ) {
342  $height = self::scaleSVGUnit( $this->reader->getAttribute( 'height' ) ?? '', $defaultHeight );
343  $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
344  }
345 
346  if ( !isset( $width ) && !isset( $height ) ) {
347  $width = $defaultWidth;
348  $height = $width / $aspect;
349  } elseif ( isset( $width ) && !isset( $height ) ) {
350  $height = $width / $aspect;
351  } elseif ( isset( $height ) && !isset( $width ) ) {
352  $width = $height * $aspect;
353  }
354 
355  if ( $width > 0 && $height > 0 ) {
356  $this->metadata['width'] = (int)round( $width );
357  $this->metadata['height'] = (int)round( $height );
358  }
359  }
360 
369  public static function scaleSVGUnit( $length, $viewportSize = 512 ) {
370  static $unitLength = [
371  'px' => 1.0,
372  'pt' => 1.25,
373  'pc' => 15.0,
374  'mm' => 3.543307,
375  'cm' => 35.43307,
376  'in' => 90.0,
377  'em' => 16.0, // fake it?
378  'ex' => 12.0, // fake it?
379  '' => 1.0, // "User units" pixels by default
380  ];
381  $matches = [];
382  if ( preg_match(
383  '/^\s*([-+]?\d*(?:\.\d+|\d+)(?:[Ee][-+]?\d+)?)\s*(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/',
384  $length,
385  $matches
386  ) ) {
387  $length = (float)$matches[1];
388  $unit = $matches[2];
389  if ( $unit === '%' ) {
390  return $length * 0.01 * $viewportSize;
391  }
392 
393  return $length * $unitLength[$unit];
394  }
395 
396  // Assume pixels
397  return (float)$length;
398  }
399 }
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(string $code, bool $lenient=false)
Returns true if a language code string is a well-formed language tag according to RFC 5646.
MediaWiki exception.
Definition: MWException.php:32
A class containing constants representing the names of configuration variables.
Service locator for MediaWiki core services.
const LANG_PREFIX_MATCH
Definition: SVGReader.php:40
static scaleSVGUnit( $length, $viewportSize=512)
Return a rounded pixel equivalent for a labeled CSS/SVG length.
Definition: SVGReader.php:369
read()
Read the SVG.
Definition: SVGReader.php:133
const LANG_FULL_MATCH
Definition: SVGReader.php:41
__construct( $source)
Creates an SVGReader drawing from the source provided.
Definition: SVGReader.php:59
$source