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 http://www.gnu.org/copyleft/gpl.html GNU General Public License
31 class SVGMetadataExtractor
{
32 static function getMetadata( $filename ) {
33 $svg = new SVGReader( $filename );
35 return $svg->getMetadata();
43 const DEFAULT_WIDTH
= 512;
44 const DEFAULT_HEIGHT
= 512;
45 const NS_SVG
= 'http://www.w3.org/2000/svg';
47 /** @var null|XMLReader */
48 private $reader = null;
51 private $mDebug = false;
54 private $metadata = array();
59 * Creates an SVGReader drawing from the source provided
60 * @param string $source URI from which to read
61 * @throws MWException|Exception
63 function __construct( $source ) {
64 global $wgSVGMetadataCutoff;
65 $this->reader
= new XMLReader();
67 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
68 $size = filesize( $source );
69 if ( $size === false ) {
70 throw new MWException( "Error getting filesize of SVG." );
73 if ( $size > $wgSVGMetadataCutoff ) {
74 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
75 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
76 if ( $contents === false ) {
77 throw new MWException( 'Error reading SVG file.' );
79 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
81 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
84 // Expand entities, since Adobe Illustrator uses them for xmlns
85 // attributes (bug 31719). 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 (bug 46859).
92 $oldDisable = libxml_disable_entity_loader( true );
93 $this->reader
->setParserProperty( XMLReader
::SUBST_ENTITIES
, true );
95 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
96 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
98 // The size in the units specified by the SVG file
99 // (for the metadata box)
100 // Per the SVG spec, if unspecified, default to '100%'
101 $this->metadata
['originalWidth'] = '100%';
102 $this->metadata
['originalHeight'] = '100%';
104 // Because we cut off the end of the svg making an invalid one. Complicated
105 // try catch thing to make sure warnings get restored. Seems like there should
107 wfSuppressWarnings();
110 } catch ( Exception
$e ) {
111 // Note, if this happens, the width/height will be taken to be 0x0.
112 // Should we consider it the default 512x512 instead?
114 libxml_disable_entity_loader( $oldDisable );
118 libxml_disable_entity_loader( $oldDisable );
122 * @return Array with the known metadata
124 public function getMetadata() {
125 return $this->metadata
;
130 * @throws MWException
133 protected function read() {
134 $keepReading = $this->reader
->read();
136 /* Skip until first element */
137 while ( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
138 $keepReading = $this->reader
->read();
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
);
145 $this->debug( "<svg> tag is correct." );
146 $this->handleSVGAttribs();
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
);
155 $this->debug( "$tag" );
157 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
158 && $this->reader
->depth
<= $exitDepth
161 } elseif ( $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( $tag, '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" );
175 if ( !isset( $this->metadata
['animated'] ) ) {
176 // Recurse into children of current tag, looking for animation.
177 $this->animateFilter( $tag );
181 // Goto next element, which is sibling of current (Skip children).
182 $keepReading = $this->reader
->next();
185 $this->reader
->close();
191 * Read a textelement from an element
193 * @param string $name Name of the element that we are reading from
194 * @param string $metafield Field that we will fill with the result
196 private function readField( $name, $metafield = null ) {
197 $this->debug( "Read field $metafield" );
198 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
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
208 } elseif ( $this->reader
->nodeType
== XmlReader
::TEXT
) {
209 $this->metadata
[$metafield] = trim( $this->reader
->value
);
211 $keepReading = $this->reader
->read();
216 * Read an XML snippet from an element
218 * @param string $metafield Field that we will fill with the result
219 * @throws MWException
221 private function readXml( $metafield = null ) {
222 $this->debug( "Read top level metadata" );
223 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
226 // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
227 if ( method_exists( $this->reader
, 'readInnerXML' ) ) {
228 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
230 throw new MWException( "The PHP XMLReader extension does not come " .
231 "with readInnerXML() method. Your libxml is probably out of " .
232 "date (need 2.6.20 or later)." );
234 $this->reader
->next();
238 * Filter all children, looking for animate elements
240 * @param string $name Name of the element that we are reading from
242 private function animateFilter( $name ) {
243 $this->debug( "animate filter for tag $name" );
244 if ( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
247 if ( $this->reader
->isEmptyElement
) {
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
257 } elseif ( $this->reader
->namespaceURI
==
258 self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
260 switch ( $this->reader
->localName
) {
262 // Normally we disallow files with
263 // <script>, but its possible
264 // to configure MW to disable
268 case 'animateMotion':
270 case 'animateTransform':
271 $this->debug( "HOUSTON WE HAVE ANIMATION" );
272 $this->metadata
['animated'] = true;
276 $keepReading = $this->reader
->read();
280 // @todo FIXME: Unused, remove?
281 private function throwXmlError( $err ) {
282 $this->debug( "FAILURE: $err" );
283 wfDebug( "SVGReader XML error: $err\n" );
286 private function debug( $data ) {
287 if ( $this->mDebug
) {
288 wfDebug( "SVGReader: $data\n" );
292 // @todo FIXME: Unused, remove?
293 private function warn( $data ) {
294 wfDebug( "SVGReader: $data\n" );
297 // @todo FIXME: Unused, remove?
298 private function notice( $data ) {
299 wfDebug( "SVGReader WARN: $data\n" );
303 * Parse the attributes of an SVG element
305 * The parser has to be in the start element of "<svg>"
307 private function handleSVGAttribs() {
308 $defaultWidth = self
::DEFAULT_WIDTH
;
309 $defaultHeight = self
::DEFAULT_HEIGHT
;
314 if ( $this->reader
->getAttribute( 'viewBox' ) ) {
315 // min-x min-y width height
316 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute( 'viewBox' ) ) );
317 if ( count( $viewBox ) == 4 ) {
318 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
319 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
320 if ( $viewWidth > 0 && $viewHeight > 0 ) {
321 $aspect = $viewWidth / $viewHeight;
322 $defaultHeight = $defaultWidth / $aspect;
326 if ( $this->reader
->getAttribute( 'width' ) ) {
327 $width = $this->scaleSVGUnit( $this->reader
->getAttribute( 'width' ), $defaultWidth );
328 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
330 if ( $this->reader
->getAttribute( 'height' ) ) {
331 $height = $this->scaleSVGUnit( $this->reader
->getAttribute( 'height' ), $defaultHeight );
332 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
335 if ( !isset( $width ) && !isset( $height ) ) {
336 $width = $defaultWidth;
337 $height = $width / $aspect;
338 } elseif ( isset( $width ) && !isset( $height ) ) {
339 $height = $width / $aspect;
340 } elseif ( isset( $height ) && !isset( $width ) ) {
341 $width = $height * $aspect;
344 if ( $width > 0 && $height > 0 ) {
345 $this->metadata
['width'] = intval( round( $width ) );
346 $this->metadata
['height'] = intval( round( $height ) );
351 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
352 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
354 * @param string $length CSS/SVG length.
355 * @param float|int $viewportSize Optional scale for percentage units...
356 * @return float Length in pixels
358 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
359 static $unitLength = array(
366 'em' => 16.0, // fake it?
367 'ex' => 12.0, // fake it?
368 '' => 1.0, // "User units" pixels by default
371 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
372 $length = floatval( $matches[1] );
374 if ( $unit == '%' ) {
375 return $length * 0.01 * $viewportSize;
377 return $length * $unitLength[$unit];
381 return floatval( $length );