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