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