/** * Count files recursively for given directory * * @param string $directory * @param array $files * @param int $level * @param string $sku * * @return array */ public function getFiles($directory, $files = array(), $level = 0, $sku = '') { $level++; $handle = opendir($directory); while ($file = readdir($handle)) { if ($file != "." && $file != ".." && $file != ".DS_Store") { if (is_dir($directory . DS . $file)) { if ($level == 1) { $sku = $file; $files[$sku] = array(); } $files = $this->getFiles($directory . DS . $file, $files, $level, $sku); if (isset($files[$sku])) { if (!count($files[$sku])) { unset($files[$sku]); } } } else { $extension = pathinfo($directory . DS . $file, PATHINFO_EXTENSION); $name = strtolower($sku . '-' . (count($files[$sku]) + 1) . '.' . $extension); $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($name); $path = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $fileName = $path . DS . $fileName; if (empty($files[$sku][$directory])) { $files[$sku][$directory] = array('directory' => $directory . DS, 'file' => $file, 'name' => $fileName); } ksort($files[$sku]); } } } closedir($handle); return $files; }
/** * Add image to media gallery and return new filename * * @param Mage_Catalog_Model_Product $product * @param string $file file path of image in file system * @param string|array $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 */ public function addImage(Mage_Catalog_Model_Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true) { if (!Mage::helper('uaudio_storage')->isEnabled()) { return parent::addImage(product, $file, $mediaAttribute, $move, $exclude); } $file = realpath($file); if (!$file || !file_exists($file)) { Mage::throwException(Mage::helper('catalog')->__('Image does not exist.')); } Mage::dispatchEvent('catalog_product_media_add_image', array('product' => $product, 'image' => $file)); $pathinfo = pathinfo($file); $imgExtensions = array('jpg', 'jpeg', 'gif', 'png'); if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) { Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.')); } $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($pathinfo['basename']); $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $fileName = $dispretionPath . DS . $fileName; $dest = $this->_getConfig()->getTmpMediaPath($fileName); $storageModel = Mage::getSingleton('core/file_storage')->getStorageModel(); $storageModel->setAllowRenameFiles(true); try { if ($move) { $uploadDestination = $storageModel->moveFile($file, $dest); } else { $uploadDestination = $storageModel->moveUploadFile($file, $dest); } if (!$uploadDestination) { throw new Exception(); } $fileName = basename($uploadDestination); $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $fileName = $dispretionPath . DS . $fileName; } catch (Exception $e) { Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage())); } $fileName = str_replace(DS, '/', $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; }
/** * Validate uploaded file * * @throws Mage_Core_Exception * @return Mage_Catalog_Model_Product_Option_Type_File */ protected function _validateUploadedFile() { $option = $this->getOption(); if (Mage::helper('aitcg/options')->checkAitOption($option)) { $values = Mage::app()->getRequest()->getParam('options'); $optionValue = $values[$option->getId()]; $runValidation = ($option->getIsRequire() || $this->_validateValue($option)) && !is_null($optionValue); if (!$runValidation) { $this->setUserValue(null); return $this; } $optionValue = Mage::helper('core')->jsonDecode($optionValue); $this->_initFilesystem(); $model = Mage::getModel('aitcg/image'); $src = Mage::getBaseDir('media') . DS . $model->getFullTempPath() . DS . $optionValue['config']['rand'] . '.' . Aitoc_Aitcg_Model_Image::FORMAT_PNG; $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName(pathinfo(strtolower($src), PATHINFO_FILENAME)); $dispersion = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $filePath = $dispersion; $fileHash = md5(file_get_contents($src)); $filePath .= DS . $fileHash . '.' . Aitoc_Aitcg_Model_Image::FORMAT_PNG; $fileFullPath = $this->getQuoteTargetDir() . $filePath; $_width = 0; $_height = 0; $_fileSize = 0; if (is_readable($src)) { $_imageSize = getimagesize($src); if ($_imageSize) { $_width = $_imageSize[0]; $_height = $_imageSize[1]; } $_fileSize = filesize($src); } $manager = Mage::getModel('aitcg/image_manager'); $template_id = $manager->addImage($values[$option->getId()], Mage::app()->getRequest()->getParam('product'), $option->getId(), $option); $this->setUserValue(array('type' => 'image/png', 'title' => 'custom_product_preview.png', 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $filePath, 'fullpath' => $fileFullPath, 'size' => $_fileSize, 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20), Aitoc_Aitcg_Helper_Options::OPTION_DATA_KEY => array('template_id' => $template_id, Aitoc_Aitcg_Model_Sales_Order_Item_Converter::CUSTOMER_IMAGE_META_VERSION_KEY => Aitoc_Aitcg_Model_Sales_Order_Item_Converter::CUSTOMER_IMAGE_META_VERSION))); $path = dirname($fileFullPath); $io = new Varien_Io_File(); if (!$io->isWriteable($path) && !$io->mkdir($path, 0777, true)) { Mage::throwException(Mage::helper('catalog')->__("Cannot create writeable directory '%s'.", $path)); } @copy($src, $fileFullPath); return $this; } else { return parent::_validateUploadedFile(); } }
/** * Validate uploaded file * * @throws Mage_Core_Exception * @return Mage_Catalog_Model_Product_Option_Type_File */ 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(); Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__("The file you uploaded is larger than %s Megabytes allowed by server", $value)); } else { switch ($this->getProcessMode()) { case Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL: Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('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 = Mage_Core_Model_File_Uploader::getCorrectFileName($fileInfo['name']); $dispersion = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $filePath = $dispersion; $fileHash = md5($this->_filesystem->read($fileInfo['tmp_name'])); $filePath .= DS . $fileHash . '.' . $extension; $fileFullPath = $this->getQuoteTargetDir() . $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 ($this->_filesystem->isReadable($fileInfo['tmp_name'])) { $_imageSize = getimagesize($fileInfo['tmp_name']); if ($_imageSize) { $_width = $_imageSize[0]; $_height = $_imageSize[1]; } } $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $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); Mage::throwException(implode("\n", $errors)); } } else { $this->setIsValid(false); Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Please specify the product required option(s)')); } return $this; }
/** * Update table (Step 4) * * @param Pimgento_Core_Model_Task $task * * @return bool */ public function updateTable($task) { $adapter = $this->getAdapter(); /* Clean up table */ $adapter->truncateTable($adapter->getTableName('pimgento_asset')); /* Insert data from tmp table */ $select = $adapter->select()->from($this->getTable(), array('asset', 'website_id', 'store_id', 'reference_file', 'variation_file')); $query = $adapter->query($select); while ($row = $query->fetch()) { $stores = explode(',', $row['store_id']); foreach ($stores as $storeId) { $pathInfo = pathinfo($row['reference_file']); $file = Mage_Core_Model_File_Uploader::getDispretionPath($pathInfo['basename']) . DS . $pathInfo['basename']; $data = array('asset' => $row['asset'], 'website_id' => $row['website_id'], 'store_id' => $storeId, 'file' => $row['reference_file'], 'variation' => $row['variation_file'], 'image' => $file, 'small_image' => $file, 'thumbnail' => $file); $adapter->insert($adapter->getTableName('pimgento_asset'), $data); } } return true; }
/** * Add image to media gallery and return new filename * * @param Mage_Catalog_Model_Product $product * @param string $file file path of image in file system * @param string|array $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 */ public function addImage(Mage_Catalog_Model_Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true) { $file = realpath($file); if (!$file || !file_exists($file)) { Mage::throwException(Mage::helper('catalog')->__('Image does not exist.')); } $pathinfo = pathinfo($file); $imgExtensions = array('jpg', 'jpeg', 'gif', 'png'); if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) { Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.')); } $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($pathinfo['basename']); $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $fileName = $dispretionPath . DS . $fileName; $fileName = $this->_getNotDuplicatedFilename($fileName, $dispretionPath); $ioAdapter = new Varien_Io_File(); $ioAdapter->setAllowCreateFolders(true); $distanationDirectory = dirname($this->_getConfig()->getTmpMediaPath($fileName)); try { $ioAdapter->open(array('path' => $distanationDirectory)); /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */ $storageHelper = Mage::helper('core/file_storage_database'); if ($move) { $ioAdapter->mv($file, $this->_getConfig()->getTmpMediaPath($fileName)); //If this is used, filesystem should be configured properly $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($fileName)); } else { $ioAdapter->cp($file, $this->_getConfig()->getTmpMediaPath($fileName)); $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($fileName)); $ioAdapter->chmod($this->_getConfig()->getTmpMediaPath($fileName), 0777); } } catch (Exception $e) { Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage())); } $fileName = str_replace(DS, '/', $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; }
/** * @param $filename * @return string */ public function getFilePath($filename) { return $this->getPdfDirectory() . DS . Mage_Core_Model_File_Uploader::getDispretionPath($filename); }
/** * Add image to media gallery and return new filename * * @param Mage_Catalog_Model_Product $product * @param string $file file path of image in file system * @param string|array $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 */ public function addImage(Mage_Catalog_Model_Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true) { if (!$this->_filesystem->isFile($file, $this->_baseTmpMediaPath)) { Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Image does not exist.')); } Mage::dispatchEvent('catalog_product_media_add_image', array('product' => $product, 'image' => $file)); $pathinfo = pathinfo($file); $imgExtensions = array('jpg', 'jpeg', 'gif', 'png'); if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) { Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Invalid image file type.')); } $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($pathinfo['basename']); $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $fileName = $dispretionPath . DS . $fileName; $fileName = $this->_getNotDuplicatedFilename($fileName, $dispretionPath); $destinationFile = $this->_getConfig()->getTmpMediaPath($fileName); try { /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */ $storageHelper = Mage::helper('Mage_Core_Helper_File_Storage_Database'); if ($move) { $this->_filesystem->rename($file, $destinationFile, $this->_baseTmpMediaPath); //If this is used, filesystem should be configured properly $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($fileName)); } else { $this->_filesystem->copy($file, $destinationFile, $this->_baseTmpMediaPath); $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($fileName)); $this->_filesystem->changePermissions($destinationFile, 0777, false, $this->_baseTmpMediaPath); } } catch (Exception $e) { Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Failed to move file: %s', $e->getMessage())); } $fileName = str_replace(DS, '/', $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; }
/** * * @param string $filename * @param resource $image * @param Mage_Catalog_Model_Product_Option $option */ protected function _uploadPhoto($filename, $image, $option) { $result = array(); $optionFile = $option->groupFactory($option->getType()); $extension = pathinfo(strtolower($filename), PATHINFO_EXTENSION); $filename = Mage_Core_Model_File_Uploader::getCorrectFileName($filename); $dispersion = Mage_Core_Model_File_Uploader::getDispretionPath($filename); $quoteDir = $optionFile->getQuoteTargetDir() . $dispersion; $uploadDir = Mage::helper('aydus_customconfigurable')->getMediaDir() . DS . $dispersion; if (!file_exists($quoteDir)) { mkdir($quoteDir, 0775, true); } if (!file_exists($uploadDir)) { mkdir($uploadDir, 0775, true); } $hash = md5($image); $filenameHash = $hash . '.' . $extension; $quoteFilePath = $quoteDir . DS . $filenameHash; $size = file_put_contents($quoteFilePath, $image); $result['error'] = $size > 0 ? false : true; if ($result['error']) { $result['data'] = 'File upload failed'; } else { $time = time(); $uploadFilePath = $uploadDir . DS . $time . '-' . $filename; if (copy($quoteFilePath, $uploadFilePath)) { $result['data'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'aydus' . DS . 'customconfigurable' . $dispersion . DS . $time . '-' . $filename; } else { $result['error'] = true; $result['data'] = 'Could not copy uploaded image to ' . $uploadFilePath . '; check permissions'; } } return $result; }