db58c6200cff54e517752f1694dd0074105c43e6
[lhc/web/wiklou.git] / includes / media / SVGMetadataExtractor.php
1 <?php
2 /**
3 * Extraction of SVG image metadata.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
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
26 */
27
28 /**
29 * @ingroup Media
30 */
31 class SVGMetadataExtractor {
32 static function getMetadata( $filename ) {
33 $svg = new SVGReader( $filename );
34
35 return $svg->getMetadata();
36 }
37 }
38
39 /**
40 * @ingroup Media
41 */
42 class SVGReader {
43 const DEFAULT_WIDTH = 512;
44 const DEFAULT_HEIGHT = 512;
45 const NS_SVG = 'http://www.w3.org/2000/svg';
46
47 /** @var null|XMLReader */
48 private $reader = null;
49
50 /** @var bool */
51 private $mDebug = false;
52
53 /** @var array */
54 private $metadata = array();
55
56 /**
57 * Constructor
58 *
59 * Creates an SVGReader drawing from the source provided
60 * @param string $source URI from which to read
61 * @throws MWException|Exception
62 */
63 function __construct( $source ) {
64 global $wgSVGMetadataCutoff;
65 $this->reader = new XMLReader();
66
67 // Don't use $file->getSize() since file object passed to SVGHandler::getMetadata is bogus.
68 $size = filesize( $source );
69 if ( $size === false ) {
70 throw new MWException( "Error getting filesize of SVG." );
71 }
72
73 if ( $size > $wgSVGMetadataCutoff ) {
74 $this->debug( "SVG is $size bytes, which is bigger than $wgSVGMetadataCutoff. Truncating." );
75 $contents = file_get_contents( $source, false, null, -1, $wgSVGMetadataCutoff );
76 if ( $contents === false ) {
77 throw new MWException( 'Error reading SVG file.' );
78 }
79 $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
80 } else {
81 $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
82 }
83
84 // Expand entities, since Adobe Illustrator uses them for xmlns
85 // attributes (bug 31719). Note that libxml2 has some protection
86 // against large recursive entity expansions so this is not as
87 // insecure as it might appear to be. However, it is still extremely
88 // insecure. It's necessary to wrap any read() calls with
89 // libxml_disable_entity_loader() to avoid arbitrary local file
90 // inclusion, or even arbitrary code execution if the expect
91 // extension is installed (bug 46859).
92 $oldDisable = libxml_disable_entity_loader( true );
93 $this->reader->setParserProperty( XMLReader::SUBST_ENTITIES, true );
94
95 $this->metadata['width'] = self::DEFAULT_WIDTH;
96 $this->metadata['height'] = self::DEFAULT_HEIGHT;
97
98 // The size in the units specified by the SVG file
99 // (for the metadata box)
100 // Per the SVG spec, if unspecified, default to '100%'
101 $this->metadata['originalWidth'] = '100%';
102 $this->metadata['originalHeight'] = '100%';
103
104 // Because we cut off the end of the svg making an invalid one. Complicated
105 // try catch thing to make sure warnings get restored. Seems like there should
106 // be a better way.
107 wfSuppressWarnings();
108 try {
109 $this->read();
110 } catch ( Exception $e ) {
111 // Note, if this happens, the width/height will be taken to be 0x0.
112 // Should we consider it the default 512x512 instead?
113 wfRestoreWarnings();
114 libxml_disable_entity_loader( $oldDisable );
115 throw $e;
116 }
117 wfRestoreWarnings();
118 libxml_disable_entity_loader( $oldDisable );
119 }
120
121 /**
122 * @return Array with the known metadata
123 */
124 public function getMetadata() {
125 return $this->metadata;
126 }
127
128 /**
129 * Read the SVG
130 * @throws MWException
131 * @return bool
132 */
133 protected function read() {
134 $keepReading = $this->reader->read();
135
136 /* Skip until first element */
137 while ( $keepReading && $this->reader->nodeType != XmlReader::ELEMENT ) {
138 $keepReading = $this->reader->read();
139 }
140
141 if ( $this->reader->localName != 'svg' || $this->reader->namespaceURI != self::NS_SVG ) {
142 throw new MWException( "Expected <svg> tag, got " .
143 $this->reader->localName . " in NS " . $this->reader->namespaceURI );
144 }
145 $this->debug( "<svg> tag is correct." );
146 $this->handleSVGAttribs();
147
148 $exitDepth = $this->reader->depth;
149 $keepReading = $this->reader->read();
150 while ( $keepReading ) {
151 $tag = $this->reader->localName;
152 $type = $this->reader->nodeType;
153 $isSVG = ( $this->reader->namespaceURI == self::NS_SVG );
154
155 $this->debug( "$tag" );
156
157 if ( $isSVG && $tag == 'svg' && $type == XmlReader::END_ELEMENT
158 && $this->reader->depth <= $exitDepth
159 ) {
160 break;
161 } elseif ( $isSVG && $tag == 'title' ) {
162 $this->readField( $tag, 'title' );
163 } elseif ( $isSVG && $tag == 'desc' ) {
164 $this->readField( $tag, 'description' );
165 } elseif ( $isSVG && $tag == 'metadata' && $type == XmlReader::ELEMENT ) {
166 $this->readXml( $tag, 'metadata' );
167 } elseif ( $isSVG && $tag == 'script' ) {
168 // We normally do not allow scripted svgs.
169 // However its possible to configure MW to let them
170 // in, and such files should be considered animated.
171 $this->metadata['animated'] = true;
172 } elseif ( $tag !== '#text' ) {
173 $this->debug( "Unhandled top-level XML tag $tag" );
174
175 if ( !isset( $this->metadata['animated'] ) ) {
176 // Recurse into children of current tag, looking for animation.
177 $this->animateFilter( $tag );
178 }
179 }
180
181 // Goto next element, which is sibling of current (Skip children).
182 $keepReading = $this->reader->next();
183 }
184
185 $this->reader->close();
186
187 return true;
188 }
189
190 /**
191 * Read a textelement from an element
192 *
193 * @param string $name Name of the element that we are reading from
194 * @param string $metafield Field that we will fill with the result
195 */
196 private function readField( $name, $metafield = null ) {
197 $this->debug( "Read field $metafield" );
198 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
199 return;
200 }
201 $keepReading = $this->reader->read();
202 while ( $keepReading ) {
203 if ( $this->reader->localName == $name
204 && $this->reader->namespaceURI == self::NS_SVG
205 && $this->reader->nodeType == XmlReader::END_ELEMENT
206 ) {
207 break;
208 } elseif ( $this->reader->nodeType == XmlReader::TEXT ) {
209 $this->metadata[$metafield] = trim( $this->reader->value );
210 }
211 $keepReading = $this->reader->read();
212 }
213 }
214
215 /**
216 * Read an XML snippet from an element
217 *
218 * @param string $metafield Field that we will fill with the result
219 * @throws MWException
220 */
221 private function readXml( $metafield = null ) {
222 $this->debug( "Read top level metadata" );
223 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
224 return;
225 }
226 // @todo Find and store type of xml snippet. metadata['metadataType'] = "rdf"
227 if ( method_exists( $this->reader, 'readInnerXML' ) ) {
228 $this->metadata[$metafield] = trim( $this->reader->readInnerXML() );
229 } else {
230 throw new MWException( "The PHP XMLReader extension does not come " .
231 "with readInnerXML() method. Your libxml is probably out of " .
232 "date (need 2.6.20 or later)." );
233 }
234 $this->reader->next();
235 }
236
237 /**
238 * Filter all children, looking for animate elements
239 *
240 * @param string $name Name of the element that we are reading from
241 */
242 private function animateFilter( $name ) {
243 $this->debug( "animate filter for tag $name" );
244 if ( $this->reader->nodeType != XmlReader::ELEMENT ) {
245 return;
246 }
247 if ( $this->reader->isEmptyElement ) {
248 return;
249 }
250 $exitDepth = $this->reader->depth;
251 $keepReading = $this->reader->read();
252 while ( $keepReading ) {
253 if ( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
254 && $this->reader->nodeType == XmlReader::END_ELEMENT
255 ) {
256 break;
257 } elseif ( $this->reader->namespaceURI ==
258 self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT
259 ) {
260 switch ( $this->reader->localName ) {
261 case 'script':
262 // Normally we disallow files with
263 // <script>, but its possible
264 // to configure MW to disable
265 // such checks.
266 case 'animate':
267 case 'set':
268 case 'animateMotion':
269 case 'animateColor':
270 case 'animateTransform':
271 $this->debug( "HOUSTON WE HAVE ANIMATION" );
272 $this->metadata['animated'] = true;
273 break;
274 }
275 }
276 $keepReading = $this->reader->read();
277 }
278 }
279
280 // @todo FIXME: Unused, remove?
281 private function throwXmlError( $err ) {
282 $this->debug( "FAILURE: $err" );
283 wfDebug( "SVGReader XML error: $err\n" );
284 }
285
286 private function debug( $data ) {
287 if ( $this->mDebug ) {
288 wfDebug( "SVGReader: $data\n" );
289 }
290 }
291
292 // @todo FIXME: Unused, remove?
293 private function warn( $data ) {
294 wfDebug( "SVGReader: $data\n" );
295 }
296
297 // @todo FIXME: Unused, remove?
298 private function notice( $data ) {
299 wfDebug( "SVGReader WARN: $data\n" );
300 }
301
302 /**
303 * Parse the attributes of an SVG element
304 *
305 * The parser has to be in the start element of "<svg>"
306 */
307 private function handleSVGAttribs() {
308 $defaultWidth = self::DEFAULT_WIDTH;
309 $defaultHeight = self::DEFAULT_HEIGHT;
310 $aspect = 1.0;
311 $width = null;
312 $height = null;
313
314 if ( $this->reader->getAttribute( 'viewBox' ) ) {
315 // min-x min-y width height
316 $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute( 'viewBox' ) ) );
317 if ( count( $viewBox ) == 4 ) {
318 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
319 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
320 if ( $viewWidth > 0 && $viewHeight > 0 ) {
321 $aspect = $viewWidth / $viewHeight;
322 $defaultHeight = $defaultWidth / $aspect;
323 }
324 }
325 }
326 if ( $this->reader->getAttribute( 'width' ) ) {
327 $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ), $defaultWidth );
328 $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
329 }
330 if ( $this->reader->getAttribute( 'height' ) ) {
331 $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ), $defaultHeight );
332 $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
333 }
334
335 if ( !isset( $width ) && !isset( $height ) ) {
336 $width = $defaultWidth;
337 $height = $width / $aspect;
338 } elseif ( isset( $width ) && !isset( $height ) ) {
339 $height = $width / $aspect;
340 } elseif ( isset( $height ) && !isset( $width ) ) {
341 $width = $height * $aspect;
342 }
343
344 if ( $width > 0 && $height > 0 ) {
345 $this->metadata['width'] = intval( round( $width ) );
346 $this->metadata['height'] = intval( round( $height ) );
347 }
348 }
349
350 /**
351 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
352 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
353 *
354 * @param string $length CSS/SVG length.
355 * @param float|int $viewportSize Optional scale for percentage units...
356 * @return float Length in pixels
357 */
358 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
359 static $unitLength = array(
360 'px' => 1.0,
361 'pt' => 1.25,
362 'pc' => 15.0,
363 'mm' => 3.543307,
364 'cm' => 35.43307,
365 'in' => 90.0,
366 'em' => 16.0, // fake it?
367 'ex' => 12.0, // fake it?
368 '' => 1.0, // "User units" pixels by default
369 );
370 $matches = array();
371 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
372 $length = floatval( $matches[1] );
373 $unit = $matches[2];
374 if ( $unit == '%' ) {
375 return $length * 0.01 * $viewportSize;
376 } else {
377 return $length * $unitLength[$unit];
378 }
379 } else {
380 // Assume pixels
381 return floatval( $length );
382 }
383 }
384 }