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
155 && $this->reader
->depth
<= $exitDepth
158 } elseif ( $isSVG && $tag == 'title' ) {
159 $this->readField( $tag, 'title' );
160 } elseif ( $isSVG && $tag == 'desc' ) {
161 $this->readField( $tag, 'description' );
162 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader
::ELEMENT
) {
163 $this->readXml( $tag, 'metadata' );
164 } elseif ( $isSVG && $tag == 'script' ) {
165 // We normally do not allow scripted svgs.
166 // However its possible to configure MW to let them
167 // in, and such files should be considered animated.
168 $this->metadata
['animated'] = true;
169 } elseif ( $tag !== '#text' ) {
170 $this->debug( "Unhandled top-level XML tag $tag" );
172 if ( !isset( $this->metadata
['animated'] ) ) {
173 // Recurse into children of current tag, looking for animation.
174 $this->animateFilter( $tag );
178 // Goto next element, which is sibling of current (Skip children).
179 $keepReading = $this->reader
->next();
182 $this->reader
->close();
188 * Read a textelement from an element
190 * @param string $name of the element that we are reading from
191 * @param string $metafield that we will fill with the result
193 private function readField( $name, $metafield = null ) {
194 $this->debug( "Read field $metafield" );
195 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
198 $keepReading = $this->reader
->read();
199 while ( $keepReading ) {
200 if ( $this->reader
->localName
== $name
201 && $this->reader
->namespaceURI
== self
::NS_SVG
202 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
205 } elseif ( $this->reader
->nodeType
== XmlReader
::TEXT
) {
206 $this->metadata
[$metafield] = trim( $this->reader
->value
);
208 $keepReading = $this->reader
->read();
213 * Read an XML snippet from an element
215 * @param string $metafield that we will fill with the result
216 * @throws MWException
218 private function readXml( $metafield = null ) {
219 $this->debug( "Read top level metadata" );
220 if ( !$metafield ||
$this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
223 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
224 if ( method_exists( $this->reader
, 'readInnerXML' ) ) {
225 $this->metadata
[$metafield] = trim( $this->reader
->readInnerXML() );
227 throw new MWException( "The PHP XMLReader extension does not come " .
228 "with readInnerXML() method. Your libxml is probably out of " .
229 "date (need 2.6.20 or later)." );
231 $this->reader
->next();
235 * Filter all children, looking for animate elements
237 * @param string $name of the element that we are reading from
239 private function animateFilter( $name ) {
240 $this->debug( "animate filter for tag $name" );
241 if ( $this->reader
->nodeType
!= XmlReader
::ELEMENT
) {
244 if ( $this->reader
->isEmptyElement
) {
247 $exitDepth = $this->reader
->depth
;
248 $keepReading = $this->reader
->read();
249 while ( $keepReading ) {
250 if ( $this->reader
->localName
== $name && $this->reader
->depth
<= $exitDepth
251 && $this->reader
->nodeType
== XmlReader
::END_ELEMENT
254 } elseif ( $this->reader
->namespaceURI
==
255 self
::NS_SVG
&& $this->reader
->nodeType
== XmlReader
::ELEMENT
257 switch ( $this->reader
->localName
) {
259 // Normally we disallow files with
260 // <script>, but its possible
261 // to configure MW to disable
265 case 'animateMotion':
267 case 'animateTransform':
268 $this->debug( "HOUSTON WE HAVE ANIMATION" );
269 $this->metadata
['animated'] = true;
273 $keepReading = $this->reader
->read();
277 private function throwXmlError( $err ) {
278 $this->debug( "FAILURE: $err" );
279 wfDebug( "SVGReader XML error: $err\n" );
282 private function debug( $data ) {
283 if ( $this->mDebug
) {
284 wfDebug( "SVGReader: $data\n" );
288 private function warn( $data ) {
289 wfDebug( "SVGReader: $data\n" );
292 private function notice( $data ) {
293 wfDebug( "SVGReader WARN: $data\n" );
297 * Parse the attributes of an SVG element
299 * The parser has to be in the start element of "<svg>"
301 private function handleSVGAttribs() {
302 $defaultWidth = self
::DEFAULT_WIDTH
;
303 $defaultHeight = self
::DEFAULT_HEIGHT
;
308 if ( $this->reader
->getAttribute( 'viewBox' ) ) {
309 // min-x min-y width height
310 $viewBox = preg_split( '/\s+/', trim( $this->reader
->getAttribute( 'viewBox' ) ) );
311 if ( count( $viewBox ) == 4 ) {
312 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
313 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
314 if ( $viewWidth > 0 && $viewHeight > 0 ) {
315 $aspect = $viewWidth / $viewHeight;
316 $defaultHeight = $defaultWidth / $aspect;
320 if ( $this->reader
->getAttribute( 'width' ) ) {
321 $width = $this->scaleSVGUnit( $this->reader
->getAttribute( 'width' ), $defaultWidth );
322 $this->metadata
['originalWidth'] = $this->reader
->getAttribute( 'width' );
324 if ( $this->reader
->getAttribute( 'height' ) ) {
325 $height = $this->scaleSVGUnit( $this->reader
->getAttribute( 'height' ), $defaultHeight );
326 $this->metadata
['originalHeight'] = $this->reader
->getAttribute( 'height' );
329 if ( !isset( $width ) && !isset( $height ) ) {
330 $width = $defaultWidth;
331 $height = $width / $aspect;
332 } elseif ( isset( $width ) && !isset( $height ) ) {
333 $height = $width / $aspect;
334 } elseif ( isset( $height ) && !isset( $width ) ) {
335 $width = $height * $aspect;
338 if ( $width > 0 && $height > 0 ) {
339 $this->metadata
['width'] = intval( round( $width ) );
340 $this->metadata
['height'] = intval( round( $height ) );
345 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
346 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
348 * @param string $length CSS/SVG length.
349 * @param $viewportSize : Float optional scale for percentage units...
350 * @return float: length in pixels
352 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
353 static $unitLength = array(
360 'em' => 16.0, // fake it?
361 'ex' => 12.0, // fake it?
362 '' => 1.0, // "User units" pixels by default
365 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
366 $length = floatval( $matches[1] );
368 if ( $unit == '%' ) {
369 return $length * 0.01 * $viewportSize;
371 return $length * $unitLength[$unit];
375 return floatval( $length );