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