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 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
72 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
74 // Because we cut off the end of the svg making an invalid one. Complicated
75 // try catch thing to make sure warnings get restored. Seems like there should
80 } catch( Exception
$e ) {
88 * @return Array with the known metadata
90 public function getMetadata() {
91 return $this->metadata
;
97 public function read() {
98 $keepReading = $this->reader
->read();
100 /* Skip until first element */
101 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
102 $keepReading = $this->reader
->read();
105 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
106 throw new MWException( "Expected <svg> tag, got ".
107 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
109 $this->debug( "<svg> tag is correct." );
110 $this->handleSVGAttribs();
112 $exitDepth = $this->reader
->depth
;
113 $keepReading = $this->reader
->read();
114 while ( $keepReading ) {
115 $tag = $this->reader
->localName
;
116 $type = $this->reader
->nodeType
;
117 $isSVG = ($this->reader
->namespaceURI
== self
::NS_SVG
);
119 $this->debug( "$tag" );
121 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
123 } elseif ( $isSVG && $tag == 'title' ) {
124 $this->readField( $tag, 'title' );
125 } elseif ( $isSVG && $tag == 'desc' ) {
126 $this->readField( $tag, 'description' );
127 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
128 $this->readXml( $tag, 'metadata' );
129 } elseif ( $tag !== '#text' ) {
130 $this->debug( "Unhandled top-level XML tag $tag" );
132 if ( !isset( $this->metadata
['animated'] ) ) {
133 // Recurse into children of current tag, looking for animation.
134 $this->animateFilter( $tag );
138 // Goto next element, which is sibling of current (Skip children).
139 $keepReading = $this->reader
->next();
142 $this->reader
->close();
148 * Read a textelement from an element
150 * @param String $name of the element that we are reading from
151 * @param String $metafield that we will fill with the result
153 private function readField( $name, $metafield=null ) {
154 $this->debug ( "Read field $metafield" );
155 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
158 $keepReading = $this->reader
->read();
159 while( $keepReading ) {
160 if( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
162 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
163 $this->metadata
[$metafield] = trim( $this->reader
->value
);
165 $keepReading = $this->reader
->read();
170 * Read an XML snippet from an element
172 * @param String $metafield that we will fill with the result
174 private function readXml( $metafield=null ) {
175 $this->debug ( "Read top level metadata" );
176 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
179 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
180 if( method_exists( $this->reader
, 'readInnerXML' ) ) {
181 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
183 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)." );
185 $this->reader
->next();
189 * Filter all children, looking for animate elements
191 * @param String $name of the element that we are reading from
193 private function animateFilter( $name ) {
194 $this->debug ( "animate filter for tag $name" );
195 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
198 if ( $this->reader
->isEmptyElement
) {
201 $exitDepth = $this->reader
->depth
;
202 $keepReading = $this->reader
->read();
203 while( $keepReading ) {
204 if( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
205 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
207 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
208 switch( $this->reader
->localName
) {
211 case 'animateMotion':
213 case 'animateTransform':
214 $this->debug( "HOUSTON WE HAVE ANIMATION" );
215 $this->metadata
['animated'] = true;
219 $keepReading = $this->reader
->read();
223 private function throwXmlError( $err ) {
224 $this->debug( "FAILURE: $err" );
225 wfDebug( "SVGReader XML error: $err\n" );
228 private function debug( $data ) {
229 if( $this->mDebug
) {
230 wfDebug( "SVGReader: $data\n" );
234 private function warn( $data ) {
235 wfDebug( "SVGReader: $data\n" );
238 private function notice( $data ) {
239 wfDebug( "SVGReader WARN: $data\n" );
243 * Parse the attributes of an SVG element
245 * The parser has to be in the start element of <svg>
247 private function handleSVGAttribs( ) {
248 $defaultWidth = self
::DEFAULT_WIDTH
;
249 $defaultHeight = self
::DEFAULT_HEIGHT
;
254 if( $this->reader
->getAttribute('viewBox') ) {
255 // min-x min-y width height
256 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
257 if( count( $viewBox ) == 4 ) {
258 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
259 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
260 if( $viewWidth > 0 && $viewHeight > 0 ) {
261 $aspect = $viewWidth / $viewHeight;
262 $defaultHeight = $defaultWidth / $aspect;
266 if( $this->reader
->getAttribute('width') ) {
267 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
269 if( $this->reader
->getAttribute('height') ) {
270 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
273 if( !isset( $width ) && !isset( $height ) ) {
274 $width = $defaultWidth;
275 $height = $width / $aspect;
276 } elseif( isset( $width ) && !isset( $height ) ) {
277 $height = $width / $aspect;
278 } elseif( isset( $height ) && !isset( $width ) ) {
279 $width = $height * $aspect;
282 if( $width > 0 && $height > 0 ) {
283 $this->metadata
['width'] = intval( round( $width ) );
284 $this->metadata
['height'] = intval( round( $height ) );
289 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
290 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
292 * @param $length String: CSS/SVG length.
293 * @param $viewportSize: Float optional scale for percentage units...
294 * @return float: length in pixels
296 static function scaleSVGUnit( $length, $viewportSize=512 ) {
297 static $unitLength = array(
304 'em' => 16.0, // fake it?
305 'ex' => 12.0, // fake it?
306 '' => 1.0, // "User units" pixels by default
309 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
310 $length = floatval( $matches[1] );
313 return $length * 0.01 * $viewportSize;
315 return $length * $unitLength[$unit];
319 return floatval( $length );