PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / media / SVG.php
blob1118598f88d6c187df1dda3a7ef03690ed74fafb
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 /** @noinspection PhpUnusedLocalVariableInspection */
209 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
210 MediaWiki\suppressWarnings();
211 unlink( $lnPath );
212 rmdir( $tmpDir );
213 MediaWiki\restoreWarnings();
214 } );
215 if ( !$ok ) {
216 wfDebugLog( 'thumbnail',
217 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
218 wfHostname(), $lnPath, $srcPath ) );
219 return new MediaTransformError( 'thumbnail_error',
220 $params['width'], $params['height'],
221 wfMessage( 'thumbnail-temp-create' )->text()
225 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
226 if ( $status === true ) {
227 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
228 } else {
229 return $status; // MediaTransformError
234 * Transform an SVG file to PNG
235 * This function can be called outside of thumbnail contexts
236 * @param string $srcPath
237 * @param string $dstPath
238 * @param string $width
239 * @param string $height
240 * @param bool|string $lang Language code of the language to render the SVG in
241 * @throws MWException
242 * @return bool|MediaTransformError
244 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
245 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
246 $err = false;
247 $retval = '';
248 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
249 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
250 // This is a PHP callable
251 $func = $wgSVGConverters[$wgSVGConverter][0];
252 $args = array_merge( array( $srcPath, $dstPath, $width, $height, $lang ),
253 array_slice( $wgSVGConverters[$wgSVGConverter], 1 ) );
254 if ( !is_callable( $func ) ) {
255 throw new MWException( "$func is not callable" );
257 $err = call_user_func_array( $func, $args );
258 $retval = (bool)$err;
259 } else {
260 // External command
261 $cmd = str_replace(
262 array( '$path/', '$width', '$height', '$input', '$output' ),
263 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
264 intval( $width ),
265 intval( $height ),
266 wfEscapeShellArg( $srcPath ),
267 wfEscapeShellArg( $dstPath ) ),
268 $wgSVGConverters[$wgSVGConverter]
271 $env = array();
272 if ( $lang !== false ) {
273 $env['LANG'] = $lang;
276 wfDebug( __METHOD__ . ": $cmd\n" );
277 $err = wfShellExecWithStderr( $cmd, $retval, $env );
280 $removed = $this->removeBadFile( $dstPath, $retval );
281 if ( $retval != 0 || $removed ) {
282 $this->logErrorForExternalProcess( $retval, $err, $cmd );
283 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
286 return true;
289 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
290 $im = new Imagick( $srcPath );
291 $im->setImageFormat( 'png' );
292 $im->setBackgroundColor( 'transparent' );
293 $im->setImageDepth( 8 );
295 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
296 return 'Could not resize image';
298 if ( !$im->writeImage( $dstPath ) ) {
299 return "Could not write to $dstPath";
304 * @param File $file
305 * @param string $path Unused
306 * @param bool|array $metadata
307 * @return array
309 function getImageSize( $file, $path, $metadata = false ) {
310 if ( $metadata === false ) {
311 $metadata = $file->getMetadata();
313 $metadata = $this->unpackMetadata( $metadata );
315 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
316 return array( $metadata['width'], $metadata['height'], 'SVG',
317 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" );
318 } else { // error
319 return array( 0, 0, 'SVG', "width=\"0\" height=\"0\"" );
323 function getThumbType( $ext, $mime, $params = null ) {
324 return array( 'png', 'image/png' );
328 * Subtitle for the image. Different from the base
329 * class so it can be denoted that SVG's have
330 * a "nominal" resolution, and not a fixed one,
331 * as well as so animation can be denoted.
333 * @param File $file
334 * @return string
336 function getLongDesc( $file ) {
337 global $wgLang;
339 $metadata = $this->unpackMetadata( $file->getMetadata() );
340 if ( isset( $metadata['error'] ) ) {
341 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
344 $size = $wgLang->formatSize( $file->getSize() );
346 if ( $this->isAnimatedImage( $file ) ) {
347 $msg = wfMessage( 'svg-long-desc-animated' );
348 } else {
349 $msg = wfMessage( 'svg-long-desc' );
352 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
354 return $msg->parse();
358 * @param File $file
359 * @param string $filename
360 * @return string Serialised metadata
362 function getMetadata( $file, $filename ) {
363 $metadata = array( 'version' => self::SVG_METADATA_VERSION );
364 try {
365 $metadata += SVGMetadataExtractor::getMetadata( $filename );
366 } catch ( Exception $e ) { // @todo SVG specific exceptions
367 // File not found, broken, etc.
368 $metadata['error'] = array(
369 'message' => $e->getMessage(),
370 'code' => $e->getCode()
372 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
375 return serialize( $metadata );
378 function unpackMetadata( $metadata ) {
379 MediaWiki\suppressWarnings();
380 $unser = unserialize( $metadata );
381 MediaWiki\restoreWarnings();
382 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
383 return $unser;
384 } else {
385 return false;
389 function getMetadataType( $image ) {
390 return 'parsed-svg';
393 function isMetadataValid( $image, $metadata ) {
394 $meta = $this->unpackMetadata( $metadata );
395 if ( $meta === false ) {
396 return self::METADATA_BAD;
398 if ( !isset( $meta['originalWidth'] ) ) {
399 // Old but compatible
400 return self::METADATA_COMPATIBLE;
403 return self::METADATA_GOOD;
406 protected function visibleMetadataFields() {
407 $fields = array( 'objectname', 'imagedescription' );
409 return $fields;
413 * @param File $file
414 * @param bool|IContextSource $context Context to use (optional)
415 * @return array|bool
417 function formatMetadata( $file, $context = false ) {
418 $result = array(
419 'visible' => array(),
420 'collapsed' => array()
422 $metadata = $file->getMetadata();
423 if ( !$metadata ) {
424 return false;
426 $metadata = $this->unpackMetadata( $metadata );
427 if ( !$metadata || isset( $metadata['error'] ) ) {
428 return false;
431 /* @todo Add a formatter
432 $format = new FormatSVG( $metadata );
433 $formatted = $format->getFormattedData();
436 // Sort fields into visible and collapsed
437 $visibleFields = $this->visibleMetadataFields();
439 $showMeta = false;
440 foreach ( $metadata as $name => $value ) {
441 $tag = strtolower( $name );
442 if ( isset( self::$metaConversion[$tag] ) ) {
443 $tag = strtolower( self::$metaConversion[$tag] );
444 } else {
445 // Do not output other metadata not in list
446 continue;
448 $showMeta = true;
449 self::addMeta( $result,
450 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
451 'exif',
452 $tag,
453 $value
457 return $showMeta ? $result : false;
461 * @param string $name Parameter name
462 * @param mixed $value Parameter value
463 * @return bool Validity
465 function validateParam( $name, $value ) {
466 if ( in_array( $name, array( 'width', 'height' ) ) ) {
467 // Reject negative heights, widths
468 return ( $value > 0 );
469 } elseif ( $name == 'lang' ) {
470 // Validate $code
471 if ( $value === '' || !Language::isValidBuiltinCode( $value ) ) {
472 wfDebug( "Invalid user language code\n" );
474 return false;
477 return true;
480 // Only lang, width and height are acceptable keys
481 return false;
485 * @param array $params Name=>value pairs of parameters
486 * @return string Filename to use
488 function makeParamString( $params ) {
489 $lang = '';
490 if ( isset( $params['lang'] ) && $params['lang'] !== 'en' ) {
491 $params['lang'] = strtolower( $params['lang'] );
492 $lang = "lang{$params['lang']}-";
494 if ( !isset( $params['width'] ) ) {
495 return false;
498 return "$lang{$params['width']}px";
501 function parseParamString( $str ) {
502 $m = false;
503 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/', $str, $m ) ) {
504 return array( 'width' => array_pop( $m ), 'lang' => $m[1] );
505 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
506 return array( 'width' => $m[1], 'lang' => 'en' );
507 } else {
508 return false;
512 function getParamMap() {
513 return array( 'img_lang' => 'lang', 'img_width' => 'width' );
517 * @param array $params
518 * @return array
520 function getScriptParams( $params ) {
521 $scriptParams = array( 'width' => $params['width'] );
522 if ( isset( $params['lang'] ) ) {
523 $scriptParams['lang'] = $params['lang'];
526 return $scriptParams;
529 public function getCommonMetaArray( File $file ) {
530 $metadata = $file->getMetadata();
531 if ( !$metadata ) {
532 return array();
534 $metadata = $this->unpackMetadata( $metadata );
535 if ( !$metadata || isset( $metadata['error'] ) ) {
536 return array();
538 $stdMetadata = array();
539 foreach ( $metadata as $name => $value ) {
540 $tag = strtolower( $name );
541 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
542 // Skip these. In the exif metadata stuff, it is assumed these
543 // are measured in px, which is not the case here.
544 continue;
546 if ( isset( self::$metaConversion[$tag] ) ) {
547 $tag = self::$metaConversion[$tag];
548 $stdMetadata[$tag] = $value;
552 return $stdMetadata;