MediaWiki REL1_33
SVGMetadataExtractor.php
Go to the documentation of this file.
1<?php
32 static function getMetadata( $filename ) {
33 $svg = new SVGReader( $filename );
34
35 return $svg->getMetadata();
36 }
37}
38
42class SVGReader {
43 const DEFAULT_WIDTH = 512;
44 const DEFAULT_HEIGHT = 512;
45 const NS_SVG = 'http://www.w3.org/2000/svg';
47 const LANG_FULL_MATCH = 2;
48
50 private $reader = null;
51
53 private $mDebug = false;
54
56 private $metadata = [];
57 private $languages = [];
58 private $languagePrefixes = [];
59
65 function __construct( $source ) {
67 $this->reader = new XMLReader();
68
69 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
70 $size = filesize( $source );
71 if ( $size === false ) {
72 throw new MWException( "Error getting filesize of SVG." );
73 }
74
75 if ( $size > $wgSVGMetadataCutoff ) {
76 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
77 $contents = file_get_contents( $source, false, null, 0, $wgSVGMetadataCutoff );
78 if ( $contents === false ) {
79 throw new MWException( 'Error reading SVG file.' );
80 }
81 $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
82 } else {
83 $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
84 }
85
86 // Expand entities, since Adobe Illustrator uses them for xmlns
87 // attributes (T33719). Note that libxml2 has some protection
88 // against large recursive entity expansions so this is not as
89 // insecure as it might appear to be. However, it is still extremely
90 // insecure. It's necessary to wrap any read() calls with
91 // libxml_disable_entity_loader() to avoid arbitrary local file
92 // inclusion, or even arbitrary code execution if the expect
93 // extension is installed (T48859).
94 $oldDisable = libxml_disable_entity_loader( true );
95 $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
96
97 $this->metadata['width'] = self::DEFAULT_WIDTH;
98 $this->metadata['height'] = self::DEFAULT_HEIGHT;
99
100 // The size in the units specified by the SVG file
101 // (for the metadata box)
102 // Per the SVG spec, if unspecified, default to '100%'
103 $this->metadata['originalWidth'] = '100%';
104 $this->metadata['originalHeight'] = '100%';
105
106 // Because we cut off the end of the svg making an invalid one. Complicated
107 // try catch thing to make sure warnings get restored. Seems like there should
108 // be a better way.
110 try {
111 $this->read();
112 } catch ( Exception $e ) {
113 // Note, if this happens, the width/height will be taken to be 0x0.
114 // Should we consider it the default 512x512 instead?
116 libxml_disable_entity_loader( $oldDisable );
117 throw $e;
118 }
120 libxml_disable_entity_loader( $oldDisable );
121 }
122
126 public function getMetadata() {
127 return $this->metadata;
128 }
129
135 protected function read() {
136 $keepReading = $this->reader->read();
137
138 /* Skip until first element */
139 while ( $keepReading && $this->reader->nodeType != XMLReader::ELEMENT ) {
140 $keepReading = $this->reader->read();
141 }
142
143 if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
144 throw new MWException( "Expected <svg> tag, got " .
145 $this->reader->localName . " in NS " . $this->reader->namespaceURI );
146 }
147 $this->debug( "<svg> tag is correct." );
148 $this->handleSVGAttribs();
149
150 $exitDepth = $this->reader->depth;
151 $keepReading = $this->reader->read();
152 while ( $keepReading ) {
153 $tag = $this->reader->localName;
154 $type = $this->reader->nodeType;
155 $isSVG = ( $this->reader->namespaceURI == self::NS_SVG );
156
157 $this->debug( "$tag" );
158
159 if ( $isSVG && $tag == 'svg' && $type == XMLReader::END_ELEMENT
160 && $this->reader->depth <= $exitDepth
161 ) {
162 break;
163 } elseif ( $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 } elseif ( $this->reader->nodeType == XMLReader::TEXT ) {
211 $this->metadata[$metafield] = trim( $this->reader->value );
212 }
213 $keepReading = $this->reader->read();
214 }
215 }
216
223 private function readXml( $metafield = null ) {
224 $this->debug( "Read top level metadata" );
225 if ( !$metafield || $this->reader->nodeType != XMLReader::ELEMENT ) {
226 return;
227 }
228 // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
229 $this->metadata[$metafield] = trim( $this->reader->readInnerXml() );
230
231 $this->reader->next();
232 }
233
240 private function animateFilterAndLang( $name ) {
241 $this->debug( "animate filter for tag $name" );
242 if ( $this->reader->nodeType != XMLReader::ELEMENT ) {
243 return;
244 }
245 if ( $this->reader->isEmptyElement ) {
246 return;
247 }
248 $exitDepth = $this->reader->depth;
249 $keepReading = $this->reader->read();
250 while ( $keepReading ) {
251 if ( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
252 && $this->reader->nodeType == XMLReader::END_ELEMENT
253 ) {
254 break;
255 } elseif ( $this->reader->namespaceURI == self::NS_SVG
256 && $this->reader->nodeType == XMLReader::ELEMENT
257 ) {
258 $sysLang = $this->reader->getAttribute( 'systemLanguage' );
259 if ( !is_null( $sysLang ) && $sysLang !== '' ) {
260 // See https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
261 $langList = explode( ',', $sysLang );
262 foreach ( $langList as $langItem ) {
263 $langItem = trim( $langItem );
264 if ( Language::isWellFormedLanguageTag( $langItem ) ) {
265 $this->languages[$langItem] = self::LANG_FULL_MATCH;
266 }
267 // Note, the standard says that any prefix should work,
268 // here we do only the initial prefix, since that will catch
269 // 99% of cases, and we are going to compare against fallbacks.
270 // This differs mildly from how the spec says languages should be
271 // handled, however it matches better how the MediaWiki language
272 // preference is generally handled.
273 $dash = strpos( $langItem, '-' );
274 // Intentionally checking both !false and > 0 at the same time.
275 if ( $dash ) {
276 $itemPrefix = substr( $langItem, 0, $dash );
277 if ( Language::isWellFormedLanguageTag( $itemPrefix ) ) {
278 $this->languagePrefixes[$itemPrefix] = self::LANG_PREFIX_MATCH;
279 }
280 }
281 }
282 }
283 switch ( $this->reader->localName ) {
284 case 'script':
285 // Normally we disallow files with
286 // <script>, but its possible
287 // to configure MW to disable
288 // such checks.
289 case 'animate':
290 case 'set':
291 case 'animateMotion':
292 case 'animateColor':
293 case 'animateTransform':
294 $this->debug( "HOUSTON WE HAVE ANIMATION" );
295 $this->metadata['animated'] = true;
296 break;
297 }
298 }
299 $keepReading = $this->reader->read();
300 }
301 }
302
303 private function debug( $data ) {
304 if ( $this->mDebug ) {
305 wfDebug( "SVGReader: $data\n" );
306 }
307 }
308
314 private function handleSVGAttribs() {
315 $defaultWidth = self::DEFAULT_WIDTH;
316 $defaultHeight = self::DEFAULT_HEIGHT;
317 $aspect = 1.0;
318 $width = null;
319 $height = null;
320
321 if ( $this->reader->getAttribute( 'viewBox' ) ) {
322 // min-x min-y width height
323 $viewBox = preg_split( '/\s*[\s,]\s*/', trim( $this->reader->getAttribute( 'viewBox' ) ) );
324 if ( count( $viewBox ) == 4 ) {
325 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
326 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
327 if ( $viewWidth > 0 && $viewHeight > 0 ) {
328 $aspect = $viewWidth / $viewHeight;
329 $defaultHeight = $defaultWidth / $aspect;
330 }
331 }
332 }
333 if ( $this->reader->getAttribute( 'width' ) ) {
334 $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ), $defaultWidth );
335 $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
336 }
337 if ( $this->reader->getAttribute( 'height' ) ) {
338 $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ), $defaultHeight );
339 $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
340 }
341
342 if ( !isset( $width ) && !isset( $height ) ) {
343 $width = $defaultWidth;
344 $height = $width / $aspect;
345 } elseif ( isset( $width ) && !isset( $height ) ) {
346 $height = $width / $aspect;
347 } elseif ( isset( $height ) && !isset( $width ) ) {
348 $width = $height * $aspect;
349 }
350
351 if ( $width > 0 && $height > 0 ) {
352 $this->metadata['width'] = intval( round( $width ) );
353 $this->metadata['height'] = intval( round( $height ) );
354 }
355 }
356
365 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
366 static $unitLength = [
367 'px' => 1.0,
368 'pt' => 1.25,
369 'pc' => 15.0,
370 'mm' => 3.543307,
371 'cm' => 35.43307,
372 'in' => 90.0,
373 'em' => 16.0, // fake it?
374 'ex' => 12.0, // fake it?
375 '' => 1.0, // "User units" pixels by default
376 ];
377 $matches = [];
378 if ( preg_match(
379 '/^\s*([-+]?\d*(?:\.\d+|\d+)(?:[Ee][-+]?\d+)?)\s*(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/',
380 $length,
382 ) ) {
383 $length = floatval( $matches[1] );
384 $unit = $matches[2];
385 if ( $unit == '%' ) {
386 return $length * 0.01 * $viewportSize;
387 } else {
388 return $length * $unitLength[$unit];
389 }
390 } else {
391 // Assume pixels
392 return floatval( $length );
393 }
394 }
395}
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
$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.
static getMetadata( $filename)
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.
readXml( $metafield=null)
Read an XML snippet from an element.
animateFilterAndLang( $name)
Filter all children, looking for animated elements.
readField( $name, $metafield=null)
Read a textelement from an element.
__construct( $source)
Creates an SVGReader drawing from the source provided.
null XMLReader $reader
returning false will NOT prevent logging $e
Definition hooks.txt:2175
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$source