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 $source String: URI from which to read
56 function __construct( $source ) {
57 global $wgSVGMetadataCutoff;
58 $this->reader
= new XMLReader();
60 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
61 $size = filesize( $source );
62 if ( $size === false ) {
63 throw new MWException( "Error getting filesize of SVG." );
66 if ( $size > $wgSVGMetadataCutoff ) {
67 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
68 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
69 if ($contents === false) {
70 throw new MWException( 'Error reading SVG file.' );
72 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
74 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
77 // Expand entities, since Adobe Illustrator uses them for xmlns
78 // attributes (bug 31719). Note that libxml2 has some protection
79 // against large recursive entity expansions so this is not as
80 // insecure as it might appear to be.
81 $this->reader
->setParserProperty( XMLReader
::SUBST_ENTITIES
, true );
83 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
84 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
86 // The size in the units specified by the SVG file
87 // (for the metadata box)
88 // Per the SVG spec, if unspecified, default to '100%'
89 $this->metadata
['originalWidth'] = '100%';
90 $this->metadata
['originalHeight'] = '100%';
92 // Because we cut off the end of the svg making an invalid one. Complicated
93 // try catch thing to make sure warnings get restored. Seems like there should
98 } catch( Exception
$e ) {
99 // Note, if this happens, the width/height will be taken to be 0x0.
100 // Should we consider it the default 512x512 instead?
108 * @return Array with the known metadata
110 public function getMetadata() {
111 return $this->metadata
;
118 public function read() {
119 $keepReading = $this->reader
->read();
121 /* Skip until first element */
122 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
123 $keepReading = $this->reader
->read();
126 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
127 throw new MWException( "Expected <svg> tag, got ".
128 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
130 $this->debug( "<svg> tag is correct." );
131 $this->handleSVGAttribs();
133 $exitDepth = $this->reader
->depth
;
134 $keepReading = $this->reader
->read();
135 while ( $keepReading ) {
136 $tag = $this->reader
->localName
;
137 $type = $this->reader
->nodeType
;
138 $isSVG = ($this->reader
->namespaceURI
== self
::NS_SVG
);
140 $this->debug( "$tag" );
142 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
144 } elseif ( $isSVG && $tag == 'title' ) {
145 $this->readField( $tag, 'title' );
146 } elseif ( $isSVG && $tag == 'desc' ) {
147 $this->readField( $tag, 'description' );
148 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
149 $this->readXml( $tag, 'metadata' );
150 } elseif ( $isSVG && $tag == 'script' ) {
151 // We normally do not allow scripted svgs.
152 // However its possible to configure MW to let them
153 // in, and such files should be considered animated.
154 $this->metadata
['animated'] = true;
155 } elseif ( $tag !== '#text' ) {
156 $this->debug( "Unhandled top-level XML tag $tag" );
158 if ( !isset( $this->metadata
['animated'] ) ) {
159 // Recurse into children of current tag, looking for animation.
160 $this->animateFilter( $tag );
164 // Goto next element, which is sibling of current (Skip children).
165 $keepReading = $this->reader
->next();
168 $this->reader
->close();
174 * Read a textelement from an element
176 * @param String $name of the element that we are reading from
177 * @param String $metafield that we will fill with the result
179 private function readField( $name, $metafield=null ) {
180 $this->debug ( "Read field $metafield" );
181 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
184 $keepReading = $this->reader
->read();
185 while( $keepReading ) {
186 if( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
188 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
189 $this->metadata
[$metafield] = trim( $this->reader
->value
);
191 $keepReading = $this->reader
->read();
196 * Read an XML snippet from an element
198 * @param String $metafield that we will fill with the result
200 private function readXml( $metafield=null ) {
201 $this->debug ( "Read top level metadata" );
202 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
205 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
206 if( method_exists( $this->reader
, 'readInnerXML' ) ) {
207 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
209 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)." );
211 $this->reader
->next();
215 * Filter all children, looking for animate elements
217 * @param String $name of the element that we are reading from
219 private function animateFilter( $name ) {
220 $this->debug ( "animate filter for tag $name" );
221 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
224 if ( $this->reader
->isEmptyElement
) {
227 $exitDepth = $this->reader
->depth
;
228 $keepReading = $this->reader
->read();
229 while( $keepReading ) {
230 if( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
231 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
233 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
234 switch( $this->reader
->localName
) {
236 // Normally we disallow files with
237 // <script>, but its possible
238 // to configure MW to disable
242 case 'animateMotion':
244 case 'animateTransform':
245 $this->debug( "HOUSTON WE HAVE ANIMATION" );
246 $this->metadata
['animated'] = true;
250 $keepReading = $this->reader
->read();
254 private function throwXmlError( $err ) {
255 $this->debug( "FAILURE: $err" );
256 wfDebug( "SVGReader XML error: $err\n" );
259 private function debug( $data ) {
260 if( $this->mDebug
) {
261 wfDebug( "SVGReader: $data\n" );
265 private function warn( $data ) {
266 wfDebug( "SVGReader: $data\n" );
269 private function notice( $data ) {
270 wfDebug( "SVGReader WARN: $data\n" );
274 * Parse the attributes of an SVG element
276 * The parser has to be in the start element of "<svg>"
278 private function handleSVGAttribs( ) {
279 $defaultWidth = self
::DEFAULT_WIDTH
;
280 $defaultHeight = self
::DEFAULT_HEIGHT
;
285 if( $this->reader
->getAttribute('viewBox') ) {
286 // min-x min-y width height
287 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
288 if( count( $viewBox ) == 4 ) {
289 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
290 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
291 if( $viewWidth > 0 && $viewHeight > 0 ) {
292 $aspect = $viewWidth / $viewHeight;
293 $defaultHeight = $defaultWidth / $aspect;
297 if( $this->reader
->getAttribute('width') ) {
298 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
299 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
301 if( $this->reader
->getAttribute('height') ) {
302 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
303 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
306 if( !isset( $width ) && !isset( $height ) ) {
307 $width = $defaultWidth;
308 $height = $width / $aspect;
309 } elseif( isset( $width ) && !isset( $height ) ) {
310 $height = $width / $aspect;
311 } elseif( isset( $height ) && !isset( $width ) ) {
312 $width = $height * $aspect;
315 if( $width > 0 && $height > 0 ) {
316 $this->metadata
['width'] = intval( round( $width ) );
317 $this->metadata
['height'] = intval( round( $height ) );
322 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
323 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
325 * @param $length String: CSS/SVG length.
326 * @param $viewportSize: Float optional scale for percentage units...
327 * @return float: length in pixels
329 static function scaleSVGUnit( $length, $viewportSize=512 ) {
330 static $unitLength = array(
337 'em' => 16.0, // fake it?
338 'ex' => 12.0, // fake it?
339 '' => 1.0, // "User units" pixels by default
342 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
343 $length = floatval( $matches[1] );
346 return $length * 0.01 * $viewportSize;
348 return $length * $unitLength[$unit];
352 return floatval( $length );