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 );
35 return $svg->getMetadata();
43 const DEFAULT_WIDTH
= 512;
44 const DEFAULT_HEIGHT
= 512;
45 const NS_SVG
= 'http://www.w3.org/2000/svg';
47 private $reader = null;
49 private $mDebug = false;
51 private $metadata = array();
56 * Creates an SVGReader drawing from the source provided
57 * @param string $source URI from which to read
58 * @throws MWException|Exception
60 function __construct( $source ) {
61 global $wgSVGMetadataCutoff;
62 $this->reader
= new XMLReader();
64 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
65 $size = filesize( $source );
66 if ( $size === false ) {
67 throw new MWException( "Error getting filesize of SVG." );
70 if ( $size > $wgSVGMetadataCutoff ) {
71 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
72 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
73 if ( $contents === false ) {
74 throw new MWException( 'Error reading SVG file.' );
76 $this->reader
->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
78 $this->reader
->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING
);
81 // Expand entities, since Adobe Illustrator uses them for xmlns
82 // attributes (bug 31719). Note that libxml2 has some protection
83 // against large recursive entity expansions so this is not as
84 // insecure as it might appear to be. However, it is still extremely
85 // insecure. It's necessary to wrap any read() calls with
86 // libxml_disable_entity_loader() to avoid arbitrary local file
87 // inclusion, or even arbitrary code execution if the expect
88 // extension is installed (bug 46859).
89 $oldDisable = libxml_disable_entity_loader( true );
90 $this->reader
->setParserProperty( XMLReader
::SUBST_ENTITIES
, true );
92 $this->metadata
['width'] = self
::DEFAULT_WIDTH
;
93 $this->metadata
['height'] = self
::DEFAULT_HEIGHT
;
95 // The size in the units specified by the SVG file
96 // (for the metadata box)
97 // Per the SVG spec, if unspecified, default to '100%'
98 $this->metadata
['originalWidth'] = '100%';
99 $this->metadata
['originalHeight'] = '100%';
101 // Because we cut off the end of the svg making an invalid one. Complicated
102 // try catch thing to make sure warnings get restored. Seems like there should
104 wfSuppressWarnings();
107 } catch ( Exception
$e ) {
108 // Note, if this happens, the width/height will be taken to be 0x0.
109 // Should we consider it the default 512x512 instead?
111 libxml_disable_entity_loader( $oldDisable );
115 libxml_disable_entity_loader( $oldDisable );
119 * @return Array with the known metadata
121 public function getMetadata() {
122 return $this->metadata
;
127 * @throws MWException
130 protected function read() {
131 $keepReading = $this->reader
->read();
133 /* Skip until first element */
134 while ( $keepReading && $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
135 $keepReading = $this->reader
->read();
138 if ( $this->reader
->localName
!= 'svg' ||
$this->reader
->namespaceURI
!= self
::NS_SVG
) {
139 throw new MWException( "Expected <svg> tag, got " .
140 $this->reader
->localName
. " in NS " . $this->reader
->namespaceURI
);
142 $this->debug( "<svg> tag is correct." );
143 $this->handleSVGAttribs();
145 $exitDepth = $this->reader
->depth
;
146 $keepReading = $this->reader
->read();
147 while ( $keepReading ) {
148 $tag = $this->reader
->localName
;
149 $type = $this->reader
->nodeType
;
150 $isSVG = ( $this->reader
->namespaceURI
== self
::NS_SVG
);
152 $this->debug( "$tag" );
154 if ( $isSVG && $tag == 'svg' && $type == XmlReader
::END_ELEMENT
&& $this->reader
->depth
<= $exitDepth ) {
156 } elseif ( $isSVG && $tag == 'title' ) {
157 $this->readField( $tag, 'title' );
158 } elseif ( $isSVG && $tag == 'desc' ) {
159 $this->readField( $tag, 'description' );
160 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
161 $this->readXml( $tag, 'metadata' );
162 } elseif ( $isSVG && $tag == 'script' ) {
163 // We normally do not allow scripted svgs.
164 // However its possible to configure MW to let them
165 // in, and such files should be considered animated.
166 $this->metadata
['animated'] = true;
167 } elseif ( $tag !== '#text' ) {
168 $this->debug( "Unhandled top-level XML tag $tag" );
170 if ( !isset( $this->metadata
['animated'] ) ) {
171 // Recurse into children of current tag, looking for animation.
172 $this->animateFilter( $tag );
176 // Goto next element, which is sibling of current (Skip children).
177 $keepReading = $this->reader
->next();
180 $this->reader
->close();
186 * Read a textelement from an element
188 * @param string $name of the element that we are reading from
189 * @param string $metafield that we will fill with the result
191 private function readField( $name, $metafield = null ) {
192 $this->debug( "Read field $metafield" );
193 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
196 $keepReading = $this->reader
->read();
197 while ( $keepReading ) {
198 if ( $this->reader
->localName
== $name && $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::END_ELEMENT
) {
200 } elseif ( $this->reader
->nodeType
== XmlReader
::TEXT
) {
201 $this->metadata
[$metafield] = trim( $this->reader
->value
);
203 $keepReading = $this->reader
->read();
208 * Read an XML snippet from an element
210 * @param string $metafield that we will fill with the result
211 * @throws MWException
213 private function readXml( $metafield = null ) {
214 $this->debug( "Read top level metadata" );
215 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
218 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
219 if ( method_exists( $this->reader
, 'readInnerXML' ) ) {
220 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
222 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)." );
224 $this->reader
->next();
228 * Filter all children, looking for animate elements
230 * @param string $name of the element that we are reading from
232 private function animateFilter( $name ) {
233 $this->debug( "animate filter for tag $name" );
234 if ( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
237 if ( $this->reader
->isEmptyElement
) {
240 $exitDepth = $this->reader
->depth
;
241 $keepReading = $this->reader
->read();
242 while ( $keepReading ) {
243 if ( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
244 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
247 } elseif ( $this->reader
->namespaceURI
== self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
) {
248 switch ( $this->reader
->localName
) {
250 // Normally we disallow files with
251 // <script>, but its possible
252 // to configure MW to disable
256 case 'animateMotion':
258 case 'animateTransform':
259 $this->debug( "HOUSTON WE HAVE ANIMATION" );
260 $this->metadata
['animated'] = true;
264 $keepReading = $this->reader
->read();
268 private function throwXmlError( $err ) {
269 $this->debug( "FAILURE: $err" );
270 wfDebug( "SVGReader XML error: $err\n" );
273 private function debug( $data ) {
274 if ( $this->mDebug
) {
275 wfDebug( "SVGReader: $data\n" );
279 private function warn( $data ) {
280 wfDebug( "SVGReader: $data\n" );
283 private function notice( $data ) {
284 wfDebug( "SVGReader WARN: $data\n" );
288 * Parse the attributes of an SVG element
290 * The parser has to be in the start element of "<svg>"
292 private function handleSVGAttribs() {
293 $defaultWidth = self
::DEFAULT_WIDTH
;
294 $defaultHeight = self
::DEFAULT_HEIGHT
;
299 if ( $this->reader
->getAttribute( 'viewBox' ) ) {
300 // min-x min-y width height
301 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute( 'viewBox' ) ) );
302 if ( count( $viewBox ) == 4 ) {
303 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
304 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
305 if ( $viewWidth > 0 && $viewHeight > 0 ) {
306 $aspect = $viewWidth / $viewHeight;
307 $defaultHeight = $defaultWidth / $aspect;
311 if ( $this->reader
->getAttribute( 'width' ) ) {
312 $width = $this->scaleSVGUnit( $this->reader
->getAttribute( 'width' ), $defaultWidth );
313 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
315 if ( $this->reader
->getAttribute( 'height' ) ) {
316 $height = $this->scaleSVGUnit( $this->reader
->getAttribute( 'height' ), $defaultHeight );
317 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
320 if ( !isset( $width ) && !isset( $height ) ) {
321 $width = $defaultWidth;
322 $height = $width / $aspect;
323 } elseif ( isset( $width ) && !isset( $height ) ) {
324 $height = $width / $aspect;
325 } elseif ( isset( $height ) && !isset( $width ) ) {
326 $width = $height * $aspect;
329 if ( $width > 0 && $height > 0 ) {
330 $this->metadata
['width'] = intval( round( $width ) );
331 $this->metadata
['height'] = intval( round( $height ) );
336 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
337 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
339 * @param string $length CSS/SVG length.
340 * @param $viewportSize : Float optional scale for percentage units...
341 * @return float: length in pixels
343 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
344 static $unitLength = array(
351 'em' => 16.0, // fake it?
352 'ex' => 12.0, // fake it?
353 '' => 1.0, // "User units" pixels by default
356 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
357 $length = floatval( $matches[1] );
359 if ( $unit == '%' ) {
360 return $length * 0.01 * $viewportSize;
362 return $length * $unitLength[$unit];
366 return floatval( $length );