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 // Because we cut off the end of the svg making an invalid one. Complicated
87 // try catch thing to make sure warnings get restored. Seems like there should
92 } catch( Exception
$e ) {
100 * @return Array with the known metadata
102 public function getMetadata() {
103 return $this->metadata
;
110 public function read() {
111 $keepReading = $this->reader
->read();
113 /* Skip until first element */
114 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
115 $keepReading = $this->reader
->read();
118 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
119 throw new MWException( "Expected <svg> tag, got ".
120 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
122 $this->debug( "<svg> tag is correct." );
123 $this->handleSVGAttribs();
125 $exitDepth = $this->reader
->depth
;
126 $keepReading = $this->reader
->read();
127 while ( $keepReading ) {
128 $tag = $this->reader
->localName
;
129 $type = $this->reader
->nodeType
;
130 $isSVG = ($this->reader
->namespaceURI
== self
::NS_SVG
);
132 $this->debug( "$tag" );
134 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
136 } elseif ( $isSVG && $tag == 'title' ) {
137 $this->readField( $tag, 'title' );
138 } elseif ( $isSVG && $tag == 'desc' ) {
139 $this->readField( $tag, 'description' );
140 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
141 $this->readXml( $tag, 'metadata' );
142 } elseif ( $tag !== '#text' ) {
143 $this->debug( "Unhandled top-level XML tag $tag" );
145 if ( !isset( $this->metadata
['animated'] ) ) {
146 // Recurse into children of current tag, looking for animation.
147 $this->animateFilter( $tag );
151 // Goto next element, which is sibling of current (Skip children).
152 $keepReading = $this->reader
->next();
155 $this->reader
->close();
161 * Read a textelement from an element
163 * @param String $name of the element that we are reading from
164 * @param String $metafield that we will fill with the result
166 private function readField( $name, $metafield=null ) {
167 $this->debug ( "Read field $metafield" );
168 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
171 $keepReading = $this->reader
->read();
172 while( $keepReading ) {
173 if( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
175 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
176 $this->metadata
[$metafield] = trim( $this->reader
->value
);
178 $keepReading = $this->reader
->read();
183 * Read an XML snippet from an element
185 * @param String $metafield that we will fill with the result
187 private function readXml( $metafield=null ) {
188 $this->debug ( "Read top level metadata" );
189 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
192 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
193 if( method_exists( $this->reader
, 'readInnerXML' ) ) {
194 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
196 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)." );
198 $this->reader
->next();
202 * Filter all children, looking for animate elements
204 * @param String $name of the element that we are reading from
206 private function animateFilter( $name ) {
207 $this->debug ( "animate filter for tag $name" );
208 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
211 if ( $this->reader
->isEmptyElement
) {
214 $exitDepth = $this->reader
->depth
;
215 $keepReading = $this->reader
->read();
216 while( $keepReading ) {
217 if( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
218 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
220 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
221 switch( $this->reader
->localName
) {
224 case 'animateMotion':
226 case 'animateTransform':
227 $this->debug( "HOUSTON WE HAVE ANIMATION" );
228 $this->metadata
['animated'] = true;
232 $keepReading = $this->reader
->read();
236 private function throwXmlError( $err ) {
237 $this->debug( "FAILURE: $err" );
238 wfDebug( "SVGReader XML error: $err\n" );
241 private function debug( $data ) {
242 if( $this->mDebug
) {
243 wfDebug( "SVGReader: $data\n" );
247 private function warn( $data ) {
248 wfDebug( "SVGReader: $data\n" );
251 private function notice( $data ) {
252 wfDebug( "SVGReader WARN: $data\n" );
256 * Parse the attributes of an SVG element
258 * The parser has to be in the start element of <svg>
260 private function handleSVGAttribs( ) {
261 $defaultWidth = self
::DEFAULT_WIDTH
;
262 $defaultHeight = self
::DEFAULT_HEIGHT
;
267 if( $this->reader
->getAttribute('viewBox') ) {
268 // min-x min-y width height
269 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
270 if( count( $viewBox ) == 4 ) {
271 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
272 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
273 if( $viewWidth > 0 && $viewHeight > 0 ) {
274 $aspect = $viewWidth / $viewHeight;
275 $defaultHeight = $defaultWidth / $aspect;
279 if( $this->reader
->getAttribute('width') ) {
280 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
282 if( $this->reader
->getAttribute('height') ) {
283 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
286 if( !isset( $width ) && !isset( $height ) ) {
287 $width = $defaultWidth;
288 $height = $width / $aspect;
289 } elseif( isset( $width ) && !isset( $height ) ) {
290 $height = $width / $aspect;
291 } elseif( isset( $height ) && !isset( $width ) ) {
292 $width = $height * $aspect;
295 if( $width > 0 && $height > 0 ) {
296 $this->metadata
['width'] = intval( round( $width ) );
297 $this->metadata
['height'] = intval( round( $height ) );
302 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
303 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
305 * @param $length String: CSS/SVG length.
306 * @param $viewportSize: Float optional scale for percentage units...
307 * @return float: length in pixels
309 static function scaleSVGUnit( $length, $viewportSize=512 ) {
310 static $unitLength = array(
317 'em' => 16.0, // fake it?
318 'ex' => 12.0, // fake it?
319 '' => 1.0, // "User units" pixels by default
322 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
323 $length = floatval( $matches[1] );
326 return $length * 0.01 * $viewportSize;
328 return $length * $unitLength[$unit];
332 return floatval( $length );