3 * Extraction of SVG image metadata.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 * @author "Derk-Jan Hartman <hartman _at_ videolan d0t org>"
23 * @author Brion Vibber
24 * @copyright Copyright © 2010-2010 Brion Vibber, Derk-Jan Hartman
25 * @license GPL-2.0-or-later
32 const DEFAULT_WIDTH
= 512;
33 const DEFAULT_HEIGHT
= 512;
34 const NS_SVG
= 'http://www.w3.org/2000/svg';
35 const LANG_PREFIX_MATCH
= 1;
36 const LANG_FULL_MATCH
= 2;
38 /** @var null|XMLReader */
39 private $reader = null;
42 private $mDebug = false;
45 private $metadata = [];
46 private $languages = [];
47 private $languagePrefixes = [];
50 * Creates an SVGReader drawing from the source provided
51 * @param string $source URI from which to read
52 * @throws MWException|Exception
54 function __construct( $source ) {
55 global $wgSVGMetadataCutoff;
56 $this->reader
= new XMLReader();
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." );
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.' );
70 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
72 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
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 );
86 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
87 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
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%';
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
98 Wikimedia\
suppressWarnings();
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 Wikimedia\restoreWarnings
();
105 libxml_disable_entity_loader( $oldDisable );
108 Wikimedia\restoreWarnings
();
109 libxml_disable_entity_loader( $oldDisable );
113 * @return array Array with the known metadata
115 public function getMetadata() {
116 return $this->metadata
;
121 * @throws MWException
124 protected function read() {
125 $keepReading = $this->reader
->read();
127 /* Skip until first element */
128 while ( $keepReading && $this->reader
->nodeType
!= XMLReader
::ELEMENT
) {
129 $keepReading = $this->reader
->read();
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
);
136 $this->debug( "<svg> tag is correct." );
137 $this->handleSVGAttribs();
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
);
146 $this->debug( "$tag" );
148 if ( $isSVG && $tag == 'svg' && $type == XMLReader
::END_ELEMENT
149 && $this->reader
->depth
<= $exitDepth
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" );
166 // Recurse into children of current tag, looking for animation and languages.
167 $this->animateFilterAndLang( $tag );
170 // Goto next element, which is sibling of current (Skip children).
171 $keepReading = $this->reader
->next();
174 $this->reader
->close();
176 $this->metadata
['translations'] = $this->languages +
$this->languagePrefixes
;
182 * Read a textelement from an element
184 * @param string $name Name of the element that we are reading from
185 * @param string $metafield Field that we will fill with the result
187 private function readField( $name, $metafield = null ) {
188 $this->debug( "Read field $metafield" );
189 if ( !$metafield ||
$this->reader
->nodeType
!= XMLReader
::ELEMENT
) {
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
199 } elseif ( $this->reader
->nodeType
== XMLReader
::TEXT
) {
200 $this->metadata
[$metafield] = trim( $this->reader
->value
);
202 $keepReading = $this->reader
->read();
207 * Read an XML snippet from an element
209 * @param string $metafield Field that we will fill with the result
210 * @throws MWException
212 private function readXml( $metafield = null ) {
213 $this->debug( "Read top level metadata" );
214 if ( !$metafield ||
$this->reader
->nodeType
!= XMLReader
::ELEMENT
) {
217 // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
218 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXml() );
220 $this->reader
->next();
224 * Filter all children, looking for animated elements.
225 * Also get a list of languages that can be targeted.
227 * @param string $name Name of the element that we are reading from
229 private function animateFilterAndLang( $name ) {
230 $this->debug( "animate filter for tag $name" );
231 if ( $this->reader
->nodeType
!= XMLReader
::ELEMENT
) {
234 if ( $this->reader
->isEmptyElement
) {
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
244 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
245 && $this->reader
->nodeType
== XMLReader
::ELEMENT
247 $sysLang = $this->reader
->getAttribute( 'systemLanguage' );
248 if ( !is_null( $sysLang ) && $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
;
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.
265 $itemPrefix = substr( $langItem, 0, $dash );
266 if ( Language
::isWellFormedLanguageTag( $itemPrefix ) ) {
267 $this->languagePrefixes
[$itemPrefix] = self
::LANG_PREFIX_MATCH
;
272 switch ( $this->reader
->localName
) {
274 // Normally we disallow files with
275 // <script>, but its possible
276 // to configure MW to disable
280 case 'animateMotion':
282 case 'animateTransform':
283 $this->debug( "HOUSTON WE HAVE ANIMATION" );
284 $this->metadata
['animated'] = true;
288 $keepReading = $this->reader
->read();
292 private function debug( $data ) {
293 if ( $this->mDebug
) {
294 wfDebug( "SVGReader: $data\n" );
299 * Parse the attributes of an SVG element
301 * The parser has to be in the start element of "<svg>"
303 private function handleSVGAttribs() {
304 $defaultWidth = self
::DEFAULT_WIDTH
;
305 $defaultHeight = self
::DEFAULT_HEIGHT
;
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;
322 if ( $this->reader
->getAttribute( 'width' ) ) {
323 $width = $this->scaleSVGUnit( $this->reader
->getAttribute( 'width' ), $defaultWidth );
324 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
326 if ( $this->reader
->getAttribute( 'height' ) ) {
327 $height = $this->scaleSVGUnit( $this->reader
->getAttribute( 'height' ), $defaultHeight );
328 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
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;
340 if ( $width > 0 && $height > 0 ) {
341 $this->metadata
['width'] = intval( round( $width ) );
342 $this->metadata
['height'] = intval( round( $height ) );
347 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
348 * https://www.w3.org/TR/SVG11/coords.html#Units
350 * @param string $length CSS/SVG length.
351 * @param float|int $viewportSize Optional scale for percentage units...
352 * @return float Length in pixels
354 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
355 static $unitLength = [
362 'em' => 16.0, // fake it?
363 'ex' => 12.0, // fake it?
364 '' => 1.0, // "User units" pixels by default
368 '/^\s*([-+]?\d*(?:\.\d+|\d+)(?:[Ee][-+]?\d+)?)\s*(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/',
372 $length = floatval( $matches[1] );
374 if ( $unit == '%' ) {
375 return $length * 0.01 * $viewportSize;
377 return $length * $unitLength[$unit];
381 return floatval( $length );