ImageContentValidator.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /**
  3. *
  4. * Copyright © Magento, Inc. All rights reserved.
  5. * See COPYING.txt for license details.
  6. */
  7. namespace Magento\Framework\Api;
  8. use Magento\Framework\Api\Data\ImageContentInterface;
  9. use Magento\Framework\Exception\InputException;
  10. use Magento\Framework\Phrase;
  11. /**
  12. * Class for Image content validation
  13. */
  14. class ImageContentValidator implements ImageContentValidatorInterface
  15. {
  16. /**
  17. * @var array
  18. */
  19. private $defaultMimeTypes = [
  20. 'image/jpg',
  21. 'image/jpeg',
  22. 'image/gif',
  23. 'image/png',
  24. ];
  25. /**
  26. * @var array
  27. */
  28. private $allowedMimeTypes;
  29. /**
  30. * @param array $allowedMimeTypes
  31. */
  32. public function __construct(
  33. array $allowedMimeTypes = []
  34. ) {
  35. $this->allowedMimeTypes = array_merge($this->defaultMimeTypes, $allowedMimeTypes);
  36. }
  37. /**
  38. * Check if gallery entry content is valid
  39. *
  40. * @param ImageContentInterface $imageContent
  41. * @return bool
  42. * @throws InputException
  43. */
  44. public function isValid(ImageContentInterface $imageContent)
  45. {
  46. $fileContent = @base64_decode($imageContent->getBase64EncodedData(), true);
  47. if (empty($fileContent)) {
  48. throw new InputException(new Phrase('The image content must be valid base64 encoded data.'));
  49. }
  50. $imageProperties = @getimagesizefromstring($fileContent);
  51. if (empty($imageProperties)) {
  52. throw new InputException(new Phrase('The image content must be valid base64 encoded data.'));
  53. }
  54. $sourceMimeType = $imageProperties['mime'];
  55. if ($sourceMimeType != $imageContent->getType() || !$this->isMimeTypeValid($sourceMimeType)) {
  56. throw new InputException(new Phrase('The image MIME type is not valid or not supported.'));
  57. }
  58. if (!$this->isNameValid($imageContent->getName())) {
  59. throw new InputException(new Phrase('Provided image name contains forbidden characters.'));
  60. }
  61. return true;
  62. }
  63. /**
  64. * Check if given mime type is valid
  65. *
  66. * @param string $mimeType
  67. * @return bool
  68. */
  69. protected function isMimeTypeValid($mimeType)
  70. {
  71. return in_array($mimeType, $this->allowedMimeTypes);
  72. }
  73. /**
  74. * Check if given filename is valid
  75. *
  76. * @param string $name
  77. * @return bool
  78. */
  79. protected function isNameValid($name)
  80. {
  81. // Cannot contain \ / : * ? " < > |
  82. if (!preg_match('/^[^\\/?*:";<>()|{}\\\\]+$/', $name)) {
  83. return false;
  84. }
  85. return true;
  86. }
  87. }