Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / media / SVG.php
blob53abfef04acefb310c906f1d1426ad81b5cb7adb
1 <?php
2 /**
3 * Handler for SVG images.
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.
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.
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
20 * @file
21 * @ingroup Media
24 /**
25 * Handler for SVG images.
27 * @ingroup Media
29 class SvgHandler extends ImageHandler {
30 const SVG_METADATA_VERSION = 2;
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:..}}
36 private static $metaConversion = array(
37 'originalwidth' => 'ImageWidth',
38 'originalheight' => 'ImageLength',
39 'description' => 'ImageDescription',
40 'title' => 'ObjectName',
43 function isEnabled() {
44 global $wgSVGConverters, $wgSVGConverter;
45 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
46 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
48 return false;
49 } else {
50 return true;
54 function mustRender( $file ) {
55 return true;
58 function isVectorized( $file ) {
59 return true;
62 /**
63 * @param File $file
64 * @return bool
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'];
76 return false;
79 /**
80 * Which languages (systemLanguage attribute) is supported.
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.
88 * @param File $file
89 * @return array Array of language codes, or empty if no language switching supported.
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;
104 return $langList;
108 * What language to render file in if none selected.
110 * @param File $file
111 * @return string Language code.
113 public function getDefaultRenderLanguage( File $file ) {
114 return 'en';
118 * We do not support making animated svg thumbnails
119 * @param File $file
120 * @return bool
122 function canAnimateThumbnail( $file ) {
123 return false;
127 * @param File $image
128 * @param array $params
129 * @return bool
131 function normaliseParams( $image, &$params ) {
132 global $wgSVGMaxSize;
133 if ( !parent::normaliseParams( $image, $params ) ) {
134 return false;
136 # Don't make an image bigger than wgMaxSVGSize on the smaller side
137 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
138 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
139 $srcWidth = $image->getWidth( $params['page'] );
140 $srcHeight = $image->getHeight( $params['page'] );
141 $params['physicalWidth'] = $wgSVGMaxSize;
142 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
144 } else {
145 if ( $params['physicalHeight'] > $wgSVGMaxSize ) {
146 $srcWidth = $image->getWidth( $params['page'] );
147 $srcHeight = $image->getHeight( $params['page'] );
148 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
149 $params['physicalHeight'] = $wgSVGMaxSize;
153 return true;
157 * @param File $image
158 * @param string $dstPath
159 * @param string $dstUrl
160 * @param array $params
161 * @param int $flags
162 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
164 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
165 if ( !$this->normaliseParams( $image, $params ) ) {
166 return new TransformParameterError( $params );
168 $clientWidth = $params['width'];
169 $clientHeight = $params['height'];
170 $physicalWidth = $params['physicalWidth'];
171 $physicalHeight = $params['physicalHeight'];
172 $lang = isset( $params['lang'] ) ? $params['lang'] : $this->getDefaultRenderLanguage( $image );
174 if ( $flags & self::TRANSFORM_LATER ) {
175 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
178 $metadata = $this->unpackMetadata( $image->getMetadata() );
179 if ( isset( $metadata['error'] ) ) { // sanity check
180 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
182 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
185 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
186 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
187 wfMessage( 'thumbnail_dest_directory' )->text() );
190 $srcPath = $image->getLocalRefPath();
191 if ( $srcPath === false ) { // Failed to get local copy
192 wfDebugLog( 'thumbnail',
193 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
194 wfHostname(), $image->getName() ) );
196 return new MediaTransformError( 'thumbnail_error',
197 $params['width'], $params['height'],
198 wfMessage( 'filemissing' )->text()
202 // Make a temp dir with a symlink to the local copy in it.
203 // This plays well with rsvg-convert policy for external entities.
204 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
205 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
206 $lnPath = "$tmpDir/" . basename( $srcPath );
207 $ok = mkdir( $tmpDir, 0771 ) && symlink( $srcPath, $lnPath );
208 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
209 wfSuppressWarnings();
210 unlink( $lnPath );
211 rmdir( $tmpDir );
212 wfRestoreWarnings();
213 } );
214 if ( !$ok ) {
215 wfDebugLog( 'thumbnail',
216 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
217 wfHostname(), $lnPath, $srcPath ) );
218 return new MediaTransformError( 'thumbnail_error',
219 $params['width'], $params['height'],
220 wfMessage( 'thumbnail-temp-create' )->text()
224 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
225 if ( $status === true ) {
226 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
227 } else {
228 return $status; // MediaTransformError
233 * Transform an SVG file to PNG
234 * This function can be called outside of thumbnail contexts
235 * @param string $srcPath
236 * @param string $dstPath
237 * @param string $width
238 * @param string $height
239 * @param bool|string $lang Language code of the language to render the SVG in
240 * @throws MWException
241 * @return bool|MediaTransformError
243 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
244 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
245 $err = false;
246 $retval = '';
247 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
248 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
249 // This is a PHP callable
250 $func = $wgSVGConverters[$wgSVGConverter][0];
251 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
252 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
253 if ( !is_callable( $func ) ) {
254 throw new MWException( "$func is not callable" );
256 $err = call_user_func_array( $func, $args );
257 $retval = (bool)$err;
258 } else {
259 // External command
260 $cmd = str_replace(
261 array( '$path/', '$width', '$height', '$input', '$output' ),
262 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
263 intval( $width ),
264 intval( $height ),
265 wfEscapeShellArg( $srcPath ),
266 wfEscapeShellArg( $dstPath ) ),
267 $wgSVGConverters[$wgSVGConverter]
270 $env = array();
271 if ( $lang !== false ) {
272 $env['LANG'] = $lang;
275 wfDebug( __METHOD__ . ": $cmd\n" );
276 $err = wfShellExecWithStderr( $cmd, $retval, $env );
279 $removed = $this->removeBadFile( $dstPath, $retval );
280 if ( $retval != 0 || $removed ) {
281 $this->logErrorForExternalProcess( $retval, $err, $cmd );
282 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
285 return true;
288 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
289 $im = new Imagick( $srcPath );
290 $im->setImageFormat( 'png' );
291 $im->setBackgroundColor( 'transparent' );
292 $im->setImageDepth( 8 );
294 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
295 return 'Could not resize image';
297 if ( !$im->writeImage( $dstPath ) ) {
298 return "Could not write to $dstPath";
303 * @param File $file
304 * @param string $path Unused
305 * @param bool|array $metadata
306 * @return array
308 function getImageSize( $file, $path, $metadata = false ) {
309 if ( $metadata === false ) {
310 $metadata = $file->getMetaData();
312 $metadata = $this->unpackMetaData( $metadata );
314 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
315 return array( $metadata['width'], $metadata['height'], 'SVG',
316 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
317 } else { // error
318 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
322 function getThumbType( $ext, $mime, $params = null ) {
323 return array( 'png', 'image/png' );
327 * Subtitle for the image. Different from the base
328 * class so it can be denoted that SVG's have
329 * a "nominal" resolution, and not a fixed one,
330 * as well as so animation can be denoted.
332 * @param File $file
333 * @return string
335 function getLongDesc( $file ) {
336 global $wgLang;
338 $metadata = $this->unpackMetadata( $file->getMetadata() );
339 if ( isset( $metadata['error'] ) ) {
340 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
343 $size = $wgLang->formatSize( $file->getSize() );
345 if ( $this->isAnimatedImage( $file ) ) {
346 $msg = wfMessage( 'svg-long-desc-animated' );
347 } else {
348 $msg = wfMessage( 'svg-long-desc' );
351 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
353 return $msg->parse();
357 * @param File $file
358 * @param string $filename
359 * @return string Serialised metadata
361 function getMetadata( $file, $filename ) {
362 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
363 try {
364 $metadata += SVGMetadataExtractor::getMetadata( $filename );
365 } catch ( Exception $e ) { // @todo SVG specific exceptions
366 // File not found, broken, etc.
367 $metadata['error'] = array(
368 'message' => $e->getMessage(),
369 'code' => $e->getCode()
371 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
374 return serialize( $metadata );
377 function unpackMetadata( $metadata ) {
378 wfSuppressWarnings();
379 $unser = unserialize( $metadata );
380 wfRestoreWarnings();
381 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
382 return $unser;
383 } else {
384 return false;
388 function getMetadataType( $image ) {
389 return 'parsed-svg';
392 function isMetadataValid( $image, $metadata ) {
393 $meta = $this->unpackMetadata( $metadata );
394 if ( $meta === false ) {
395 return self::METADATA_BAD;
397 if ( !isset( $meta['originalWidth'] ) ) {
398 // Old but compatible
399 return self::METADATA_COMPATIBLE;
402 return self::METADATA_GOOD;
405 protected function visibleMetadataFields() {
406 $fields = array( 'objectname', 'imagedescription' );
408 return $fields;
412 * @param File $file
413 * @return array|bool
415 function formatMetadata( $file ) {
416 $result = array(
417 'visible' => array(),
418 'collapsed' => array()
420 $metadata = $file->getMetadata();
421 if ( !$metadata ) {
422 return false;
424 $metadata = $this->unpackMetadata( $metadata );
425 if ( !$metadata || isset( $metadata['error'] ) ) {
426 return false;
429 /* @todo Add a formatter
430 $format = new FormatSVG( $metadata );
431 $formatted = $format->getFormattedData();
434 // Sort fields into visible and collapsed
435 $visibleFields = $this->visibleMetadataFields();
437 $showMeta = false;
438 foreach ( $metadata as $name => $value ) {
439 $tag = strtolower( $name );
440 if ( isset( self::$metaConversion[$tag] ) ) {
441 $tag = strtolower( self::$metaConversion[$tag] );
442 } else {
443 // Do not output other metadata not in list
444 continue;
446 $showMeta = true;
447 self::addMeta( $result,
448 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
449 'exif',
450 $tag,
451 $value
455 return $showMeta ? $result : false;
459 * @param string $name Parameter name
460 * @param mixed $value Parameter value
461 * @return bool Validity
463 function validateParam( $name, $value ) {
464 if ( in_array( $name, array( 'width', 'height' ) ) ) {
465 // Reject negative heights, widths
466 return ( $value > 0 );
467 } elseif ( $name == 'lang' ) {
468 // Validate $code
469 if ( $value === '' || !Language::isValidBuiltinCode( $value ) ) {
470 wfDebug( "Invalid user language code\n" );
472 return false;
475 return true;
478 // Only lang, width and height are acceptable keys
479 return false;
483 * @param array $params Name=>value pairs of parameters
484 * @return string Filename to use
486 function makeParamString( $params ) {
487 $lang = '';
488 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
489 $params['lang'] = mb_strtolower( $params['lang'] );
490 $lang = "lang{$params['lang']}-";
492 if ( !isset( $params['width'] ) ) {
493 return false;
496 return "$lang{$params['width']}px";
499 function parseParamString( $str ) {
500 $m = false;
501 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
502 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
503 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
504 return array( 'width' => $m[1], 'lang' => 'en' );
505 } else {
506 return false;
510 function getParamMap() {
511 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
515 * @param array $params
516 * @return array
518 function getScriptParams( $params ) {
519 $scriptParams = array( 'width' => $params['width'] );
520 if ( isset( $params['lang'] ) ) {
521 $scriptParams['lang'] = $params['lang'];
524 return $scriptParams;
527 public function getCommonMetaArray( File $file ) {
528 $metadata = $file->getMetadata();
529 if ( !$metadata ) {
530 return array();
532 $metadata = $this->unpackMetadata( $metadata );
533 if ( !$metadata || isset( $metadata['error'] ) ) {
534 return array();
536 $stdMetadata = array();
537 foreach ( $metadata as $name => $value ) {
538 $tag = strtolower( $name );
539 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
540 // Skip these. In the exif metadata stuff, it is assumed these
541 // are measured in px, which is not the case here.
542 continue;
544 if ( isset( self::$metaConversion[$tag] ) ) {
545 $tag = self::$metaConversion[$tag];
546 $stdMetadata[$tag] = $value;
550 return $stdMetadata;