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