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