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';
39 const ADOBE_SVG_ENTITY
= '&ns_svg;';
41 private $reader = null;
42 private $mDebug = false;
43 private $metadata = Array();
48 * Creates an SVGReader drawing from the source provided
49 * @param $source String: URI from which to read
51 function __construct( $source ) {
52 global $wgSVGMetadataCutoff;
53 $this->reader
= new XMLReader();
55 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
56 $size = filesize( $source );
57 if ( $size === false ) {
58 throw new MWException( "Error getting filesize of SVG." );
61 if ( $size > $wgSVGMetadataCutoff ) {
62 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
63 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
64 if ($contents === false) {
65 throw new MWException( 'Error reading SVG file.' );
67 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
69 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
72 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
73 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
75 // Because we cut off the end of the svg making an invalid one. Complicated
76 // try catch thing to make sure warnings get restored. Seems like there should
81 } catch( Exception
$e ) {
89 * @return Array with the known metadata
91 public function getMetadata() {
92 return $this->metadata
;
98 public function read() {
99 $keepReading = $this->reader
->read();
101 /* Skip until first element */
102 while( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
103 $keepReading = $this->reader
->read();
106 # Note, entities not expanded in namespaceURI - bug 31719
107 if ( $this->reader
->localName
!= 'svg' ||
108 ( $this->reader
->namespaceURI
!= self
::NS_SVG
&&
109 $this->reader
->namespaceURI
!= self
::ADOBE_SVG_ENTITY
) ) {
110 throw new MWException( "Expected <svg> tag, got ".
111 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
113 $this->debug( "<svg> tag is correct." );
114 $this->handleSVGAttribs();
116 $exitDepth = $this->reader
->depth
;
117 $keepReading = $this->reader
->read();
118 while ( $keepReading ) {
119 $tag = $this->reader
->localName
;
120 $type = $this->reader
->nodeType
;
121 $isSVG = ($this->reader
->namespaceURI
== self
::NS_SVG
);
123 $this->debug( "$tag" );
125 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
127 } elseif ( $isSVG && $tag == 'title' ) {
128 $this->readField( $tag, 'title' );
129 } elseif ( $isSVG && $tag == 'desc' ) {
130 $this->readField( $tag, 'description' );
131 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
132 $this->readXml( $tag, 'metadata' );
133 } elseif ( $tag !== '#text' ) {
134 $this->debug( "Unhandled top-level XML tag $tag" );
136 if ( !isset( $this->metadata
['animated'] ) ) {
137 // Recurse into children of current tag, looking for animation.
138 $this->animateFilter( $tag );
142 // Goto next element, which is sibling of current (Skip children).
143 $keepReading = $this->reader
->next();
146 $this->reader
->close();
152 * Read a textelement from an element
154 * @param String $name of the element that we are reading from
155 * @param String $metafield that we will fill with the result
157 private function readField( $name, $metafield=null ) {
158 $this->debug ( "Read field $metafield" );
159 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
162 $keepReading = $this->reader
->read();
163 while( $keepReading ) {
164 if( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
166 } elseif( $this->reader
->nodeType
== XmlReader
::TEXT
){
167 $this->metadata
[$metafield] = trim( $this->reader
->value
);
169 $keepReading = $this->reader
->read();
174 * Read an XML snippet from an element
176 * @param String $metafield that we will fill with the result
178 private function readXml( $metafield=null ) {
179 $this->debug ( "Read top level metadata" );
180 if( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
183 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
184 if( method_exists( $this->reader
, 'readInnerXML' ) ) {
185 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
187 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)." );
189 $this->reader
->next();
193 * Filter all children, looking for animate elements
195 * @param String $name of the element that we are reading from
197 private function animateFilter( $name ) {
198 $this->debug ( "animate filter for tag $name" );
199 if( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
202 if ( $this->reader
->isEmptyElement
) {
205 $exitDepth = $this->reader
->depth
;
206 $keepReading = $this->reader
->read();
207 while( $keepReading ) {
208 if( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
209 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
211 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
212 switch( $this->reader
->localName
) {
215 case 'animateMotion':
217 case 'animateTransform':
218 $this->debug( "HOUSTON WE HAVE ANIMATION" );
219 $this->metadata
['animated'] = true;
223 $keepReading = $this->reader
->read();
227 private function throwXmlError( $err ) {
228 $this->debug( "FAILURE: $err" );
229 wfDebug( "SVGReader XML error: $err\n" );
232 private function debug( $data ) {
233 if( $this->mDebug
) {
234 wfDebug( "SVGReader: $data\n" );
238 private function warn( $data ) {
239 wfDebug( "SVGReader: $data\n" );
242 private function notice( $data ) {
243 wfDebug( "SVGReader WARN: $data\n" );
247 * Parse the attributes of an SVG element
249 * The parser has to be in the start element of <svg>
251 private function handleSVGAttribs( ) {
252 $defaultWidth = self
::DEFAULT_WIDTH
;
253 $defaultHeight = self
::DEFAULT_HEIGHT
;
258 if( $this->reader
->getAttribute('viewBox') ) {
259 // min-x min-y width height
260 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute('viewBox') ) );
261 if( count( $viewBox ) == 4 ) {
262 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
263 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
264 if( $viewWidth > 0 && $viewHeight > 0 ) {
265 $aspect = $viewWidth / $viewHeight;
266 $defaultHeight = $defaultWidth / $aspect;
270 if( $this->reader
->getAttribute('width') ) {
271 $width = $this->scaleSVGUnit( $this->reader
->getAttribute('width'), $defaultWidth );
273 if( $this->reader
->getAttribute('height') ) {
274 $height = $this->scaleSVGUnit( $this->reader
->getAttribute('height'), $defaultHeight );
277 if( !isset( $width ) && !isset( $height ) ) {
278 $width = $defaultWidth;
279 $height = $width / $aspect;
280 } elseif( isset( $width ) && !isset( $height ) ) {
281 $height = $width / $aspect;
282 } elseif( isset( $height ) && !isset( $width ) ) {
283 $width = $height * $aspect;
286 if( $width > 0 && $height > 0 ) {
287 $this->metadata
['width'] = intval( round( $width ) );
288 $this->metadata
['height'] = intval( round( $height ) );
293 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
294 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
296 * @param $length String: CSS/SVG length.
297 * @param $viewportSize: Float optional scale for percentage units...
298 * @return float: length in pixels
300 static function scaleSVGUnit( $length, $viewportSize=512 ) {
301 static $unitLength = array(
308 'em' => 16.0, // fake it?
309 'ex' => 12.0, // fake it?
310 '' => 1.0, // "User units" pixels by default
313 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
314 $length = floatval( $matches[1] );
317 return $length * 0.01 * $viewportSize;
319 return $length * $unitLength[$unit];
323 return floatval( $length );