Collapse some nested if statements
[lhc/web/wiklou.git] / includes / media / SvgHandler.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 use Wikimedia\ScopedCallback;
24
25 /**
26 * Handler for SVG images.
27 *
28 * @ingroup Media
29 */
30 class SvgHandler extends ImageHandler {
31 const SVG_METADATA_VERSION = 2;
32
33 /** @var array 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 = [
38 'originalwidth' => 'ImageWidth',
39 'originalheight' => 'ImageLength',
40 'description' => 'ImageDescription',
41 'title' => 'ObjectName',
42 ];
43
44 public function isEnabled() {
45 global $wgSVGConverters, $wgSVGConverter;
46 if ( !isset( $wgSVGConverters[$wgSVGConverter] ) ) {
47 wfDebug( "\$wgSVGConverter is invalid, disabling SVG rendering.\n" );
48
49 return false;
50 } else {
51 return true;
52 }
53 }
54
55 public function mustRender( $file ) {
56 return true;
57 }
58
59 function isVectorized( $file ) {
60 return true;
61 }
62
63 /**
64 * @param File $file
65 * @return bool
66 */
67 function isAnimatedImage( $file ) {
68 # @todo Detect animated SVGs
69 $metadata = $file->getMetadata();
70 if ( $metadata ) {
71 $metadata = $this->unpackMetadata( $metadata );
72 if ( isset( $metadata['animated'] ) ) {
73 return $metadata['animated'];
74 }
75 }
76
77 return false;
78 }
79
80 /**
81 * Which languages (systemLanguage attribute) is supported.
82 *
83 * @note This list is not guaranteed to be exhaustive.
84 * To avoid OOM errors, we only look at first bit of a file.
85 * Thus all languages on this list are present in the file,
86 * but its possible for the file to have a language not on
87 * this list.
88 *
89 * @param File $file
90 * @return array Array of language codes, or empty if no language switching supported.
91 */
92 public function getAvailableLanguages( File $file ) {
93 $metadata = $file->getMetadata();
94 $langList = [];
95 if ( $metadata ) {
96 $metadata = $this->unpackMetadata( $metadata );
97 if ( isset( $metadata['translations'] ) ) {
98 foreach ( $metadata['translations'] as $lang => $langType ) {
99 if ( $langType === SVGReader::LANG_FULL_MATCH ) {
100 $langList[] = strtolower( $lang );
101 }
102 }
103 }
104 }
105 return array_unique( $langList );
106 }
107
108 /**
109 * SVG's systemLanguage matching rules state:
110 * 'The `systemLanguage` attribute ... [e]valuates to "true" if one of the languages indicated
111 * by user preferences exactly equals one of the languages given in the value of this parameter,
112 * or if one of the languages indicated by user preferences exactly equals a prefix of one of
113 * the languages given in the value of this parameter such that the first tag character
114 * following the prefix is "-".'
115 *
116 * Return the first element of $svgLanguages that matches $userPreferredLanguage
117 *
118 * @see https://www.w3.org/TR/SVG/struct.html#SystemLanguageAttribute
119 * @param string $userPreferredLanguage
120 * @param array $svgLanguages
121 * @return string|null
122 */
123 public function getMatchedLanguage( $userPreferredLanguage, array $svgLanguages ) {
124 foreach ( $svgLanguages as $svgLang ) {
125 if ( strcasecmp( $svgLang, $userPreferredLanguage ) === 0 ) {
126 return $svgLang;
127 }
128 $trimmedSvgLang = $svgLang;
129 while ( strpos( $trimmedSvgLang, '-' ) !== false ) {
130 $trimmedSvgLang = substr( $trimmedSvgLang, 0, strrpos( $trimmedSvgLang, '-' ) );
131 if ( strcasecmp( $trimmedSvgLang, $userPreferredLanguage ) === 0 ) {
132 return $svgLang;
133 }
134 }
135 }
136 return null;
137 }
138
139 /**
140 * Determines render language from image parameters
141 *
142 * @param array $params
143 * @return string
144 */
145 protected function getLanguageFromParams( array $params ) {
146 return $params['lang'] ?? $params['targetlang'] ?? 'en';
147 }
148
149 /**
150 * What language to render file in if none selected
151 *
152 * @param File $file Language code
153 * @return string
154 */
155 public function getDefaultRenderLanguage( File $file ) {
156 return 'en';
157 }
158
159 /**
160 * We do not support making animated svg thumbnails
161 * @param File $file
162 * @return bool
163 */
164 function canAnimateThumbnail( $file ) {
165 return false;
166 }
167
168 /**
169 * @param File $image
170 * @param array &$params
171 * @return bool
172 */
173 public function normaliseParams( $image, &$params ) {
174 if ( parent::normaliseParams( $image, $params ) ) {
175 $params = $this->normaliseParamsInternal( $image, $params );
176 return true;
177 }
178
179 return false;
180 }
181
182 /**
183 * Code taken out of normaliseParams() for testability
184 *
185 * @since 1.33
186 *
187 * @param File $image
188 * @param array $params
189 * @return array Modified $params
190 */
191 protected function normaliseParamsInternal( $image, $params ) {
192 global $wgSVGMaxSize;
193
194 # Don't make an image bigger than wgMaxSVGSize on the smaller side
195 if ( $params['physicalWidth'] <= $params['physicalHeight'] ) {
196 if ( $params['physicalWidth'] > $wgSVGMaxSize ) {
197 $srcWidth = $image->getWidth( $params['page'] );
198 $srcHeight = $image->getHeight( $params['page'] );
199 $params['physicalWidth'] = $wgSVGMaxSize;
200 $params['physicalHeight'] = File::scaleHeight( $srcWidth, $srcHeight, $wgSVGMaxSize );
201 }
202 } elseif ( $params['physicalHeight'] > $wgSVGMaxSize ) {
203 $srcWidth = $image->getWidth( $params['page'] );
204 $srcHeight = $image->getHeight( $params['page'] );
205 $params['physicalWidth'] = File::scaleHeight( $srcHeight, $srcWidth, $wgSVGMaxSize );
206 $params['physicalHeight'] = $wgSVGMaxSize;
207 }
208 // To prevent the proliferation of thumbnails in languages not present in SVGs, unless
209 // explicitly forced by user.
210 if ( isset( $params['targetlang'] ) && !$image->getMatchedLanguage( $params['targetlang'] ) ) {
211 unset( $params['targetlang'] );
212 }
213
214 return $params;
215 }
216
217 /**
218 * @param File $image
219 * @param string $dstPath
220 * @param string $dstUrl
221 * @param array $params
222 * @param int $flags
223 * @return bool|MediaTransformError|ThumbnailImage|TransformParameterError
224 */
225 function doTransform( $image, $dstPath, $dstUrl, $params, $flags = 0 ) {
226 if ( !$this->normaliseParams( $image, $params ) ) {
227 return new TransformParameterError( $params );
228 }
229 $clientWidth = $params['width'];
230 $clientHeight = $params['height'];
231 $physicalWidth = $params['physicalWidth'];
232 $physicalHeight = $params['physicalHeight'];
233 $lang = $this->getLanguageFromParams( $params );
234
235 if ( $flags & self::TRANSFORM_LATER ) {
236 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
237 }
238
239 $metadata = $this->unpackMetadata( $image->getMetadata() );
240 if ( isset( $metadata['error'] ) ) { // sanity check
241 $err = wfMessage( 'svg-long-error', $metadata['error']['message'] );
242
243 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight, $err );
244 }
245
246 if ( !wfMkdirParents( dirname( $dstPath ), null, __METHOD__ ) ) {
247 return new MediaTransformError( 'thumbnail_error', $clientWidth, $clientHeight,
248 wfMessage( 'thumbnail_dest_directory' ) );
249 }
250
251 $srcPath = $image->getLocalRefPath();
252 if ( $srcPath === false ) { // Failed to get local copy
253 wfDebugLog( 'thumbnail',
254 sprintf( 'Thumbnail failed on %s: could not get local copy of "%s"',
255 wfHostname(), $image->getName() ) );
256
257 return new MediaTransformError( 'thumbnail_error',
258 $params['width'], $params['height'],
259 wfMessage( 'filemissing' )
260 );
261 }
262
263 // Make a temp dir with a symlink to the local copy in it.
264 // This plays well with rsvg-convert policy for external entities.
265 // https://git.gnome.org/browse/librsvg/commit/?id=f01aded72c38f0e18bc7ff67dee800e380251c8e
266 $tmpDir = wfTempDir() . '/svg_' . wfRandomString( 24 );
267 $lnPath = "$tmpDir/" . basename( $srcPath );
268 $ok = mkdir( $tmpDir, 0771 );
269 if ( !$ok ) {
270 wfDebugLog( 'thumbnail',
271 sprintf( 'Thumbnail failed on %s: could not create temporary directory %s',
272 wfHostname(), $tmpDir ) );
273 return new MediaTransformError( 'thumbnail_error',
274 $params['width'], $params['height'],
275 wfMessage( 'thumbnail-temp-create' )->text()
276 );
277 }
278 $ok = symlink( $srcPath, $lnPath );
279 /** @noinspection PhpUnusedLocalVariableInspection */
280 $cleaner = new ScopedCallback( function () use ( $tmpDir, $lnPath ) {
281 Wikimedia\suppressWarnings();
282 unlink( $lnPath );
283 rmdir( $tmpDir );
284 Wikimedia\restoreWarnings();
285 } );
286 if ( !$ok ) {
287 wfDebugLog( 'thumbnail',
288 sprintf( 'Thumbnail failed on %s: could not link %s to %s',
289 wfHostname(), $lnPath, $srcPath ) );
290 return new MediaTransformError( 'thumbnail_error',
291 $params['width'], $params['height'],
292 wfMessage( 'thumbnail-temp-create' )
293 );
294 }
295
296 $status = $this->rasterize( $lnPath, $dstPath, $physicalWidth, $physicalHeight, $lang );
297 if ( $status === true ) {
298 return new ThumbnailImage( $image, $dstUrl, $dstPath, $params );
299 } else {
300 return $status; // MediaTransformError
301 }
302 }
303
304 /**
305 * Transform an SVG file to PNG
306 * This function can be called outside of thumbnail contexts
307 * @param string $srcPath
308 * @param string $dstPath
309 * @param string $width
310 * @param string $height
311 * @param bool|string $lang Language code of the language to render the SVG in
312 * @throws MWException
313 * @return bool|MediaTransformError
314 */
315 public function rasterize( $srcPath, $dstPath, $width, $height, $lang = false ) {
316 global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
317 $err = false;
318 $retval = '';
319 if ( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
320 if ( is_array( $wgSVGConverters[$wgSVGConverter] ) ) {
321 // This is a PHP callable
322 $func = $wgSVGConverters[$wgSVGConverter][0];
323 if ( !is_callable( $func ) ) {
324 throw new MWException( "$func is not callable" );
325 }
326 $err = $func( $srcPath,
327 $dstPath,
328 $width,
329 $height,
330 $lang,
331 ...array_slice( $wgSVGConverters[$wgSVGConverter], 1 )
332 );
333 $retval = (bool)$err;
334 } else {
335 // External command
336 $cmd = str_replace(
337 [ '$path/', '$width', '$height', '$input', '$output' ],
338 [ $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
339 intval( $width ),
340 intval( $height ),
341 wfEscapeShellArg( $srcPath ),
342 wfEscapeShellArg( $dstPath ) ],
343 $wgSVGConverters[$wgSVGConverter]
344 );
345
346 $env = [];
347 if ( $lang !== false ) {
348 $env['LANG'] = $lang;
349 }
350
351 wfDebug( __METHOD__ . ": $cmd\n" );
352 $err = wfShellExecWithStderr( $cmd, $retval, $env );
353 }
354 }
355 $removed = $this->removeBadFile( $dstPath, $retval );
356 if ( $retval != 0 || $removed ) {
357 $this->logErrorForExternalProcess( $retval, $err, $cmd );
358 return new MediaTransformError( 'thumbnail_error', $width, $height, $err );
359 }
360
361 return true;
362 }
363
364 public static function rasterizeImagickExt( $srcPath, $dstPath, $width, $height ) {
365 $im = new Imagick( $srcPath );
366 $im->setImageFormat( 'png' );
367 $im->setBackgroundColor( 'transparent' );
368 $im->setImageDepth( 8 );
369
370 if ( !$im->thumbnailImage( intval( $width ), intval( $height ), /* fit */ false ) ) {
371 return 'Could not resize image';
372 }
373 if ( !$im->writeImage( $dstPath ) ) {
374 return "Could not write to $dstPath";
375 }
376 }
377
378 /**
379 * @param File|FSFile $file
380 * @param string $path Unused
381 * @param bool|array $metadata
382 * @return array
383 */
384 function getImageSize( $file, $path, $metadata = false ) {
385 if ( $metadata === false && $file instanceof File ) {
386 $metadata = $file->getMetadata();
387 }
388 $metadata = $this->unpackMetadata( $metadata );
389
390 if ( isset( $metadata['width'] ) && isset( $metadata['height'] ) ) {
391 return [ $metadata['width'], $metadata['height'], 'SVG',
392 "width=\"{$metadata['width']}\" height=\"{$metadata['height']}\"" ];
393 } else { // error
394 return [ 0, 0, 'SVG', "width=\"0\" height=\"0\"" ];
395 }
396 }
397
398 public function getThumbType( $ext, $mime, $params = null ) {
399 return [ 'png', 'image/png' ];
400 }
401
402 /**
403 * Subtitle for the image. Different from the base
404 * class so it can be denoted that SVG's have
405 * a "nominal" resolution, and not a fixed one,
406 * as well as so animation can be denoted.
407 *
408 * @param File $file
409 * @return string
410 */
411 public function getLongDesc( $file ) {
412 global $wgLang;
413
414 $metadata = $this->unpackMetadata( $file->getMetadata() );
415 if ( isset( $metadata['error'] ) ) {
416 return wfMessage( 'svg-long-error', $metadata['error']['message'] )->text();
417 }
418
419 $size = $wgLang->formatSize( $file->getSize() );
420
421 if ( $this->isAnimatedImage( $file ) ) {
422 $msg = wfMessage( 'svg-long-desc-animated' );
423 } else {
424 $msg = wfMessage( 'svg-long-desc' );
425 }
426
427 $msg->numParams( $file->getWidth(), $file->getHeight() )->params( $size );
428
429 return $msg->parse();
430 }
431
432 /**
433 * @param File|FSFile $file
434 * @param string $filename
435 * @return string Serialised metadata
436 */
437 public function getMetadata( $file, $filename ) {
438 $metadata = [ 'version' => self::SVG_METADATA_VERSION ];
439 try {
440 $metadata += SVGMetadataExtractor::getMetadata( $filename );
441 } catch ( Exception $e ) { // @todo SVG specific exceptions
442 // File not found, broken, etc.
443 $metadata['error'] = [
444 'message' => $e->getMessage(),
445 'code' => $e->getCode()
446 ];
447 wfDebug( __METHOD__ . ': ' . $e->getMessage() . "\n" );
448 }
449
450 return serialize( $metadata );
451 }
452
453 function unpackMetadata( $metadata ) {
454 Wikimedia\suppressWarnings();
455 $unser = unserialize( $metadata );
456 Wikimedia\restoreWarnings();
457 if ( isset( $unser['version'] ) && $unser['version'] == self::SVG_METADATA_VERSION ) {
458 return $unser;
459 } else {
460 return false;
461 }
462 }
463
464 function getMetadataType( $image ) {
465 return 'parsed-svg';
466 }
467
468 public function isMetadataValid( $image, $metadata ) {
469 $meta = $this->unpackMetadata( $metadata );
470 if ( $meta === false ) {
471 return self::METADATA_BAD;
472 }
473 if ( !isset( $meta['originalWidth'] ) ) {
474 // Old but compatible
475 return self::METADATA_COMPATIBLE;
476 }
477
478 return self::METADATA_GOOD;
479 }
480
481 protected function visibleMetadataFields() {
482 $fields = [ 'objectname', 'imagedescription' ];
483
484 return $fields;
485 }
486
487 /**
488 * @param File $file
489 * @param bool|IContextSource $context Context to use (optional)
490 * @return array|bool
491 */
492 public function formatMetadata( $file, $context = false ) {
493 $result = [
494 'visible' => [],
495 'collapsed' => []
496 ];
497 $metadata = $file->getMetadata();
498 if ( !$metadata ) {
499 return false;
500 }
501 $metadata = $this->unpackMetadata( $metadata );
502 if ( !$metadata || isset( $metadata['error'] ) ) {
503 return false;
504 }
505
506 /* @todo Add a formatter
507 $format = new FormatSVG( $metadata );
508 $formatted = $format->getFormattedData();
509 */
510
511 // Sort fields into visible and collapsed
512 $visibleFields = $this->visibleMetadataFields();
513
514 $showMeta = false;
515 foreach ( $metadata as $name => $value ) {
516 $tag = strtolower( $name );
517 if ( isset( self::$metaConversion[$tag] ) ) {
518 $tag = strtolower( self::$metaConversion[$tag] );
519 } else {
520 // Do not output other metadata not in list
521 continue;
522 }
523 $showMeta = true;
524 self::addMeta( $result,
525 in_array( $tag, $visibleFields ) ? 'visible' : 'collapsed',
526 'exif',
527 $tag,
528 $value
529 );
530 }
531
532 return $showMeta ? $result : false;
533 }
534
535 /**
536 * @param string $name Parameter name
537 * @param mixed $value Parameter value
538 * @return bool Validity
539 */
540 public function validateParam( $name, $value ) {
541 if ( in_array( $name, [ 'width', 'height' ] ) ) {
542 // Reject negative heights, widths
543 return ( $value > 0 );
544 } elseif ( $name == 'lang' ) {
545 // Validate $code
546 if ( $value === '' || !Language::isValidCode( $value ) ) {
547 return false;
548 }
549
550 return true;
551 }
552
553 // Only lang, width and height are acceptable keys
554 return false;
555 }
556
557 /**
558 * @param array $params Name=>value pairs of parameters
559 * @return string Filename to use
560 */
561 public function makeParamString( $params ) {
562 $lang = '';
563 $code = $this->getLanguageFromParams( $params );
564 if ( $code !== 'en' ) {
565 $lang = 'lang' . strtolower( $code ) . '-';
566 }
567 if ( !isset( $params['width'] ) ) {
568 return false;
569 }
570
571 return "$lang{$params['width']}px";
572 }
573
574 public function parseParamString( $str ) {
575 $m = false;
576 if ( preg_match( '/^lang([a-z]+(?:-[a-z]+)*)-(\d+)px$/i', $str, $m ) ) {
577 return [ 'width' => array_pop( $m ), 'lang' => $m[1] ];
578 } elseif ( preg_match( '/^(\d+)px$/', $str, $m ) ) {
579 return [ 'width' => $m[1], 'lang' => 'en' ];
580 } else {
581 return false;
582 }
583 }
584
585 public function getParamMap() {
586 return [ 'img_lang' => 'lang', 'img_width' => 'width' ];
587 }
588
589 /**
590 * @param array $params
591 * @return array
592 */
593 protected function getScriptParams( $params ) {
594 $scriptParams = [ 'width' => $params['width'] ];
595 if ( isset( $params['lang'] ) ) {
596 $scriptParams['lang'] = $params['lang'];
597 }
598
599 return $scriptParams;
600 }
601
602 public function getCommonMetaArray( File $file ) {
603 $metadata = $file->getMetadata();
604 if ( !$metadata ) {
605 return [];
606 }
607 $metadata = $this->unpackMetadata( $metadata );
608 if ( !$metadata || isset( $metadata['error'] ) ) {
609 return [];
610 }
611 $stdMetadata = [];
612 foreach ( $metadata as $name => $value ) {
613 $tag = strtolower( $name );
614 if ( $tag === 'originalwidth' || $tag === 'originalheight' ) {
615 // Skip these. In the exif metadata stuff, it is assumed these
616 // are measured in px, which is not the case here.
617 continue;
618 }
619 if ( isset( self::$metaConversion[$tag] ) ) {
620 $tag = self::$metaConversion[$tag];
621 $stdMetadata[$tag] = $value;
622 }
623 }
624
625 return $stdMetadata;
626 }
627 }