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 );
34 return $svg->getMetadata();
42 const DEFAULT_WIDTH
= 512;
43 const DEFAULT_HEIGHT
= 512;
44 const NS_SVG
= 'http://www.w3.org/2000/svg';
46 private $reader = null;
47 private $mDebug = false;
48 private $metadata = Array();
53 * Creates an SVGReader drawing from the source provided
54 * @param string $source URI from which to read
55 * @throws MWException|Exception
57 function __construct( $source ) {
58 global $wgSVGMetadataCutoff;
59 $this->reader
= new XMLReader();
61 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
62 $size = filesize( $source );
63 if ( $size === false ) {
64 throw new MWException( "Error getting filesize of SVG." );
67 if ( $size > $wgSVGMetadataCutoff ) {
68 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
69 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
70 if ( $contents === false ) {
71 throw new MWException( 'Error reading SVG file.' );
73 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
75 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
78 // Expand entities, since Adobe Illustrator uses them for xmlns
79 // attributes (bug 31719). Note that libxml2 has some protection
80 // against large recursive entity expansions so this is not as
81 // insecure as it might appear to be. However, it is still extremely
82 // insecure. It's necessary to wrap any read() calls with
83 // libxml_disable_entity_loader() to avoid arbitrary local file
84 // inclusion, or even arbitrary code execution if the expect
85 // extension is installed (bug 46859).
86 $oldDisable = libxml_disable_entity_loader( true );
87 $this->reader
->setParserProperty( XMLReader
::SUBST_ENTITIES
, true );
89 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
90 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
92 // The size in the units specified by the SVG file
93 // (for the metadata box)
94 // Per the SVG spec, if unspecified, default to '100%'
95 $this->metadata
['originalWidth'] = '100%';
96 $this->metadata
['originalHeight'] = '100%';
98 // Because we cut off the end of the svg making an invalid one. Complicated
99 // try catch thing to make sure warnings get restored. Seems like there should
101 wfSuppressWarnings();
104 } catch ( Exception
$e ) {
105 // Note, if this happens, the width/height will be taken to be 0x0.
106 // Should we consider it the default 512x512 instead?
108 libxml_disable_entity_loader( $oldDisable );
112 libxml_disable_entity_loader( $oldDisable );
116 * @return Array with the known metadata
118 public function getMetadata() {
119 return $this->metadata
;
124 * @throws MWException
127 protected function read() {
128 $keepReading = $this->reader
->read();
130 /* Skip until first element */
131 while ( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
132 $keepReading = $this->reader
->read();
135 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
136 throw new MWException( "Expected <svg> tag, got " .
137 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
139 $this->debug( "<svg> tag is correct." );
140 $this->handleSVGAttribs();
142 $exitDepth = $this->reader
->depth
;
143 $keepReading = $this->reader
->read();
144 while ( $keepReading ) {
145 $tag = $this->reader
->localName
;
146 $type = $this->reader
->nodeType
;
147 $isSVG = ( $this->reader
->namespaceURI
== self
::NS_SVG
);
149 $this->debug( "$tag" );
151 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
153 } elseif ( $isSVG && $tag == 'title' ) {
154 $this->readField( $tag, 'title' );
155 } elseif ( $isSVG && $tag == 'desc' ) {
156 $this->readField( $tag, 'description' );
157 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
158 $this->readXml( $tag, 'metadata' );
159 } elseif ( $isSVG && $tag == 'script' ) {
160 // We normally do not allow scripted svgs.
161 // However its possible to configure MW to let them
162 // in, and such files should be considered animated.
163 $this->metadata
['animated'] = true;
164 } elseif ( $tag !== '#text' ) {
165 $this->debug( "Unhandled top-level XML tag $tag" );
167 if ( !isset( $this->metadata
['animated'] ) ) {
168 // Recurse into children of current tag, looking for animation.
169 $this->animateFilter( $tag );
173 // Goto next element, which is sibling of current (Skip children).
174 $keepReading = $this->reader
->next();
177 $this->reader
->close();
183 * Read a textelement from an element
185 * @param string $name of the element that we are reading from
186 * @param string $metafield that we will fill with the result
188 private function readField( $name, $metafield = null ) {
189 $this->debug( "Read field $metafield" );
190 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
193 $keepReading = $this->reader
->read();
194 while ( $keepReading ) {
195 if ( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
197 } elseif ( $this->reader
->nodeType
== XmlReader
::TEXT
) {
198 $this->metadata
[$metafield] = trim( $this->reader
->value
);
200 $keepReading = $this->reader
->read();
205 * Read an XML snippet from an element
207 * @param string $metafield that we will fill with the result
208 * @throws MWException
210 private function readXml( $metafield = null ) {
211 $this->debug( "Read top level metadata" );
212 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
215 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
216 if ( method_exists( $this->reader
, 'readInnerXML' ) ) {
217 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
219 throw new MWException( "The PHP XMLReader extension does not come with readInnerXML() method. Your libxml is probably out of date (need 2.6.20 or later)." );
221 $this->reader
->next();
225 * Filter all children, looking for animate elements
227 * @param string $name of the element that we are reading from
229 private function animateFilter( $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
) {
243 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
244 switch ( $this->reader
->localName
) {
246 // Normally we disallow files with
247 // <script>, but its possible
248 // to configure MW to disable
252 case 'animateMotion':
254 case 'animateTransform':
255 $this->debug( "HOUSTON WE HAVE ANIMATION" );
256 $this->metadata
['animated'] = true;
260 $keepReading = $this->reader
->read();
264 private function throwXmlError( $err ) {
265 $this->debug( "FAILURE: $err" );
266 wfDebug( "SVGReader XML error: $err\n" );
269 private function debug( $data ) {
270 if ( $this->mDebug
) {
271 wfDebug( "SVGReader: $data\n" );
275 private function warn( $data ) {
276 wfDebug( "SVGReader: $data\n" );
279 private function notice( $data ) {
280 wfDebug( "SVGReader WARN: $data\n" );
284 * Parse the attributes of an SVG element
286 * The parser has to be in the start element of "<svg>"
288 private function handleSVGAttribs() {
289 $defaultWidth = self
::DEFAULT_WIDTH
;
290 $defaultHeight = self
::DEFAULT_HEIGHT
;
295 if ( $this->reader
->getAttribute( 'viewBox' ) ) {
296 // min-x min-y width height
297 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute( 'viewBox' ) ) );
298 if ( count( $viewBox ) == 4 ) {
299 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
300 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
301 if ( $viewWidth > 0 && $viewHeight > 0 ) {
302 $aspect = $viewWidth / $viewHeight;
303 $defaultHeight = $defaultWidth / $aspect;
307 if ( $this->reader
->getAttribute( 'width' ) ) {
308 $width = $this->scaleSVGUnit( $this->reader
->getAttribute( 'width' ), $defaultWidth );
309 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
311 if ( $this->reader
->getAttribute( 'height' ) ) {
312 $height = $this->scaleSVGUnit( $this->reader
->getAttribute( 'height' ), $defaultHeight );
313 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
316 if ( !isset( $width ) && !isset( $height ) ) {
317 $width = $defaultWidth;
318 $height = $width / $aspect;
319 } elseif ( isset( $width ) && !isset( $height ) ) {
320 $height = $width / $aspect;
321 } elseif ( isset( $height ) && !isset( $width ) ) {
322 $width = $height * $aspect;
325 if ( $width > 0 && $height > 0 ) {
326 $this->metadata
['width'] = intval( round( $width ) );
327 $this->metadata
['height'] = intval( round( $height ) );
332 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
333 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
335 * @param string $length CSS/SVG length.
336 * @param $viewportSize: Float optional scale for percentage units...
337 * @return float: length in pixels
339 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
340 static $unitLength = array(
347 'em' => 16.0, // fake it?
348 'ex' => 12.0, // fake it?
349 '' => 1.0, // "User units" pixels by default
352 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
353 $length = floatval( $matches[1] );
355 if ( $unit == '%' ) {
356 return $length * 0.01 * $viewportSize;
358 return $length * $unitLength[$unit];
362 return floatval( $length );