Reverting r82307 (bug 27465) as initial step to recommitting a cleaner fix.
[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->reader->name != '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 ( $tag == 'svg' && $type == XmlReader::END_ELEMENT && $this->reader->depth <= $exitDepth ) {
120 break;
121 } elseif ( $tag == 'title' ) {
122 $this->readField( $tag, 'title' );
123 } elseif ( $tag == 'desc' ) {
124 $this->readField( $tag, 'description' );
125 } elseif ( $tag == '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 'set':
205 case 'animateMotion':
206 case 'animateColor':
207 case 'animateTransform':
208 $this->debug( "HOUSTON WE HAVE ANIMATION" );
209 $this->metadata['animated'] = true;
210 break;
211 }
212 }
213 $keepReading = $this->reader->read();
214 }
215 }
216
217 private function throwXmlError( $err ) {
218 $this->debug( "FAILURE: $err" );
219 wfDebug( "SVGReader XML error: $err\n" );
220 }
221
222 private function debug( $data ) {
223 if( $this->mDebug ) {
224 wfDebug( "SVGReader: $data\n" );
225 }
226 }
227
228 private function warn( $data ) {
229 wfDebug( "SVGReader: $data\n" );
230 }
231
232 private function notice( $data ) {
233 wfDebug( "SVGReader WARN: $data\n" );
234 }
235
236 /**
237 * Parse the attributes of an SVG element
238 *
239 * The parser has to be in the start element of <svg>
240 */
241 private function handleSVGAttribs( ) {
242 $defaultWidth = self::DEFAULT_WIDTH;
243 $defaultHeight = self::DEFAULT_HEIGHT;
244 $aspect = 1.0;
245 $width = null;
246 $height = null;
247
248 if( $this->reader->getAttribute('viewBox') ) {
249 // min-x min-y width height
250 $viewBox = preg_split( '/\s+/', trim( $this->reader->getAttribute('viewBox') ) );
251 if( count( $viewBox ) == 4 ) {
252 $viewWidth = $this->scaleSVGUnit( $viewBox[2] );
253 $viewHeight = $this->scaleSVGUnit( $viewBox[3] );
254 if( $viewWidth > 0 && $viewHeight > 0 ) {
255 $aspect = $viewWidth / $viewHeight;
256 $defaultHeight = $defaultWidth / $aspect;
257 }
258 }
259 }
260 if( $this->reader->getAttribute('width') ) {
261 $width = $this->scaleSVGUnit( $this->reader->getAttribute('width'), $defaultWidth );
262 }
263 if( $this->reader->getAttribute('height') ) {
264 $height = $this->scaleSVGUnit( $this->reader->getAttribute('height'), $defaultHeight );
265 }
266
267 if( !isset( $width ) && !isset( $height ) ) {
268 $width = $defaultWidth;
269 $height = $width / $aspect;
270 } elseif( isset( $width ) && !isset( $height ) ) {
271 $height = $width / $aspect;
272 } elseif( isset( $height ) && !isset( $width ) ) {
273 $width = $height * $aspect;
274 }
275
276 if( $width > 0 && $height > 0 ) {
277 $this->metadata['width'] = intval( round( $width ) );
278 $this->metadata['height'] = intval( round( $height ) );
279 }
280 }
281
282 /**
283 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
284 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
285 *
286 * @param $length String: CSS/SVG length.
287 * @param $viewportSize: Float optional scale for percentage units...
288 * @return float: length in pixels
289 */
290 static function scaleSVGUnit( $length, $viewportSize=512 ) {
291 static $unitLength = array(
292 'px' => 1.0,
293 'pt' => 1.25,
294 'pc' => 15.0,
295 'mm' => 3.543307,
296 'cm' => 35.43307,
297 'in' => 90.0,
298 'em' => 16.0, // fake it?
299 'ex' => 12.0, // fake it?
300 '' => 1.0, // "User units" pixels by default
301 );
302 $matches = array();
303 if( preg_match( '/^\s*(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)\s*$/', $length, $matches ) ) {
304 $length = floatval( $matches[1] );
305 $unit = $matches[2];
306 if( $unit == '%' ) {
307 return $length * 0.01 * $viewportSize;
308 } else {
309 return $length * $unitLength[$unit];
310 }
311 } else {
312 // Assume pixels
313 return floatval( $length );
314 }
315 }
316 }