MediaWiki REL1_41
SVGReader.php
Go to the documentation of this file.
1<?php
2
31use Wikimedia\AtEase\AtEase;
32
36class 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 InvalidSVGException( "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 InvalidSVGException( '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 InvalidSVGException( "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 // Note: if this throws, the width/height will be taken to be 0x0.
111 // Should we consider it the default 512x512 instead?
112 $this->read();
113 } finally {
114 libxml_disable_entity_loader( $oldDisable );
115 AtEase::restoreWarnings();
116 }
117 }
118
122 public function getMetadata() {
123 return $this->metadata;
124 }
125
131 protected function read() {
132 $keepReading = $this->reader->read();
133
134 /* Skip until first element */
135 while ( $keepReading && $this->reader->nodeType !== XMLReader::ELEMENT ) {
136 $keepReading = $this->reader->read();
137 }
138
139 if ( $this->reader->localName !== 'svg' || $this->reader->namespaceURI !== self::NS_SVG ) {
140 throw new InvalidSVGException( "Expected <svg> tag, got " .
141 $this->reader->localName . " in NS " . $this->reader->namespaceURI );
142 }
143 $this->debug( '<svg> tag is correct.' );
144 $this->handleSVGAttribs();
145
146 $exitDepth = $this->reader->depth;
147 $keepReading = $this->reader->read();
148 while ( $keepReading ) {
149 $tag = $this->reader->localName;
150 $type = $this->reader->nodeType;
151 $isSVG = ( $this->reader->namespaceURI === self::NS_SVG );
152
153 $this->debug( "$tag" );
154
155 if ( $isSVG && $tag === 'svg' && $type === XMLReader::END_ELEMENT
156 && $this->reader->depth <= $exitDepth
157 ) {
158 break;
159 }
160
161 if ( $isSVG && $tag === 'title' ) {
162 $this->readField( $tag, 'title' );
163 } elseif ( $isSVG && $tag === 'desc' ) {
164 $this->readField( $tag, 'description' );
165 } elseif ( $isSVG && $tag === 'metadata' && $type === XMLReader::ELEMENT ) {
166 $this->readXml( 'metadata' );
167 } elseif ( $isSVG && $tag === 'script' ) {
168 // We normally do not allow scripted svgs.
169 // However its possible to configure MW to let them
170 // in, and such files should be considered animated.
171 $this->metadata['animated'] = true;
172 } elseif ( $tag !== '#text' ) {
173 $this->debug( "Unhandled top-level XML tag $tag" );
174
175 // Recurse into children of current tag, looking for animation and languages.
176 $this->animateFilterAndLang( $tag );
177 }
178
179 // Goto next element, which is sibling of current (Skip children).
180 $keepReading = $this->reader->next();
181 }
182
183 $this->reader->close();
184
185 $this->metadata['translations'] = $this->languages + $this->languagePrefixes;
186
187 return true;
188 }
189
196 private function readField( $name, $metafield = null ) {
197 $this->debug( "Read field $metafield" );
198 if ( !$metafield || $this->reader->nodeType !== XMLReader::ELEMENT ) {
199 return;
200 }
201 $keepReading = $this->reader->read();
202 while ( $keepReading ) {
203 if ( $this->reader->localName === $name
204 && $this->reader->namespaceURI === self::NS_SVG
205 && $this->reader->nodeType === XMLReader::END_ELEMENT
206 ) {
207 break;
208 }
209
210 if ( $this->reader->nodeType === XMLReader::TEXT ) {
211 $this->metadata[$metafield] = trim( $this->reader->value );
212 }
213 $keepReading = $this->reader->read();
214 }
215 }
216
222 private function readXml( $metafield = null ) {
223 $this->debug( "Read top level metadata" );
224 if ( !$metafield || $this->reader->nodeType !== XMLReader::ELEMENT ) {
225 return;
226 }
227 // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
228 $this->metadata[$metafield] = trim( $this->reader->readInnerXml() );
229
230 $this->reader->next();
231 }
232
239 private function animateFilterAndLang( $name ) {
240 $this->debug( "animate filter for tag $name" );
241 if ( $this->reader->nodeType !== XMLReader::ELEMENT ) {
242 return;
243 }
244 if ( $this->reader->isEmptyElement ) {
245 return;
246 }
247 $exitDepth = $this->reader->depth;
248 $keepReading = $this->reader->read();
249 while ( $keepReading ) {
250 if ( $this->reader->localName === $name && $this->reader->depth <= $exitDepth
251 && $this->reader->nodeType === XMLReader::END_ELEMENT
252 ) {
253 break;
254 }
255
256 if ( $this->reader->namespaceURI === self::NS_SVG
257 && $this->reader->nodeType === XMLReader::ELEMENT
258 ) {
259 $sysLang = $this->reader->getAttribute( 'systemLanguage' );
260 if ( $sysLang !== null && $sysLang !== '' ) {
261 // See https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
262 $langList = explode( ',', $sysLang );
263 foreach ( $langList as $langItem ) {
264 $langItem = trim( $langItem );
265 if ( LanguageCode::isWellFormedLanguageTag( $langItem ) ) {
266 $this->languages[$langItem] = self::LANG_FULL_MATCH;
267 }
268 // Note, the standard says that any prefix should work,
269 // here we do only the initial prefix, since that will catch
270 // 99% of cases, and we are going to compare against fallbacks.
271 // This differs mildly from how the spec says languages should be
272 // handled, however it matches better how the MediaWiki language
273 // preference is generally handled.
274 $dash = strpos( $langItem, '-' );
275 // Intentionally checking both !false and > 0 at the same time.
276 if ( $dash ) {
277 $itemPrefix = substr( $langItem, 0, $dash );
278 if ( LanguageCode::isWellFormedLanguageTag( $itemPrefix ) ) {
279 $this->languagePrefixes[$itemPrefix] = self::LANG_PREFIX_MATCH;
280 }
281 }
282 }
283 }
284 switch ( $this->reader->localName ) {
285 case 'script':
286 // Normally we disallow files with
287 // <script>, but its possible
288 // to configure MW to disable
289 // such checks.
290 case 'animate':
291 case 'set':
292 case 'animateMotion':
293 case 'animateColor':
294 case 'animateTransform':
295 $this->debug( "HOUSTON WE HAVE ANIMATION" );
296 $this->metadata['animated'] = true;
297 break;
298 }
299 }
300 $keepReading = $this->reader->read();
301 }
302 }
303
304 private function debug( $data ) {
305 if ( $this->mDebug ) {
306 wfDebug( "SVGReader: $data" );
307 }
308 }
309
315 private function handleSVGAttribs() {
316 $defaultWidth = self::DEFAULT_WIDTH;
317 $defaultHeight = self::DEFAULT_HEIGHT;
318 $aspect = 1.0;
319 $width = null;
320 $height = null;
321
322 if ( $this->reader->getAttribute( 'viewBox' ) ) {
323 // min-x min-y width height
324 $viewBox = preg_split( '/\s*[\s,]\s*/', trim( $this->reader->getAttribute( 'viewBox' ) ?? '' ) );
325 if ( count( $viewBox ) === 4 ) {
326 $viewWidth = self::scaleSVGUnit( $viewBox[2] );
327 $viewHeight = self::scaleSVGUnit( $viewBox[3] );
328 if ( $viewWidth > 0 && $viewHeight > 0 ) {
329 $aspect = $viewWidth / $viewHeight;
330 $defaultHeight = $defaultWidth / $aspect;
331 }
332 }
333 }
334 if ( $this->reader->getAttribute( 'width' ) ) {
335 $width = self::scaleSVGUnit( $this->reader->getAttribute( 'width' ) ?? '', $defaultWidth );
336 $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
337 }
338 if ( $this->reader->getAttribute( 'height' ) ) {
339 $height = self::scaleSVGUnit( $this->reader->getAttribute( 'height' ) ?? '', $defaultHeight );
340 $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
341 }
342
343 if ( !isset( $width ) && !isset( $height ) ) {
344 $width = $defaultWidth;
345 $height = $width / $aspect;
346 } elseif ( isset( $width ) && !isset( $height ) ) {
347 $height = $width / $aspect;
348 } elseif ( isset( $height ) && !isset( $width ) ) {
349 $width = $height * $aspect;
350 }
351
352 if ( $width > 0 && $height > 0 ) {
353 $this->metadata['width'] = (int)round( $width );
354 $this->metadata['height'] = (int)round( $height );
355 }
356 }
357
366 public static function scaleSVGUnit( $length, $viewportSize = 512 ) {
367 static $unitLength = [
368 'px' => 1.0,
369 'pt' => 1.25,
370 'pc' => 15.0,
371 'mm' => 3.543307,
372 'cm' => 35.43307,
373 'in' => 90.0,
374 'em' => 16.0, // fake it?
375 'ex' => 12.0, // fake it?
376 '' => 1.0, // "User units" pixels by default
377 ];
378 $matches = [];
379 if ( preg_match(
380 '/^\s*([-+]?\d*(?:\.\d+|\d+)(?:[Ee][-+]?\d+)?)\s*(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/',
381 $length,
383 ) ) {
384 $length = (float)$matches[1];
385 $unit = $matches[2];
386 if ( $unit === '%' ) {
387 return $length * 0.01 * $viewportSize;
388 }
389
390 return $length * $unitLength[$unit];
391 }
392
393 // Assume pixels
394 return (float)$length;
395 }
396}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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.
read()
Read the SVG.
const LANG_FULL_MATCH
Definition SVGReader.php:41
__construct( $source)
Creates an SVGReader drawing from the source provided.
Definition SVGReader.php:59
$source