SvgHandler.php 18 KB

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