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