Merge "(bug 19195) Make user IDs more readily available with the API"
[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 ( $tag !== '#text' ) {
143 $this->debug( "Unhandled top-level XML tag $tag" );
144
145 if ( !isset( $this->metadata['animated'] ) ) {
146 // Recurse into children of current tag, looking for animation.
147 $this->animateFilter( $tag );
148 }
149 }
150
151 // Goto next element, which is sibling of current (Skip children).
152 $keepReading = $this->reader->next();
153 }
154
155 $this->reader->close();
156
157 return true;
158 }
159
160 /**
161 * Read a textelement from an element
162 *
163 * @param String $name of the element that we are reading from
164 * @param String $metafield that we will fill with the result
165 */
166 private function readField( $name, $metafield=null ) {
167 $this->debug ( "Read field $metafield" );
168 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
169 return;
170 }
171 $keepReading = $this->reader->read();
172 while( $keepReading ) {
173 if( $this->reader->localName == $name && $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
174 break;
175 } elseif( $this->reader->nodeType == XmlReader::TEXT ){
176 $this->metadata[$metafield] = trim( $this->reader->value );
177 }
178 $keepReading = $this->reader->read();
179 }
180 }
181
182 /**
183 * Read an XML snippet from an element
184 *
185 * @param String $metafield that we will fill with the result
186 */
187 private function readXml( $metafield=null ) {
188 $this->debug ( "Read top level metadata" );
189 if( !$metafield || $this->reader->nodeType != XmlReader::ELEMENT ) {
190 return;
191 }
192 // TODO: find and store type of xml snippet. metadata['metadataType'] = "rdf"
193 if( method_exists( $this->reader, 'readInnerXML' ) ) {
194 $this->metadata[$metafield] = trim( $this->reader->readInnerXML() );
195 } else {
196 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)." );
197 }
198 $this->reader->next();
199 }
200
201 /**
202 * Filter all children, looking for animate elements
203 *
204 * @param String $name of the element that we are reading from
205 */
206 private function animateFilter( $name ) {
207 $this->debug ( "animate filter for tag $name" );
208 if( $this->reader->nodeType != XmlReader::ELEMENT ) {
209 return;
210 }
211 if ( $this->reader->isEmptyElement ) {
212 return;
213 }
214 $exitDepth = $this->reader->depth;
215 $keepReading = $this->reader->read();
216 while( $keepReading ) {
217 if( $this->reader->localName == $name && $this->reader->depth <= $exitDepth
218 && $this->reader->nodeType == XmlReader::END_ELEMENT ) {
219 break;
220 } elseif ( $this->reader->namespaceURI == self::NS_SVG && $this->reader->nodeType == XmlReader::ELEMENT ) {
221 switch( $this->reader->localName ) {
222 case 'animate':
223 case 'set':
224 case 'animateMotion':
225 case 'animateColor':
226 case 'animateTransform':
227 $this->debug( "HOUSTON WE HAVE ANIMATION" );
228 $this->metadata['animated'] = true;
229 break;
230 }
231 }
232 $keepReading = $this->reader->read();
233 }
234 }
235
236 private function throwXmlError( $err ) {
237 $this->debug( "FAILURE: $err" );
238 wfDebug( "SVGReader XML error: $err\n" );
239 }
240
241 private function debug( $data ) {
242 if( $this->mDebug ) {
243 wfDebug( "SVGReader: $data\n" );
244 }
245 }
246
247 private function warn( $data ) {
248 wfDebug( "SVGReader: $data\n" );
249 }
250
251 private function notice( $data ) {
252 wfDebug( "SVGReader WARN: $data\n" );
253 }
254
255 /**
256 * Parse the attributes of an SVG element
257 *
258 * The parser has to be in the start element of <svg>
259 */
260 private function handleSVGAttribs( ) {
261 $defaultWidth = self::DEFAULT_WIDTH;
262 $defaultHeight = self::DEFAULT_HEIGHT;
263 $aspect = 1.0;
264 $width = null;
265 $height = null;
266
267 if( $this->reader->getAttribute('viewBox') ) {
268 // min-x min-y width height
269 $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute('viewBox') ) );
270 if( count( $viewBox ) == 4 ) {
271 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
272 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
273 if( $viewWidth > 0 && $viewHeight > 0 ) {
274 $aspect = $viewWidth / $viewHeight;
275 $defaultHeight = $defaultWidth / $aspect;
276 }
277 }
278 }
279 if( $this->reader->getAttribute('width') ) {
280 $width = $this->scaleSVGUnit( $this->reader->getAttribute('width'), $defaultWidth );
281 }
282 if( $this->reader->getAttribute('height') ) {
283 $height = $this->scaleSVGUnit( $this->reader->getAttribute('height'), $defaultHeight );
284 }
285
286 if( !isset( $width ) && !isset( $height ) ) {
287 $width = $defaultWidth;
288 $height = $width / $aspect;
289 } elseif( isset( $width ) && !isset( $height ) ) {
290 $height = $width / $aspect;
291 } elseif( isset( $height ) && !isset( $width ) ) {
292 $width = $height * $aspect;
293 }
294
295 if( $width > 0 && $height > 0 ) {
296 $this->metadata['width'] = intval( round( $width ) );
297 $this->metadata['height'] = intval( round( $height ) );
298 }
299 }
300
301 /**
302 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
303 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
304 *
305 * @param $length String: CSS/SVG length.
306 * @param $viewportSize: Float optional scale for percentage units...
307 * @return float: length in pixels
308 */
309 static function scaleSVGUnit( $length, $viewportSize=512 ) {
310 static $unitLength = array(
311 'px' => 1.0,
312 'pt' => 1.25,
313 'pc' => 15.0,
314 'mm' => 3.543307,
315 'cm' => 35.43307,
316 'in' => 90.0,
317 'em' => 16.0, // fake it?
318 'ex' => 12.0, // fake it?
319 '' => 1.0, // "User units" pixels by default
320 );
321 $matches = array();
322 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
323 $length = floatval( $matches[1] );
324 $unit = $matches[2];
325 if( $unit == '%' ) {
326 return $length * 0.01 * $viewportSize;
327 } else {
328 return $length * $unitLength[$unit];
329 }
330 } else {
331 // Assume pixels
332 return floatval( $length );
333 }
334 }
335 }