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