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