Merge "Define 'MW_UPDATER' when running update.php"
[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 && $this->reader->depth <= $exitDepth ) {
155 break;
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" );
169
170 if ( !isset( $this->metadata['animated'] ) ) {
171 // Recurse into children of current tag, looking for animation.
172 $this->animateFilter( $tag );
173 }
174 }
175
176 // Goto next element, which is sibling of current (Skip children).
177 $keepReading = $this->reader->next();
178 }
179
180 $this->reader->close();
181
182 return true;
183 }
184
185 /**
186 * Read a textelement from an element
187 *
188 * @param string $name of the element that we are reading from
189 * @param string $metafield that we will fill with the result
190 */
191 private function readField( $name, $metafield = null ) {
192 $this->debug( "Read field $metafield" );
193 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
194 return;
195 }
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 ) {
199 break;
200 } elseif ( $this->reader->nodeType == XmlReader::TEXT ) {
201 $this->metadata[$metafield] = trim( $this->reader->value );
202 }
203 $keepReading = $this->reader->read();
204 }
205 }
206
207 /**
208 * Read an XML snippet from an element
209 *
210 * @param string $metafield that we will fill with the result
211 * @throws MWException
212 */
213 private function readXml( $metafield = null ) {
214 $this->debug( "Read top level metadata" );
215 if ( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
216 return;
217 }
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() );
221 } else {
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)." );
223 }
224 $this->reader->next();
225 }
226
227 /**
228 * Filter all children, looking for animate elements
229 *
230 * @param string $name of the element that we are reading from
231 */
232 private function animateFilter( $name ) {
233 $this->debug( "animate filter for tag $name" );
234 if ( $this->reader->nodeType != XmlReader::ELEMENT ) {
235 return;
236 }
237 if ( $this->reader->isEmptyElement ) {
238 return;
239 }
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
245 ) {
246 break;
247 } elseif ( $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT ) {
248 switch ( $this->reader->localName ) {
249 case 'script':
250 // Normally we disallow files with
251 // <script>, but its possible
252 // to configure MW to disable
253 // such checks.
254 case 'animate':
255 case 'set':
256 case 'animateMotion':
257 case 'animateColor':
258 case 'animateTransform':
259 $this->debug( "HOUSTON WE HAVE ANIMATION" );
260 $this->metadata['animated'] = true;
261 break;
262 }
263 }
264 $keepReading = $this->reader->read();
265 }
266 }
267
268 private function throwXmlError( $err ) {
269 $this->debug( "FAILURE: $err" );
270 wfDebug( "SVGReader XML error: $err\n" );
271 }
272
273 private function debug( $data ) {
274 if ( $this->mDebug ) {
275 wfDebug( "SVGReader: $data\n" );
276 }
277 }
278
279 private function warn( $data ) {
280 wfDebug( "SVGReader: $data\n" );
281 }
282
283 private function notice( $data ) {
284 wfDebug( "SVGReader WARN: $data\n" );
285 }
286
287 /**
288 * Parse the attributes of an SVG element
289 *
290 * The parser has to be in the start element of "<svg>"
291 */
292 private function handleSVGAttribs() {
293 $defaultWidth = self::DEFAULT_WIDTH;
294 $defaultHeight = self::DEFAULT_HEIGHT;
295 $aspect = 1.0;
296 $width = null;
297 $height = null;
298
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;
308 }
309 }
310 }
311 if ( $this->reader->getAttribute( 'width' ) ) {
312 $width = $this->scaleSVGUnit( $this->reader->getAttribute( 'width' ), $defaultWidth );
313 $this->metadata['originalWidth'] = $this->reader->getAttribute( 'width' );
314 }
315 if ( $this->reader->getAttribute( 'height' ) ) {
316 $height = $this->scaleSVGUnit( $this->reader->getAttribute( 'height' ), $defaultHeight );
317 $this->metadata['originalHeight'] = $this->reader->getAttribute( 'height' );
318 }
319
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;
327 }
328
329 if ( $width > 0 && $height > 0 ) {
330 $this->metadata['width'] = intval( round( $width ) );
331 $this->metadata['height'] = intval( round( $height ) );
332 }
333 }
334
335 /**
336 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
337 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
338 *
339 * @param string $length CSS/SVG length.
340 * @param $viewportSize : Float optional scale for percentage units...
341 * @return float: length in pixels
342 */
343 static function scaleSVGUnit( $length, $viewportSize = 512 ) {
344 static $unitLength = array(
345 'px' => 1.0,
346 'pt' => 1.25,
347 'pc' => 15.0,
348 'mm' => 3.543307,
349 'cm' => 35.43307,
350 'in' => 90.0,
351 'em' => 16.0, // fake it?
352 'ex' => 12.0, // fake it?
353 '' => 1.0, // "User units" pixels by default
354 );
355 $matches = array();
356 if ( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
357 $length = floatval( $matches[1] );
358 $unit = $matches[2];
359 if ( $unit == '%' ) {
360 return $length * 0.01 * $viewportSize;
361 } else {
362 return $length * $unitLength[$unit];
363 }
364 } else {
365 // Assume pixels
366 return floatval( $length );
367 }
368 }
369 }