vendor/pimcore/pimcore/bundles/CoreBundle/EventListener/AssetSanitizationListener.php line 41

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Bundle\CoreBundle\EventListener;
  15. use enshrined\svgSanitize\Sanitizer;
  16. use Pimcore\Event\AssetEvents;
  17. use Pimcore\Event\Model\ElementEventInterface;
  18. use Pimcore\Model\Asset;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Symfony\Component\Mime\MimeTypes;
  21. /**
  22.  * @internal
  23.  */
  24. class AssetSanitizationListener implements EventSubscriberInterface
  25. {
  26.     public static function getSubscribedEvents()
  27.     {
  28.         return [
  29.             AssetEvents::PRE_ADD => 'sanitizeAsset',
  30.             AssetEvents::PRE_UPDATE => 'sanitizeAsset',
  31.         ];
  32.     }
  33.     /**
  34.      * @param ElementEventInterface $e
  35.      */
  36.     public function sanitizeAsset(ElementEventInterface $e)
  37.     {
  38.         $element $e->getElement();
  39.         if ($element instanceof Asset\Image && $element->getDataChanged()) {
  40.             $assetStream $element->getStream();
  41.             if (isset($assetStream)) {
  42.                 $streamMetaData stream_get_meta_data($assetStream);
  43.                 $mime MimeTypes::getDefault()->guessMimeType($streamMetaData['uri']);
  44.                 if ($mime === 'image/svg+xml') {
  45.                     $sanitizedData $this->sanitizeSVG(stream_get_contents($assetStream));
  46.                     $element->setData($sanitizedData);
  47.                 }
  48.             }
  49.         }
  50.     }
  51.     /**
  52.      * @param string $fileContent
  53.      *
  54.      * @return string
  55.      *
  56.      * @throws \Exception
  57.      */
  58.     protected function sanitizeSVG(string $fileContent)
  59.     {
  60.         $sanitizer = new Sanitizer();
  61.         $sanitizedFileContent $sanitizer->sanitize($fileContent);
  62.         if (!$sanitizedFileContent) {
  63.             throw new \Exception('SVG Sanitization failed, probably due badly formatted XML.');
  64.         }
  65.         return $sanitizedFileContent;
  66.     }
  67. }