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