Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ValidatorFile.php
Go to the documentation of this file.
1 <?php
8 
11 use Magento\Catalog\Model\Product\Exception as ProductException;
15 
21 class ValidatorFile extends Validator
22 {
28  protected $path = 'custom_options';
29 
35  protected $quotePath = 'custom_options/quote';
36 
42  protected $orderPath = 'custom_options/order';
43 
47  protected $mediaDirectory;
48 
52  protected $filesystem;
53 
57  protected $httpFactory;
58 
62  protected $product;
63 
67  protected $isImageValidator;
68 
72  private $random;
73 
85  public function __construct(
87  \Magento\Framework\Filesystem $filesystem,
88  \Magento\Framework\File\Size $fileSize,
89  \Magento\Framework\HTTP\Adapter\FileTransferFactory $httpFactory,
90  \Magento\Framework\Validator\File\IsImage $isImageValidator,
91  Random $random = null
92  ) {
93  $this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
94  $this->filesystem = $filesystem;
95  $this->httpFactory = $httpFactory;
96  $this->isImageValidator = $isImageValidator;
97  $this->random = $random
98  ?? ObjectManager::getInstance()->get(Random::class);
99  parent::__construct($scopeConfig, $filesystem, $fileSize);
100  }
101 
108  public function setProduct(Product $product)
109  {
110  $this->product = $product;
111  return $this;
112  }
113 
129  public function validate($processingParams, $option)
130  {
131  $upload = $this->httpFactory->create();
132  $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
133  try {
134  $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
135  if (!$runValidation) {
136  throw new \Magento\Framework\Validator\Exception(
137  __(
138  'The validation failed. '
139  . 'Make sure the required options are entered and the file is uploaded, then try again.'
140  )
141  );
142  }
143 
144  $fileInfo = $upload->getFileInfo($file)[$file];
145  $fileInfo['title'] = $fileInfo['name'];
146  } catch (\Magento\Framework\Validator\Exception $e) {
147  throw $e;
148  } catch (\Exception $e) {
149  // when file exceeds the upload_max_filesize, $_FILES is empty
150  if ($this->validateContentLength()) {
151  $value = $this->fileSize->getMaxFileSizeInMb();
152  throw new LocalizedException(
153  __(
154  "The file was too big and couldn't be uploaded. "
155  . "Use a file smaller than %1 MBs and try to upload again.",
156  $value
157  )
158  );
159  } else {
160  throw new ProductException(__("The required option wasn't entered. Enter the option and try again."));
161  }
162  }
163 
167  $upload = $this->buildImageValidator($upload, $option);
168 
172  $this->initFilesystem();
173  $userValue = [];
174 
175  if ($upload->isUploaded($file) && $upload->isValid($file)) {
178 
179  $filePath = $dispersion;
180 
181  $tmpDirectory = $this->filesystem->getDirectoryRead(DirectoryList::SYS_TMP);
182  $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name'])));
183  $fileRandomName = $this->random->getRandomString(32);
184  $filePath .= '/' .$fileRandomName;
185  $fileFullPath = $this->mediaDirectory->getAbsolutePath($this->quotePath . $filePath);
186 
187  $upload->addFilter(new \Zend_Filter_File_Rename(['target' => $fileFullPath, 'overwrite' => true]));
188 
189  if ($this->product !== null) {
190  $this->product->getTypeInstance()->addFileQueue(
191  [
192  'operation' => 'receive_uploaded_file',
193  'src_name' => $file,
194  'dst_name' => $fileFullPath,
195  'uploader' => $upload,
196  'option' => $this,
197  ]
198  );
199  }
200 
201  $_width = 0;
202  $_height = 0;
203 
204  if ($tmpDirectory->isReadable($tmpDirectory->getRelativePath($fileInfo['tmp_name']))) {
205  if (filesize($fileInfo['tmp_name'])) {
206  if ($this->isImageValidator->isValid($fileInfo['tmp_name'])) {
207  $imageSize = getimagesize($fileInfo['tmp_name']);
208  }
209  } else {
210  throw new LocalizedException(__('The file is empty. Select another file and try again.'));
211  }
212 
213  if (!empty($imageSize)) {
214  $_width = $imageSize[0];
215  $_height = $imageSize[1];
216  }
217  }
218 
219  $userValue = [
220  'type' => $fileInfo['type'],
221  'title' => $fileInfo['name'],
222  'quote_path' => $this->quotePath . $filePath,
223  'order_path' => $this->orderPath . $filePath,
224  'fullpath' => $fileFullPath,
225  'size' => $fileInfo['size'],
226  'width' => $_width,
227  'height' => $_height,
228  'secret_key' => substr($fileHash, 0, 20),
229  ];
230  } elseif ($upload->getErrors()) {
231  $errors = $this->getValidatorErrors($upload->getErrors(), $fileInfo, $option);
232 
233  if (count($errors) > 0) {
234  throw new LocalizedException(__(implode("\n", $errors)));
235  }
236  } else {
237  throw new LocalizedException(
238  __("The product's required option(s) weren't entered. Make sure the options are entered and try again.")
239  );
240  }
241  return $userValue;
242  }
243 
250  protected function initFilesystem()
251  {
252  $this->mediaDirectory->create($this->path);
253  $this->mediaDirectory->create($this->quotePath);
254  $this->mediaDirectory->create($this->orderPath);
255 
256  // Directory listing and hotlink secure
257  $path = $this->path . '/.htaccess';
258  if (!$this->mediaDirectory->isFile($path)) {
259  $this->mediaDirectory->writeFile($path, "Order deny,allow\nDeny from all");
260  }
261  }
262 
269  protected function validateContentLength()
270  {
271  return isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $this->fileSize->getMaxFileSize();
272  }
273 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
static getCorrectFileName($fileName)
Definition: Uploader.php:375
__()
Definition: __.php:13
__construct(\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\Filesystem $filesystem, \Magento\Framework\File\Size $fileSize, \Magento\Framework\HTTP\Adapter\FileTransferFactory $httpFactory, \Magento\Framework\Validator\File\IsImage $isImageValidator, Random $random=null)
$tmpDirectory
$fileName
Definition: translate.phtml:15
$value
Definition: gender.phtml:16
$_width
Definition: gallery.phtml:11
buildImageValidator($object, $option, $fileFullPath=null)
Definition: Validator.php:142
$_height
Definition: files.phtml:12
$errors
Definition: overview.phtml:9
static getDispersionPath($fileName)
Definition: Uploader.php:642