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