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