3 * SVGMetadataExtractor.php
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
28 class SVGMetadataExtractor
{
29 static function getMetadata( $filename ) {
30 $svg = new SVGReader( $filename );
31 return $svg->getMetadata();
36 const DEFAULT_WIDTH
= 512;
37 const DEFAULT_HEIGHT
= 512;
38 const NS_SVG
= 'http://www.w3.org/2000/svg';
40 private $reader = null;
41 private $mDebug = false;
42 private $metadata = Array();
47 * Creates an SVGReader drawing from the source provided
48 * @param $source String: URI from which to read
50 function __construct( $source ) {
51 global $wgSVGMetadataCutoff;
52 $this->reader
= new XMLReader();
54 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
55 $size = filesize( $source );
56 if ( $size === false ) {
57 throw new MWException( "Error getting filesize of SVG." );
60 if ( $size > $wgSVGMetadataCutoff ) {
61 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
62 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
63 if ($contents === false) {
64 throw new MWException( 'Error reading SVG file.' );
66 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
68 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
71 // Expand entities, since Adobe Illustrator uses them for xmlns
72 // attributes (bug 31719). Note that libxml2 has some protection
73 // against large recursive entity expansions so this is not as
74 // insecure as it might appear to be.
75 $this->reader
->setParserProperty( XMLReader
::SUBST_ENTITIES
, true );
77 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
78 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
80 // Because we cut off the end of the svg making an invalid one. Complicated
81 // try catch thing to make sure warnings get restored. Seems like there should
86 } catch( Exception
$e ) {
94 * @return Array with the known metadata
96 public function getMetadata() {
97 return $this->metadata
;
103 public function read() {
104 $keepReading = $this->reader
->read();
106 /* Skip until first element */
107 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
108 $keepReading = $this->reader
->read();
111 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
112 throw new MWException( "Expected <svg> tag, got ".
113 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
115 $this->debug( "<svg> tag is correct." );
116 $this->handleSVGAttribs();
118 $exitDepth = $this->reader
->depth
;
119 $keepReading = $this->reader
->read();
120 while ( $keepReading ) {
121 $tag = $this->reader
->localName
;
122 $type = $this->reader
->nodeType
;
123 $isSVG = ($this->reader
->namespaceURI
== self
::NS_SVG
);
125 $this->debug( "$tag" );
127 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
129 } elseif ( $isSVG && $tag == 'title' ) {
130 $this->readField( $tag, 'title' );
131 } elseif ( $isSVG && $tag == 'desc' ) {
132 $this->readField( $tag, 'description' );
133 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
134 $this->readXml( $tag, 'metadata' );
135 } elseif ( $tag !== '#text' ) {
136 $this->debug( "Unhandled top-level XML tag $tag" );
138 if ( !isset( $this->metadata
['animated'] ) ) {
139 // Recurse into children of current tag, looking for animation.
140 $this->animateFilter( $tag );
144 // Goto next element, which is sibling of current (Skip children).
145 $keepReading = $this->reader
->next();
148 $this->reader
->close();
154 * Read a textelement from an element
156 * @param String $name of the element that we are reading from
157 * @param String $metafield that we will fill with the result
159 private function readField( $name, $metafield=null ) {
160 $this->debug ( "Read field $metafield" );
161 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
164 $keepReading = $this->reader
->read();
165 while( $keepReading ) {
166 if( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
168 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
169 $this->metadata
[$metafield] = trim( $this->reader
->value
);
171 $keepReading = $this->reader
->read();
176 * Read an XML snippet from an element
178 * @param String $metafield that we will fill with the result
180 private function readXml( $metafield=null ) {
181 $this->debug ( "Read top level metadata" );
182 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
185 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
186 if( method_exists( $this->reader
, 'readInnerXML' ) ) {
187 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
189 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)." );
191 $this->reader
->next();
195 * Filter all children, looking for animate elements
197 * @param String $name of the element that we are reading from
199 private function animateFilter( $name ) {
200 $this->debug ( "animate filter for tag $name" );
201 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
204 if ( $this->reader
->isEmptyElement
) {
207 $exitDepth = $this->reader
->depth
;
208 $keepReading = $this->reader
->read();
209 while( $keepReading ) {
210 if( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
211 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
213 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
214 switch( $this->reader
->localName
) {
217 case 'animateMotion':
219 case 'animateTransform':
220 $this->debug( "HOUSTON WE HAVE ANIMATION" );
221 $this->metadata
['animated'] = true;
225 $keepReading = $this->reader
->read();
229 private function throwXmlError( $err ) {
230 $this->debug( "FAILURE: $err" );
231 wfDebug( "SVGReader XML error: $err\n" );
234 private function debug( $data ) {
235 if( $this->mDebug
) {
236 wfDebug( "SVGReader: $data\n" );
240 private function warn( $data ) {
241 wfDebug( "SVGReader: $data\n" );
244 private function notice( $data ) {
245 wfDebug( "SVGReader WARN: $data\n" );
249 * Parse the attributes of an SVG element
251 * The parser has to be in the start element of <svg>
253 private function handleSVGAttribs( ) {
254 $defaultWidth = self
::DEFAULT_WIDTH
;
255 $defaultHeight = self
::DEFAULT_HEIGHT
;
260 if( $this->reader
->getAttribute('viewBox') ) {
261 // min-x min-y width height
262 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
263 if( count( $viewBox ) == 4 ) {
264 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
265 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
266 if( $viewWidth > 0 && $viewHeight > 0 ) {
267 $aspect = $viewWidth / $viewHeight;
268 $defaultHeight = $defaultWidth / $aspect;
272 if( $this->reader
->getAttribute('width') ) {
273 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
275 if( $this->reader
->getAttribute('height') ) {
276 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
279 if( !isset( $width ) && !isset( $height ) ) {
280 $width = $defaultWidth;
281 $height = $width / $aspect;
282 } elseif( isset( $width ) && !isset( $height ) ) {
283 $height = $width / $aspect;
284 } elseif( isset( $height ) && !isset( $width ) ) {
285 $width = $height * $aspect;
288 if( $width > 0 && $height > 0 ) {
289 $this->metadata
['width'] = intval( round( $width ) );
290 $this->metadata
['height'] = intval( round( $height ) );
295 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
296 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
298 * @param $length String: CSS/SVG length.
299 * @param $viewportSize: Float optional scale for percentage units...
300 * @return float: length in pixels
302 static function scaleSVGUnit( $length, $viewportSize=512 ) {
303 static $unitLength = array(
310 'em' => 16.0, // fake it?
311 'ex' => 12.0, // fake it?
312 '' => 1.0, // "User units" pixels by default
315 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
316 $length = floatval( $matches[1] );
319 return $length * 0.01 * $viewportSize;
321 return $length * $unitLength[$unit];
325 return floatval( $length );