Exemplo n.º 1
0
 /**
  * Validate uploaded file
  *
  * @return $this
  * @throws \Magento\Framework\Model\Exception
  */
 protected function _validateUploadedFile()
 {
     $option = $this->getOption();
     $processingParams = $this->_getProcessingParams();
     /**
      * Upload init
      */
     $upload = new \Zend_File_Transfer_Adapter_Http();
     $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
     $maxFileSize = $this->getFileSizeService()->getMaxFileSize();
     try {
         $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
         if (!$runValidation) {
             $this->setUserValue(null);
             return $this;
         }
         $fileInfo = $upload->getFileInfo($file);
         $fileInfo = $fileInfo[$file];
         $fileInfo['title'] = $fileInfo['name'];
     } catch (\Exception $e) {
         // when file exceeds the upload_max_filesize, $_FILES is empty
         if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $maxFileSize) {
             $this->setIsValid(false);
             $value = $this->getFileSizeService()->getMaxFileSizeInMb();
             throw new Exception(__("The file you uploaded is larger than %1 Megabytes allowed by server", $value));
         } else {
             switch ($this->getProcessMode()) {
                 case \Magento\Catalog\Model\Product\Type\AbstractType::PROCESS_MODE_FULL:
                     throw new Exception(__('Please specify the product\'s required option(s).'));
                     break;
                 default:
                     $this->setUserValue(null);
                     break;
             }
             return $this;
         }
     }
     /**
      * Option Validations
      */
     // Image dimensions
     $_dimentions = array();
     if ($option->getImageSizeX() > 0) {
         $_dimentions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $_dimentions['maxheight'] = $option->getImageSizeY();
     }
     if (count($_dimentions) > 0) {
         $upload->addValidator('ImageSize', false, $_dimentions);
     }
     // File extension
     $_allowed = $this->_parseExtensionsString($option->getFileExtension());
     if ($_allowed !== null) {
         $upload->addValidator('Extension', false, $_allowed);
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $upload->addValidator('ExcludeExtension', false, $_forbidden);
         }
     }
     // Maximum filesize
     $upload->addValidator('FilesSize', false, array('max' => $maxFileSize));
     /**
      * Upload process
      */
     $this->_initFilesystem();
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = \Magento\Core\Model\File\Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = \Magento\Core\Model\File\Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $tmpDirectory = $this->_filesystem->getDirectoryRead(\Magento\Framework\App\Filesystem::SYS_TMP_DIR);
         $fileHash = md5($tmpDirectory->readFile($tmpDirectory->getRelativePath($fileInfo['tmp_name'])));
         $filePath .= '/' . $fileHash . '.' . $extension;
         $fileFullPath = $this->_mediaDirectory->getAbsolutePath($this->_quotePath . $filePath);
         $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
         $this->getProduct()->getTypeInstance()->addFileQueue(array('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(\Magento\Framework\App\Filesystem::MEDIA_DIR);
         $this->setUserValue(array('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);
         if (count($errors) > 0) {
             $this->setIsValid(false);
             throw new Exception(implode("\n", $errors));
         }
     } else {
         $this->setIsValid(false);
         throw new Exception(__('Please specify the product\'s required option(s).'));
     }
     return $this;
 }
Exemplo n.º 2
0
 /**
  * Add image to media gallery and return new filename
  *
  * @param \Magento\Catalog\Model\Product $product
  * @param string $file file path of image in file system
  * @param string|string[] $mediaAttribute code of attribute with type 'media_image',
  *                                                      leave blank if image should be only in gallery
  * @param boolean $move if true, it will move source file
  * @param boolean $exclude mark image as disabled in product page view
  * @return string
  * @throws Exception
  */
 public function addImage(\Magento\Catalog\Model\Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true)
 {
     $file = $this->_mediaDirectory->getRelativePath($file);
     if (!$this->_mediaDirectory->isFile($file)) {
         throw new Exception(__('The image does not exist.'));
     }
     $pathinfo = pathinfo($file);
     $imgExtensions = array('jpg', 'jpeg', 'gif', 'png');
     if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) {
         throw new Exception(__('Please correct the image file type.'));
     }
     $fileName = \Magento\Core\Model\File\Uploader::getCorrectFileName($pathinfo['basename']);
     $dispretionPath = \Magento\Core\Model\File\Uploader::getDispretionPath($fileName);
     $fileName = $dispretionPath . '/' . $fileName;
     $fileName = $this->_getNotDuplicatedFilename($fileName, $dispretionPath);
     $destinationFile = $this->_mediaConfig->getTmpMediaPath($fileName);
     try {
         /** @var $storageHelper \Magento\Core\Helper\File\Storage\Database */
         $storageHelper = $this->_fileStorageDb;
         if ($move) {
             $this->_mediaDirectory->renameFile($file, $destinationFile);
             //If this is used, filesystem should be configured properly
             $storageHelper->saveFile($this->_mediaConfig->getTmpMediaShortUrl($fileName));
         } else {
             $this->_mediaDirectory->copyFile($file, $destinationFile);
             $storageHelper->saveFile($this->_mediaConfig->getTmpMediaShortUrl($fileName));
             $this->_mediaDirectory->changePermissions($destinationFile, 0777);
         }
     } catch (\Exception $e) {
         throw new Exception(__('We couldn\'t move this file: %1.', $e->getMessage()));
     }
     $fileName = str_replace('\\', '/', $fileName);
     $attrCode = $this->getAttribute()->getAttributeCode();
     $mediaGalleryData = $product->getData($attrCode);
     $position = 0;
     if (!is_array($mediaGalleryData)) {
         $mediaGalleryData = array('images' => array());
     }
     foreach ($mediaGalleryData['images'] as &$image) {
         if (isset($image['position']) && $image['position'] > $position) {
             $position = $image['position'];
         }
     }
     $position++;
     $mediaGalleryData['images'][] = array('file' => $fileName, 'position' => $position, 'label' => '', 'disabled' => (int) $exclude);
     $product->setData($attrCode, $mediaGalleryData);
     if (!is_null($mediaAttribute)) {
         $this->setMediaAttribute($product, $mediaAttribute, $fileName);
     }
     return $fileName;
 }