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;
39 private $reader = null;
40 private $mDebug = false;
41 private $metadata = Array();
46 * Creates an SVGReader drawing from the source provided
47 * @param $source String: URI from which to read
49 function __construct( $source ) {
50 global $wgSVGMetadataCutoff;
51 $this->reader
= new XMLReader();
53 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
54 $size = filesize( $source );
55 if ( $size === false ) {
56 throw new MWException( "Error getting filesize of SVG." );
59 if ( $size > $wgSVGMetadataCutoff ) {
60 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
61 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
62 if ($contents === false) {
63 throw new MWException( 'Error reading SVG file.' );
65 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
67 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
70 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
71 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
73 // Because we cut off the end of the svg making an invalid one. Complicated
74 // try catch thing to make sure warnings get restored. Seems like there should
79 } catch( Exception
$e ) {
87 * @return Array with the known metadata
89 public function getMetadata() {
90 return $this->metadata
;
96 public function read() {
97 $keepReading = $this->reader
->read();
99 /* Skip until first element */
100 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
101 $keepReading = $this->reader
->read();
104 if ( !$this->qualifiedNameEquals( $this->reader
->name
, 'svg', 'svg' ) ) {
105 throw new MWException( "Expected <svg> tag, got ".
106 $this->reader
->name
);
108 $this->debug( "<svg> tag is correct." );
109 $this->handleSVGAttribs();
111 $exitDepth = $this->reader
->depth
;
112 $keepReading = $this->reader
->read();
113 while ( $keepReading ) {
114 $tag = $this->reader
->name
;
115 $type = $this->reader
->nodeType
;
117 $this->debug( "$tag" );
119 if ( $this->qualifiedNameEquals( $tag, 'svg', 'svg' ) && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
121 } elseif ( $this->qualifiedNameEquals( $tag, 'svg', 'title' ) ) {
122 $this->readField( $tag, 'title' );
123 } elseif ( $this->qualifiedNameEquals( $tag, 'svg', 'desc' ) ) {
124 $this->readField( $tag, 'description' );
125 } elseif ( $this->qualifiedNameEquals( $tag, 'svg', 'metadata' ) && $type == XmlReader
::ELEMENT
) {
126 $this->readXml( $tag, 'metadata' );
127 } elseif ( $tag !== '#text' ) {
128 $this->debug( "Unhandled top-level XML tag $tag" );
130 if ( !isset( $this->metadata
['animated'] ) ) {
131 // Recurse into children of current tag, looking for animation.
132 $this->animateFilter( $tag );
136 // Goto next element, which is sibling of current (Skip children).
137 $keepReading = $this->reader
->next();
140 $this->reader
->close();
146 * Read a textelement from an element
148 * @param String $name of the element that we are reading from
149 * @param String $metafield that we will fill with the result
151 private function readField( $name, $metafield=null ) {
152 $this->debug ( "Read field $metafield" );
153 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
156 $keepReading = $this->reader
->read();
157 while( $keepReading ) {
158 if( $this->reader
->name
== $name && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
160 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
161 $this->metadata
[$metafield] = trim( $this->reader
->value
);
163 $keepReading = $this->reader
->read();
168 * Read an XML snippet from an element
170 * @param String $metafield that we will fill with the result
172 private function readXml( $metafield=null ) {
173 $this->debug ( "Read top level metadata" );
174 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
177 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
178 $this->metadata
[$metafield] = $this->reader
->readInnerXML();
179 $this->reader
->next();
183 * Filter all children, looking for animate elements
185 * @param String $name of the element that we are reading from
187 private function animateFilter( $name ) {
188 $this->debug ( "animate filter for tag $name" );
189 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
192 if ( $this->reader
->isEmptyElement
) {
195 $exitDepth = $this->reader
->depth
;
196 $keepReading = $this->reader
->read();
197 while( $keepReading ) {
198 if( $this->reader
->name
== $name && $this->reader
->depth
<= $exitDepth
199 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
201 } elseif ( $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
202 switch( $this->reader
->name
) {
207 case 'animateMotion':
208 case 'svg:animateMotion':
210 case 'svg:animateColor':
211 case 'animateTransform':
212 case 'svg:animateTransform':
213 $this->debug( "HOUSTON WE HAVE ANIMATION" );
214 $this->metadata
['animated'] = true;
218 $keepReading = $this->reader
->read();
222 private function throwXmlError( $err ) {
223 $this->debug( "FAILURE: $err" );
224 wfDebug( "SVGReader XML error: $err\n" );
227 private function debug( $data ) {
228 if( $this->mDebug
) {
229 wfDebug( "SVGReader: $data\n" );
233 private function warn( $data ) {
234 wfDebug( "SVGReader: $data\n" );
237 private function notice( $data ) {
238 wfDebug( "SVGReader WARN: $data\n" );
242 * Parse the attributes of an SVG element
244 * The parser has to be in the start element of <svg>
246 private function handleSVGAttribs( ) {
247 $defaultWidth = self
::DEFAULT_WIDTH
;
248 $defaultHeight = self
::DEFAULT_HEIGHT
;
253 if( $this->reader
->getAttribute('viewBox') ) {
254 // min-x min-y width height
255 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
256 if( count( $viewBox ) == 4 ) {
257 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
258 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
259 if( $viewWidth > 0 && $viewHeight > 0 ) {
260 $aspect = $viewWidth / $viewHeight;
261 $defaultHeight = $defaultWidth / $aspect;
265 if( $this->reader
->getAttribute('width') ) {
266 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
268 if( $this->reader
->getAttribute('height') ) {
269 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
272 if( !isset( $width ) && !isset( $height ) ) {
273 $width = $defaultWidth;
274 $height = $width / $aspect;
275 } elseif( isset( $width ) && !isset( $height ) ) {
276 $height = $width / $aspect;
277 } elseif( isset( $height ) && !isset( $width ) ) {
278 $width = $height * $aspect;
281 if( $width > 0 && $height > 0 ) {
282 $this->metadata
['width'] = intval( round( $width ) );
283 $this->metadata
['height'] = intval( round( $height ) );
288 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
289 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
291 * @param $length String: CSS/SVG length.
292 * @param $viewportSize: Float optional scale for percentage units...
293 * @return float: length in pixels
295 static function scaleSVGUnit( $length, $viewportSize=512 ) {
296 static $unitLength = array(
303 'em' => 16.0, // fake it?
304 'ex' => 12.0, // fake it?
305 '' => 1.0, // "User units" pixels by default
308 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
309 $length = floatval( $matches[1] );
312 return $length * 0.01 * $viewportSize;
314 return $length * $unitLength[$unit];
318 return floatval( $length );
323 * XML namespace check
325 * Check if a read node name matches the expected nodeName
326 * @param $qualifiedName as read by XMLReader
327 * @param $prefix the namespace prefix that you expect for this element, defaults to svg namespace
328 * @param $localName the localName part of the element that you want to match
332 private function qualifiedNameEquals( $qualifiedName, $prefix="svg", $localName ) {
333 if( ($qualifiedName == $localName && $prefix == "svg" ) ||
334 $qualifiedName == ($prefix . ":" . $localName) ) {