6864de467545041532fea362fe97dfd080a0b7e1
[lhc/web/wiklou.git] / includes / media / SVG.php
1 <?php
2 /**
3 * Handler for SVG images.
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 */
23
24 /**
25 * Handler for SVG images.
26 *
27 * @ingroup Media
28 */
29 class SvgHandler extends ImageHandler {
30 const SVG_METADATA_VERSION = 2;
31
32 /** @var array A list of metadata tags that can be converted
33 * to the commonly used exif tags. This allows messages
34 * to be reused, and consistent tag names for {{#formatmetadata:..}}
35 */
36 private static $metaConversion = array(
37 'originalwidth' => 'ImageWidth',
38 'originalheight' => 'ImageLength',
39 'description' => 'ImageDescription',
40 'title' => 'ObjectName',
41 );
42
43 function isEnabled() {
44 global $wgSVGConverters, $wgSVGConverter;
45 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
46 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
47
48 return false;
49 } else {
50 return true;
51 }
52 }
53
54 function mustRender( $file ) {
55 return true;
56 }
57
58 function isVectorized( $file ) {
59 return true;
60 }
61
62 /**
63 * @param File $file
64 * @return bool
65 */
66 function isAnimatedImage( $file ) {
67 # @todo Detect animated SVGs
68 $metadata = $file->getMetadata();
69 if ( $metadata ) {
70 $metadata = $this->unpackMetadata( $metadata );
71 if ( isset( $metadata['animated'] ) ) {
72 return $metadata['animated'];
73 }
74 }
75
76 return false;
77 }
78
79 /**
80 * We do not support making animated svg thumbnails
81 */
82 function canAnimateThumb( $file ) {
83 return false;
84 }
85
86 /**
87 * @param File $image
88 * @param array $params
89 * @return bool
90 */
91 function normaliseParams( $image, &$params ) {
92 global $wgSVGMaxSize;
93 if ( !parent::normaliseParams( $image, $params ) ) {
94 return false;
95 }
96 # Don't make an image bigger than wgMaxSVGSize on the smaller side
97 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
98 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
99 $srcWidth = $image->getWidth( $params['page'] );
100 $srcHeight = $image->getHeight( $params['page'] );
101 $params['physicalWidth'] = $wgSVGMaxSize;
102 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
103 }
104 } else {
105 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
106 $srcWidth = $image->getWidth( $params['page'] );
107 $srcHeight = $image->getHeight( $params['page'] );
108 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
109 $params['physicalHeight'] = $wgSVGMaxSize;
110 }
111 }
112
113 return true;
114 }
115
116 /**
117 * @param File $image
118 * @param string $dstPath
119 * @param string $dstUrl
120 * @param array $params
121 * @param int $flags
122 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
123 */
124 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
125 if ( !$this->normaliseParams( $image, $params ) ) {
126 return new TransformParameterError( $params );
127 }
128 $clientWidth = $params['width'];
129 $clientHeight = $params['height'];
130 $physicalWidth = $params['physicalWidth'];
131 $physicalHeight = $params['physicalHeight'];
132 $lang = isset( $params['lang'] ) ? $params['lang'] : 'en';
133
134 if ( $flags & self::TRANSFORM_LATER ) {
135 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
136 }
137
138 $metadata = $this->unpackMetadata( $image->getMetadata() );
139 if ( isset( $metadata['error'] ) ) { // sanity check
140 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
141
142 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
143 }
144
145 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
146 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
147 wfMessage( 'thumbnail_dest_directory' )->text() );
148 }
149
150 $srcPath = $image->getLocalRefPath();
151 $status = $this->rasterize( $srcPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
152 if ( $status === true ) {
153 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
154 } else {
155 return $status; // MediaTransformError
156 }
157 }
158
159 /**
160 * Transform an SVG file to PNG
161 * This function can be called outside of thumbnail contexts
162 * @param string $srcPath
163 * @param string $dstPath
164 * @param string $width
165 * @param string $height
166 * @param bool|string $lang Language code of the language to render the SVG in
167 * @throws MWException
168 * @return bool|MediaTransformError
169 */
170 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
171 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
172 $err = false;
173 $retval = '';
174 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
175 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
176 // This is a PHP callable
177 $func = $wgSVGConverters[$wgSVGConverter][0];
178 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
179 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
180 if ( !is_callable( $func ) ) {
181 throw new MWException( "$func is not callable" );
182 }
183 $err = call_user_func_array( $func, $args );
184 $retval = (bool)$err;
185 } else {
186 // External command
187 $cmd = str_replace(
188 array( '$path/', '$width', '$height', '$input', '$output' ),
189 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
190 intval( $width ),
191 intval( $height ),
192 wfEscapeShellArg( $srcPath ),
193 wfEscapeShellArg( $dstPath ) ),
194 $wgSVGConverters[$wgSVGConverter]
195 );
196
197 $env = array();
198 if ( $lang !== false ) {
199 $env['LANG'] = $lang;
200 }
201
202 wfProfileIn( 'rsvg' );
203 wfDebug( __METHOD__ . ": $cmd\n" );
204 $err = wfShellExecWithStderr( $cmd, $retval, $env );
205 wfProfileOut( 'rsvg' );
206 }
207 }
208 $removed = $this->removeBadFile( $dstPath, $retval );
209 if ( $retval != 0 || $removed ) {
210 $this->logErrorForExternalProcess( $retval, $err, $cmd );
211 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
212 }
213
214 return true;
215 }
216
217 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
218 $im = new Imagick( $srcPath );
219 $im->setImageFormat( 'png' );
220 $im->setBackgroundColor( 'transparent' );
221 $im->setImageDepth( 8 );
222
223 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
224 return 'Could not resize image';
225 }
226 if ( !$im->writeImage( $dstPath ) ) {
227 return "Could not write to $dstPath";
228 }
229 }
230
231 /**
232 * @param File $file
233 * @param string $path Unused
234 * @param bool|array $metadata
235 * @return array
236 */
237 function getImageSize( $file, $path, $metadata = false ) {
238 if ( $metadata === false ) {
239 $metadata = $file->getMetaData();
240 }
241 $metadata = $this->unpackMetaData( $metadata );
242
243 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
244 return array( $metadata['width'], $metadata['height'], 'SVG',
245 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
246 } else { // error
247 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
248 }
249 }
250
251 function getThumbType( $ext, $mime, $params = null ) {
252 return array( 'png', 'image/png' );
253 }
254
255 /**
256 * Subtitle for the image. Different from the base
257 * class so it can be denoted that SVG's have
258 * a "nominal" resolution, and not a fixed one,
259 * as well as so animation can be denoted.
260 *
261 * @param File $file
262 * @return string
263 */
264 function getLongDesc( $file ) {
265 global $wgLang;
266
267 $metadata = $this->unpackMetadata( $file->getMetadata() );
268 if ( isset( $metadata['error'] ) ) {
269 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
270 }
271
272 $size = $wgLang->formatSize( $file->getSize() );
273
274 if ( $this->isAnimatedImage( $file ) ) {
275 $msg = wfMessage( 'svg-long-desc-animated' );
276 } else {
277 $msg = wfMessage( 'svg-long-desc' );
278 }
279
280 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
281
282 return $msg->parse();
283 }
284
285 /**
286 * @param File $file
287 * @param string $filename
288 * @return string Serialised metadata
289 */
290 function getMetadata( $file, $filename ) {
291 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
292 try {
293 $metadata += SVGMetadataExtractor::getMetadata( $filename );
294 } catch ( MWException $e ) { // @todo SVG specific exceptions
295 // File not found, broken, etc.
296 $metadata['error'] = array(
297 'message' => $e->getMessage(),
298 'code' => $e->getCode()
299 );
300 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
301 }
302
303 return serialize( $metadata );
304 }
305
306 function unpackMetadata( $metadata ) {
307 wfSuppressWarnings();
308 $unser = unserialize( $metadata );
309 wfRestoreWarnings();
310 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
311 return $unser;
312 } else {
313 return false;
314 }
315 }
316
317 function getMetadataType( $image ) {
318 return 'parsed-svg';
319 }
320
321 function isMetadataValid( $image, $metadata ) {
322 $meta = $this->unpackMetadata( $metadata );
323 if ( $meta === false ) {
324 return self::METADATA_BAD;
325 }
326 if ( !isset( $meta['originalWidth'] ) ) {
327 // Old but compatible
328 return self::METADATA_COMPATIBLE;
329 }
330
331 return self::METADATA_GOOD;
332 }
333
334 function visibleMetadataFields() {
335 $fields = array( 'objectname', 'imagedescription' );
336
337 return $fields;
338 }
339
340 /**
341 * @param File $file
342 * @return array|bool
343 */
344 function formatMetadata( $file ) {
345 $result = array(
346 'visible' => array(),
347 'collapsed' => array()
348 );
349 $metadata = $file->getMetadata();
350 if ( !$metadata ) {
351 return false;
352 }
353 $metadata = $this->unpackMetadata( $metadata );
354 if ( !$metadata || isset( $metadata['error'] ) ) {
355 return false;
356 }
357
358 /* @todo Add a formatter
359 $format = new FormatSVG( $metadata );
360 $formatted = $format->getFormattedData();
361 */
362
363 // Sort fields into visible and collapsed
364 $visibleFields = $this->visibleMetadataFields();
365
366 $showMeta = false;
367 foreach ( $metadata as $name => $value ) {
368 $tag = strtolower( $name );
369 if ( isset( self::$metaConversion[$tag] ) ) {
370 $tag = strtolower( self::$metaConversion[$tag] );
371 } else {
372 // Do not output other metadata not in list
373 continue;
374 }
375 $showMeta = true;
376 self::addMeta( $result,
377 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
378 'exif',
379 $tag,
380 $value
381 );
382 }
383
384 return $showMeta ? $result : false;
385 }
386
387 /**
388 * @param string $name Parameter name
389 * @param mixed $value Parameter value
390 * @return bool Validity
391 */
392 function validateParam( $name, $value ) {
393 if ( in_array( $name, array( 'width', 'height' ) ) ) {
394 // Reject negative heights, widths
395 return ( $value > 0 );
396 } elseif ( $name == 'lang' ) {
397 // Validate $code
398 if ( !Language::isValidBuiltinCode( $value ) ) {
399 wfDebug( "Invalid user language code\n" );
400
401 return false;
402 }
403
404 return true;
405 }
406
407 // Only lang, width and height are acceptable keys
408 return false;
409 }
410
411 /**
412 * @param array $params name=>value pairs of parameters
413 * @return string Filename to use
414 */
415 function makeParamString( $params ) {
416 $lang = '';
417 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
418 $params['lang'] = mb_strtolower( $params['lang'] );
419 $lang = "lang{$params['lang']}-";
420 }
421 if ( !isset( $params['width'] ) ) {
422 return false;
423 }
424
425 return "$lang{$params['width']}px";
426 }
427
428 function parseParamString( $str ) {
429 $m = false;
430 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
431 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
432 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
433 return array( 'width' => $m[1], 'lang' => 'en' );
434 } else {
435 return false;
436 }
437 }
438
439 function getParamMap() {
440 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
441 }
442
443 /**
444 * @param array $params
445 * @return array
446 */
447 function getScriptParams( $params ) {
448 return array(
449 'width' => $params['width'],
450 'lang' => $params['lang'],
451 );
452 }
453
454 public function getCommonMetaArray( File $file ) {
455 $metadata = $file->getMetadata();
456 if ( !$metadata ) {
457 return array();
458 }
459 $metadata = $this->unpackMetadata( $metadata );
460 if ( !$metadata || isset( $metadata['error'] ) ) {
461 return array();
462 }
463 $stdMetadata = array();
464 foreach ( $metadata as $name => $value ) {
465 $tag = strtolower( $name );
466 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
467 // Skip these. In the exif metadata stuff, it is assumed these
468 // are measured in px, which is not the case here.
469 continue;
470 }
471 if ( isset( self::$metaConversion[$tag] ) ) {
472 $tag = self::$metaConversion[$tag];
473 $stdMetadata[$tag] = $value;
474 }
475 }
476
477 return $stdMetadata;
478 }
479 }