Remove function call from for loop test part in GIFMetadataExtractor::readGCT()
[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 private $reader = null;
48
49 private $mDebug = false;
50
51 private $metadata = array();
52
53 /**
54 * Constructor
55 *
56 * Creates an SVGReader drawing from the source provided
57 * @param string $source URI from which to read
58 * @throws MWException|Exception
59 */
60 function __construct( $source ) {
61 global $wgSVGMetadataCutoff;
62 $this->reader = new XMLReader();
63
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." );
68 }
69
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.' );
75 }
76 $this->reader->XML( $contents, null, LIBXML_NOERROR | LIBXML_NOWARNING );
77 } else {
78 $this->reader->open( $source, null, LIBXML_NOERROR | LIBXML_NOWARNING );
79 }
80
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 );
91
92 $this->metadata['width'] = self::DEFAULT_WIDTH;
93 $this->metadata['height'] = self::DEFAULT_HEIGHT;
94
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%';
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
103 // be a better way.
104 wfSuppressWarnings();
105 try {
106 $this->read();
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?
110 wfRestoreWarnings();
111 libxml_disable_entity_loader( $oldDisable );
112 throw $e;
113 }
114 wfRestoreWarnings();
115 libxml_disable_entity_loader( $oldDisable );
116 }
117
118 /**
119 * @return Array with the known metadata
120 */
121 public function getMetadata() {
122 return $this->metadata;
123 }
124
125 /**
126 * Read the SVG
127 * @throws MWException
128 * @return bool
129 */
130 protected function read() {
131 $keepReading = $this->reader->read();
132
133 /* Skip until first element */
134 while ( $keepReading && $this->reader->nodeType != XmlReader::ELEMENT ) {
135 $keepReading = $this->reader->read();
136 }
137
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 );
141 }
142 $this->debug( "<svg> tag is correct." );
143 $this->handleSVGAttribs();
144
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 );
151
152 $this->debug( "$tag" );
153
154 if ( $isSVG && $tag == 'svg' && $type == XmlReader::END_ELEMENT
155 && $this->reader->depth <= $exitDepth
156 ) {
157 break;
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" );
171
172 if ( !isset( $this->metadata['animated'] ) ) {
173 // Recurse into children of current tag, looking for animation.
174 $this->animateFilter( $tag );
175 }
176 }
177
178 // Goto next element, which is sibling of current (Skip children).
179 $keepReading = $this->reader->next();
180 }
181
182 $this->reader->close();
183
184 return true;
185 }
186
187 /**
188 * Read a textelement from an element
189 *
190 * @param string $name of the element that we are reading from
191 * @param string $metafield that we will fill with the result
192 */
193 private function readField( $name, $metafield = null ) {
194 $this->debug( "Read field $metafield" );
195 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
196 return;
197 }
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
203 ) {
204 break;
205 } elseif ( $this->reader->nodeType == XmlReader::TEXT ) {
206 $this->metadata[$metafield] = trim( $this->reader->value );
207 }
208 $keepReading = $this->reader->read();
209 }
210 }
211
212 /**
213 * Read an XML snippet from an element
214 *
215 * @param string $metafield that we will fill with the result
216 * @throws MWException
217 */
218 private function readXml( $metafield = null ) {
219 $this->debug( "Read top level metadata" );
220 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
221 return;
222 }
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() );
226 } else {
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)." );
230 }
231 $this->reader->next();
232 }
233
234 /**
235 * Filter all children, looking for animate elements
236 *
237 * @param string $name of the element that we are reading from
238 */
239 private function animateFilter( $name ) {
240 $this->debug( "animate filter for tag $name" );
241 if ( $this->reader->nodeType != XmlReader::ELEMENT ) {
242 return;
243 }
244 if ( $this->reader->isEmptyElement ) {
245 return;
246 }
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
252 ) {
253 break;
254 } elseif ( $this->reader->namespaceURI ==
255 self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT
256 ) {
257 switch ( $this->reader->localName ) {
258 case 'script':
259 // Normally we disallow files with
260 // <script>, but its possible
261 // to configure MW to disable
262 // such checks.
263 case 'animate':
264 case 'set':
265 case 'animateMotion':
266 case 'animateColor':
267 case 'animateTransform':
268 $this->debug( "HOUSTON WE HAVE ANIMATION" );
269 $this->metadata['animated'] = true;
270 break;
271 }
272 }
273 $keepReading = $this->reader->read();
274 }
275 }
276
277 private function throwXmlError( $err ) {
278 $this->debug( "FAILURE: $err" );
279 wfDebug( "SVGReader XML error: $err\n" );
280 }
281
282 private function debug( $data ) {
283 if ( $this->mDebug ) {
284 wfDebug( "SVGReader: $data\n" );
285 }
286 }
287
288 private function warn( $data ) {
289 wfDebug( "SVGReader: $data\n" );
290 }
291
292 private function notice( $data ) {
293 wfDebug( "SVGReader WARN: $data\n" );
294 }
295
296 /**
297 * Parse the attributes of an SVG element
298 *
299 * The parser has to be in the start element of "<svg>"
300 */
301 private function handleSVGAttribs() {
302 $defaultWidth = self::DEFAULT_WIDTH;
303 $defaultHeight = self::DEFAULT_HEIGHT;
304 $aspect = 1.0;
305 $width = null;
306 $height = null;
307
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;
317 }
318 }
319 }
320 if ( $this->reader->getAttribute( 'width' ) ) {
321 $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ), $defaultWidth );
322 $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
323 }
324 if ( $this->reader->getAttribute( 'height' ) ) {
325 $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ), $defaultHeight );
326 $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
327 }
328
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;
336 }
337
338 if ( $width > 0 && $height > 0 ) {
339 $this->metadata['width'] = intval( round( $width ) );
340 $this->metadata['height'] = intval( round( $height ) );
341 }
342 }
343
344 /**
345 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
346 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
347 *
348 * @param string $length CSS/SVG length.
349 * @param $viewportSize : Float optional scale for percentage units...
350 * @return float: length in pixels
351 */
352 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
353 static $unitLength = array(
354 'px' => 1.0,
355 'pt' => 1.25,
356 'pc' => 15.0,
357 'mm' => 3.543307,
358 'cm' => 35.43307,
359 'in' => 90.0,
360 'em' => 16.0, // fake it?
361 'ex' => 12.0, // fake it?
362 '' => 1.0, // "User units" pixels by default
363 );
364 $matches = array();
365 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
366 $length = floatval( $matches[1] );
367 $unit = $matches[2];
368 if ( $unit == '%' ) {
369 return $length * 0.01 * $viewportSize;
370 } else {
371 return $length * $unitLength[$unit];
372 }
373 } else {
374 // Assume pixels
375 return floatval( $length );
376 }
377 }
378 }