Merge "Fix title handling in User::getCanonicalName"
[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 * Which languages (systemLanguage attribute) is supported.
81 *
82 * @note This list is not guaranteed to be exhaustive.
83 * To avoid OOM errors, we only look at first bit of a file.
84 * Thus all languages on this list are present in the file,
85 * but its possible for the file to have a language not on
86 * this list.
87 *
88 * @param File $file
89 * @return array Array of language codes, or empty if no language switching supported.
90 */
91 public function getAvailableLanguages( File $file ) {
92 $metadata = $file->getMetadata();
93 $langList = array();
94 if ( $metadata ) {
95 $metadata = $this->unpackMetadata( $metadata );
96 if ( isset( $metadata['translations'] ) ) {
97 foreach ( $metadata['translations'] as $lang => $langType ) {
98 if ( $langType === SvgReader::LANG_FULL_MATCH ) {
99 $langList[] = $lang;
100 }
101 }
102 }
103 }
104 return $langList;
105 }
106
107 /**
108 * What language to render file in if none selected.
109 *
110 * @return string Language code.
111 */
112 public function getDefaultRenderLanguage( File $file ) {
113 return 'en';
114 }
115
116 /**
117 * We do not support making animated svg thumbnails
118 */
119 function canAnimateThumbnail( $file ) {
120 return false;
121 }
122
123 /**
124 * @param File $image
125 * @param array $params
126 * @return bool
127 */
128 function normaliseParams( $image, &$params ) {
129 global $wgSVGMaxSize;
130 if ( !parent::normaliseParams( $image, $params ) ) {
131 return false;
132 }
133 # Don't make an image bigger than wgMaxSVGSize on the smaller side
134 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
135 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
136 $srcWidth = $image->getWidth( $params['page'] );
137 $srcHeight = $image->getHeight( $params['page'] );
138 $params['physicalWidth'] = $wgSVGMaxSize;
139 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
140 }
141 } else {
142 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
143 $srcWidth = $image->getWidth( $params['page'] );
144 $srcHeight = $image->getHeight( $params['page'] );
145 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
146 $params['physicalHeight'] = $wgSVGMaxSize;
147 }
148 }
149
150 return true;
151 }
152
153 /**
154 * @param File $image
155 * @param string $dstPath
156 * @param string $dstUrl
157 * @param array $params
158 * @param int $flags
159 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
160 */
161 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
162 if ( !$this->normaliseParams( $image, $params ) ) {
163 return new TransformParameterError( $params );
164 }
165 $clientWidth = $params['width'];
166 $clientHeight = $params['height'];
167 $physicalWidth = $params['physicalWidth'];
168 $physicalHeight = $params['physicalHeight'];
169 $lang = isset( $params['lang'] ) ? $params['lang'] : $this->getDefaultRenderLanguage( $image );
170
171 if ( $flags & self::TRANSFORM_LATER ) {
172 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
173 }
174
175 $metadata = $this->unpackMetadata( $image->getMetadata() );
176 if ( isset( $metadata['error'] ) ) { // sanity check
177 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
178
179 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
180 }
181
182 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
183 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
184 wfMessage( 'thumbnail_dest_directory' )->text() );
185 }
186
187 $srcPath = $image->getLocalRefPath();
188 if ( $srcPath === false ) { // Failed to get local copy
189 wfDebugLog( 'thumbnail',
190 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
191 wfHostname(), $image->getName() ) );
192
193 return new MediaTransformError( 'thumbnail_error',
194 $params['width'], $params['height'],
195 wfMessage( 'filemissing' )->text()
196 );
197 }
198
199 // Make a temp dir with a symlink to the local copy in it.
200 // This plays well with rsvg-convert policy for external entities.
201 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
202 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
203 $lnPath = "$tmpDir/" . basename( $srcPath );
204 $ok = mkdir( $tmpDir, 0771 ) && symlink( $srcPath, $lnPath );
205 $cleaner = new ScopedCallback( function() use ( $tmpDir, $lnPath ) {
206 wfSuppressWarnings();
207 unlink( $lnPath );
208 rmdir( $tmpDir );
209 wfRestoreWarnings();
210 } );
211 if ( !$ok ) {
212 wfDebugLog( 'thumbnail',
213 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
214 wfHostname(), $lnPath, $srcPath ) );
215 return new MediaTransformError( 'thumbnail_error',
216 $params['width'], $params['height'],
217 wfMessage( 'thumbnail-temp-create' )->text()
218 );
219 }
220
221 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
222 if ( $status === true ) {
223 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
224 } else {
225 return $status; // MediaTransformError
226 }
227 }
228
229 /**
230 * Transform an SVG file to PNG
231 * This function can be called outside of thumbnail contexts
232 * @param string $srcPath
233 * @param string $dstPath
234 * @param string $width
235 * @param string $height
236 * @param bool|string $lang Language code of the language to render the SVG in
237 * @throws MWException
238 * @return bool|MediaTransformError
239 */
240 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
241 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
242 $err = false;
243 $retval = '';
244 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
245 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
246 // This is a PHP callable
247 $func = $wgSVGConverters[$wgSVGConverter][0];
248 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
249 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
250 if ( !is_callable( $func ) ) {
251 throw new MWException( "$func is not callable" );
252 }
253 $err = call_user_func_array( $func, $args );
254 $retval = (bool)$err;
255 } else {
256 // External command
257 $cmd = str_replace(
258 array( '$path/', '$width', '$height', '$input', '$output' ),
259 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
260 intval( $width ),
261 intval( $height ),
262 wfEscapeShellArg( $srcPath ),
263 wfEscapeShellArg( $dstPath ) ),
264 $wgSVGConverters[$wgSVGConverter]
265 );
266
267 $env = array();
268 if ( $lang !== false ) {
269 $env['LANG'] = $lang;
270 }
271
272 wfProfileIn( 'rsvg' );
273 wfDebug( __METHOD__ . ": $cmd\n" );
274 $err = wfShellExecWithStderr( $cmd, $retval, $env );
275 wfProfileOut( 'rsvg' );
276 }
277 }
278 $removed = $this->removeBadFile( $dstPath, $retval );
279 if ( $retval != 0 || $removed ) {
280 $this->logErrorForExternalProcess( $retval, $err, $cmd );
281 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
282 }
283
284 return true;
285 }
286
287 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
288 $im = new Imagick( $srcPath );
289 $im->setImageFormat( 'png' );
290 $im->setBackgroundColor( 'transparent' );
291 $im->setImageDepth( 8 );
292
293 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
294 return 'Could not resize image';
295 }
296 if ( !$im->writeImage( $dstPath ) ) {
297 return "Could not write to $dstPath";
298 }
299 }
300
301 /**
302 * @param File $file
303 * @param string $path Unused
304 * @param bool|array $metadata
305 * @return array
306 */
307 function getImageSize( $file, $path, $metadata = false ) {
308 if ( $metadata === false ) {
309 $metadata = $file->getMetaData();
310 }
311 $metadata = $this->unpackMetaData( $metadata );
312
313 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
314 return array( $metadata['width'], $metadata['height'], 'SVG',
315 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
316 } else { // error
317 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
318 }
319 }
320
321 function getThumbType( $ext, $mime, $params = null ) {
322 return array( 'png', 'image/png' );
323 }
324
325 /**
326 * Subtitle for the image. Different from the base
327 * class so it can be denoted that SVG's have
328 * a "nominal" resolution, and not a fixed one,
329 * as well as so animation can be denoted.
330 *
331 * @param File $file
332 * @return string
333 */
334 function getLongDesc( $file ) {
335 global $wgLang;
336
337 $metadata = $this->unpackMetadata( $file->getMetadata() );
338 if ( isset( $metadata['error'] ) ) {
339 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
340 }
341
342 $size = $wgLang->formatSize( $file->getSize() );
343
344 if ( $this->isAnimatedImage( $file ) ) {
345 $msg = wfMessage( 'svg-long-desc-animated' );
346 } else {
347 $msg = wfMessage( 'svg-long-desc' );
348 }
349
350 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
351
352 return $msg->parse();
353 }
354
355 /**
356 * @param File $file
357 * @param string $filename
358 * @return string Serialised metadata
359 */
360 function getMetadata( $file, $filename ) {
361 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
362 try {
363 $metadata += SVGMetadataExtractor::getMetadata( $filename );
364 } catch ( MWException $e ) { // @todo SVG specific exceptions
365 // File not found, broken, etc.
366 $metadata['error'] = array(
367 'message' => $e->getMessage(),
368 'code' => $e->getCode()
369 );
370 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
371 }
372
373 return serialize( $metadata );
374 }
375
376 function unpackMetadata( $metadata ) {
377 wfSuppressWarnings();
378 $unser = unserialize( $metadata );
379 wfRestoreWarnings();
380 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
381 return $unser;
382 } else {
383 return false;
384 }
385 }
386
387 function getMetadataType( $image ) {
388 return 'parsed-svg';
389 }
390
391 function isMetadataValid( $image, $metadata ) {
392 $meta = $this->unpackMetadata( $metadata );
393 if ( $meta === false ) {
394 return self::METADATA_BAD;
395 }
396 if ( !isset( $meta['originalWidth'] ) ) {
397 // Old but compatible
398 return self::METADATA_COMPATIBLE;
399 }
400
401 return self::METADATA_GOOD;
402 }
403
404 protected function visibleMetadataFields() {
405 $fields = array( 'objectname', 'imagedescription' );
406
407 return $fields;
408 }
409
410 /**
411 * @param File $file
412 * @return array|bool
413 */
414 function formatMetadata( $file ) {
415 $result = array(
416 'visible' => array(),
417 'collapsed' => array()
418 );
419 $metadata = $file->getMetadata();
420 if ( !$metadata ) {
421 return false;
422 }
423 $metadata = $this->unpackMetadata( $metadata );
424 if ( !$metadata || isset( $metadata['error'] ) ) {
425 return false;
426 }
427
428 /* @todo Add a formatter
429 $format = new FormatSVG( $metadata );
430 $formatted = $format->getFormattedData();
431 */
432
433 // Sort fields into visible and collapsed
434 $visibleFields = $this->visibleMetadataFields();
435
436 $showMeta = false;
437 foreach ( $metadata as $name => $value ) {
438 $tag = strtolower( $name );
439 if ( isset( self::$metaConversion[$tag] ) ) {
440 $tag = strtolower( self::$metaConversion[$tag] );
441 } else {
442 // Do not output other metadata not in list
443 continue;
444 }
445 $showMeta = true;
446 self::addMeta( $result,
447 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
448 'exif',
449 $tag,
450 $value
451 );
452 }
453
454 return $showMeta ? $result : false;
455 }
456
457 /**
458 * @param string $name Parameter name
459 * @param mixed $value Parameter value
460 * @return bool Validity
461 */
462 function validateParam( $name, $value ) {
463 if ( in_array( $name, array( 'width', 'height' ) ) ) {
464 // Reject negative heights, widths
465 return ( $value > 0 );
466 } elseif ( $name == 'lang' ) {
467 // Validate $code
468 if ( $value === '' || !Language::isValidBuiltinCode( $value ) ) {
469 wfDebug( "Invalid user language code\n" );
470
471 return false;
472 }
473
474 return true;
475 }
476
477 // Only lang, width and height are acceptable keys
478 return false;
479 }
480
481 /**
482 * @param array $params Name=>value pairs of parameters
483 * @return string Filename to use
484 */
485 function makeParamString( $params ) {
486 $lang = '';
487 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
488 $params['lang'] = mb_strtolower( $params['lang'] );
489 $lang = "lang{$params['lang']}-";
490 }
491 if ( !isset( $params['width'] ) ) {
492 return false;
493 }
494
495 return "$lang{$params['width']}px";
496 }
497
498 function parseParamString( $str ) {
499 $m = false;
500 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
501 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
502 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
503 return array( 'width' => $m[1], 'lang' => 'en' );
504 } else {
505 return false;
506 }
507 }
508
509 function getParamMap() {
510 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
511 }
512
513 /**
514 * @param array $params
515 * @return array
516 */
517 function getScriptParams( $params ) {
518 $scriptParams = array( 'width' => $params['width'] );
519 if ( isset( $params['lang'] ) ) {
520 $scriptParams['lang'] = $params['lang'];
521 }
522
523 return $scriptParams;
524 }
525
526 public function getCommonMetaArray( File $file ) {
527 $metadata = $file->getMetadata();
528 if ( !$metadata ) {
529 return array();
530 }
531 $metadata = $this->unpackMetadata( $metadata );
532 if ( !$metadata || isset( $metadata['error'] ) ) {
533 return array();
534 }
535 $stdMetadata = array();
536 foreach ( $metadata as $name => $value ) {
537 $tag = strtolower( $name );
538 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
539 // Skip these. In the exif metadata stuff, it is assumed these
540 // are measured in px, which is not the case here.
541 continue;
542 }
543 if ( isset( self::$metaConversion[$tag] ) ) {
544 $tag = self::$metaConversion[$tag];
545 $stdMetadata[$tag] = $value;
546 }
547 }
548
549 return $stdMetadata;
550 }
551 }