public function testEmptyFile() { $this->prepareEnvForEmptyFile(); $this->setExpectedException('\\Magento\\Framework\\Exception\\LocalizedException', 'The file is empty. Please choose another one'); $httpAdapterMock = $this->getMock('Zend_File_Transfer_Adapter_Http', ['isValid']); $httpAdapterMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); $this->model->validate($this->objectManager->create('Magento\\Framework\\DataObject'), $this->getProductOption()); }
/** * @return void */ public function testValidate() { $this->prepareEnv(); $httpAdapterMock = $this->getMock('Zend_File_Transfer_Adapter_Http', ['isValid']); $httpAdapterMock->expects($this->once())->method('isValid')->will($this->returnValue(true)); $this->httpFactoryMock->expects($this->once())->method('create')->will($this->returnValue($httpAdapterMock)); $result = $this->model->validate($this->objectManager->create('Magento\\Framework\\Object'), $this->getProductOption()); unset($result['fullpath'], $result['secret_key']); $this->assertEquals($this->expectedValidate(), $result); }
/** * Validate file. * * @throws \Exception * @param string $fileId * @param bool $isImage * @return bool */ public function isFileValid($fileId, $isImage) { $adapter = $this->httpFactory->create(); $adapter->addValidator(new \Zend_Validate_File_FilesSize(['max' => $isImage ? self::MAX_IMAGE_FILE_SIZE : self::MAX_FILE_SIZE])); if ($adapter->isUploaded($fileId)) { // validate image if (!$adapter->isValid($fileId)) { throw new \Exception(__('Uploaded file is not valid.')); } return true; } return false; }
/** * Move uploaded file and create source adapter instance. * * @throws \Magento\Framework\Exception\LocalizedException * @return string Source file path */ public function uploadSource() { /** @var $adapter \Zend_File_Transfer_Adapter_Http */ $adapter = $this->_httpFactory->create(); if (!$adapter->isValid(self::FIELD_NAME_SOURCE_FILE)) { $errors = $adapter->getErrors(); if ($errors[0] == \Zend_Validate_File_Upload::INI_SIZE) { $errorMessage = $this->_importExportData->getMaxUploadSizeMessage(); } else { $errorMessage = __('File was not uploaded.'); } throw new \Magento\Framework\Exception\LocalizedException($errorMessage); } $entity = $this->getEntity(); /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */ $uploader = $this->_uploaderFactory->create(['fileId' => self::FIELD_NAME_SOURCE_FILE]); $uploader->skipDbProcessing(true); $result = $uploader->save($this->getWorkingDir()); $extension = pathinfo($result['file'], PATHINFO_EXTENSION); $uploadedFile = $result['path'] . $result['file']; if (!$extension) { $this->_varDirectory->delete($uploadedFile); throw new \Magento\Framework\Exception\LocalizedException(__('Uploaded file has no extension')); } $sourceFile = $this->getWorkingDir() . $entity; $sourceFile .= '.' . $extension; $sourceFileRelative = $this->_varDirectory->getRelativePath($sourceFile); if (strtolower($uploadedFile) != strtolower($sourceFile)) { if ($this->_varDirectory->isExist($sourceFileRelative)) { $this->_varDirectory->delete($sourceFileRelative); } try { $this->_varDirectory->renameFile($this->_varDirectory->getRelativePath($uploadedFile), $sourceFileRelative); } catch (\Magento\Framework\Exception\FileSystemException $e) { throw new \Magento\Framework\Exception\LocalizedException(__('Source file moving failed')); } } $this->_removeBom($sourceFile); // trying to create source adapter for file and catch possible exception to be convinced in its adequacy try { $this->_getSourceAdapter($sourceFile); } catch (\Exception $e) { $this->_varDirectory->delete($sourceFileRelative); throw new \Magento\Framework\Exception\LocalizedException(__($e->getMessage())); } return $sourceFile; }
/** * Upload image and return uploaded image file name or false * * @throws Mage_Core_Exception * @param string $scope the request key for file * @return bool|string */ public function uploadImage($scope) { $adapter = $this->httpFactory->create(); $adapter->addValidator(new \Zend_Validate_File_FilesSize(['max' => self::MAX_FILE_SIZE])); if ($adapter->isUploaded($scope)) { // validate image if (!$adapter->isValid($scope)) { $this->messageManager->addException__('Uploaded image is not valid.'); } $uploader = $this->_fileUploaderFactory->create(['fileId' => $scope]); $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $uploader->setAllowCreateFolders(true); if ($uploader->save($this->getBaseDir())) { return $uploader->getUploadedFileName(); } } return false; }
/** * @param \Magento\Framework\Object $processingParams * @param \Magento\Catalog\Model\Product\Option $option * @return array * @throws LocalizedException * @throws ProductException * @throws \Exception * @throws \Magento\Framework\Exception\InputException * @throws \Magento\Framework\Validator\Exception * @throws \Zend_File_Transfer_Exception * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function validate($processingParams, $option) { $upload = $this->httpFactory->create(); $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file'; try { $runValidation = $option->getIsRequire() || $upload->isUploaded($file); if (!$runValidation) { throw new \Magento\Framework\Validator\Exception(__('Validation failed. Required options were not filled or file was not uploaded.')); } $fileInfo = $upload->getFileInfo($file)[$file]; $fileInfo['title'] = $fileInfo['name']; } catch (\Magento\Framework\Validator\Exception $e) { throw $e; } catch (\Exception $e) { // when file exceeds the upload_max_filesize, $_FILES is empty if ($this->validateContentLength()) { $value = $this->fileSize->getMaxFileSizeInMb(); throw new LocalizedException(__('The file you uploaded is larger than %1 Megabytes allowed by server', $value)); } else { throw new ProductException(__('Option required.')); } } /** * Option Validations */ $upload = $this->buildImageValidator($upload, $option); /** * Upload process */ $this->initFilesystem(); $userValue = []; if ($upload->isUploaded($file) && $upload->isValid($file)) { $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION); $fileName = \Magento\MediaStorage\Model\File\Uploader::getCorrectFileName($fileInfo['name']); $dispersion = \Magento\MediaStorage\Model\File\Uploader::getDispretionPath($fileName); $filePath = $dispersion; $tmpDirectory = $this->filesystem->getDirectoryRead(DirectoryList::SYS_TMP); $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name']))); $filePath .= '/' . $fileHash . '.' . $extension; $fileFullPath = $this->mediaDirectory->getAbsolutePath($this->quotePath . $filePath); $upload->addFilter(new \Zend_Filter_File_Rename(['target' => $fileFullPath, 'overwrite' => true])); if ($this->product !== null) { $this->product->getTypeInstance()->addFileQueue(['operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this]); } $_width = 0; $_height = 0; if ($tmpDirectory->isReadable($tmpDirectory->getRelativePath($fileInfo['tmp_name']))) { $imageSize = getimagesize($fileInfo['tmp_name']); if ($imageSize) { $_width = $imageSize[0]; $_height = $imageSize[1]; } } $uri = $this->filesystem->getUri(DirectoryList::MEDIA); $userValue = ['type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $uri . $this->quotePath . $filePath, 'order_path' => $uri . $this->orderPath . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)]; } elseif ($upload->getErrors()) { $errors = $this->getValidatorErrors($upload->getErrors(), $fileInfo, $option); if (count($errors) > 0) { throw new LocalizedException(__(implode("\n", $errors))); } } else { throw new LocalizedException(__('Please specify the product\'s required option(s).')); } return $userValue; }
/** * Constructor * * @param \Magento\Framework\Filesystem $filesystem * @param \Magento\Framework\HTTP\Adapter\FileTransferFactory $adapterFactory * @param \Magento\Framework\File\UploaderFactory $uploaderFactory */ public function __construct(\Magento\Framework\Filesystem $filesystem, \Magento\Framework\HTTP\Adapter\FileTransferFactory $adapterFactory, \Magento\Framework\File\UploaderFactory $uploaderFactory) { $this->_filesystem = $filesystem; $this->_transferAdapter = $adapterFactory->create(); $this->_uploaderFactory = $uploaderFactory; }