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