/** * Create destination folder if not exists and return full file path * * @throws Exception * @param string $destination * @param string $newName * @return string */ protected function _prepareDestination($destination = null, $newName = null) { if (empty($destination)) { $destination = $this->_fileSrcPath; } else { if (empty($newName)) { $info = pathinfo($destination); $newName = $info['basename']; $destination = $info['dirname']; } } if (empty($newName)) { $newFileName = $this->_fileSrcName; } else { $newFileName = $newName; } $fileName = $destination . DIRECTORY_SEPARATOR . $newFileName; if (!is_writable($destination)) { try { $result = $this->_ioFile->mkdir($destination); } catch (Exception $e) { $result = false; } if (!$result) { throw new Exception('Unable to write file into directory ' . $destination . '. Access forbidden.'); } } return $fileName; }
protected function _loadFiles() { if (!$this->_isLoaded) { $readPath = Mage::getBaseDir("var") . DS . "backups"; $ioProxy = new Varien_Io_File(); try { $ioProxy->open(array('path' => $readPath)); } catch (Exception $e) { $ioProxy->mkdir($readPath, 0755); $ioProxy->chmod($readPath, 0755); $ioProxy->open(array('path' => $readPath)); } if (!is_file($readPath . DS . ".htaccess")) { // Deny from reading in browser $ioProxy->write(".htaccess", "deny from all", 0644); } $list = $ioProxy->ls(Varien_Io_File::GREP_FILES); $fileExtension = constant($this->_itemObjectClass . "::BACKUP_EXTENSION"); foreach ($list as $entry) { if ($entry['filetype'] == $fileExtension) { $item = new $this->_itemObjectClass(); $item->load($entry['text'], $readPath); if ($this->_checkCondition($item)) { $this->addItem($item); } } } $this->_totalRecords = count($this->_items); if ($this->_totalRecords > 1) { usort($this->_items, array(&$this, 'compareByTypeOrDate')); } $this->_isLoaded = true; } return $this; }
/** * Write file to file system. * * @param null $destination * @param null $newName * @throws Exception */ public function save($destination = null, $newName = null) { Varien_Profiler::start(__METHOD__); if (isset($destination) && isset($newName)) { $fileName = $destination . "/" . $newName; } elseif (isset($destination) && !isset($newName)) { $info = pathinfo($destination); $fileName = $destination; $destination = $info['dirname']; } elseif (!isset($destination) && isset($newName)) { $fileName = $this->_fileSrcPath . "/" . $newName; } else { $fileName = $this->_fileSrcPath . $this->_fileSrcName; } $destinationDir = isset($destination) ? $destination : $this->_fileSrcPath; if (!is_writable($destinationDir)) { try { $io = new Varien_Io_File(); $io->mkdir($destination); } catch (Exception $e) { Varien_Profiler::stop(__METHOD__); throw new Exception("Unable to write into directory '{$destinationDir}'."); } } //set compression quality $this->getImageMagick()->setImageCompressionQuality($this->getQuality()); //remove all underlying information $this->getImageMagick()->stripImage(); //write to file system $this->getImageMagick()->writeImage($fileName); //clear data and free resources $this->getImageMagick()->clear(); $this->getImageMagick()->destroy(); Varien_Profiler::stop(__METHOD__); }
public function save($destination = null, $newName = null) { $fileName = !isset($destination) ? $this->_fileName : $destination; if (isset($destination) && isset($newName)) { $fileName = $destination . "/" . $fileName; } elseif (isset($destination) && !isset($newName)) { $info = pathinfo($destination); $fileName = $destination; $destination = $info['dirname']; } elseif (!isset($destination) && isset($newName)) { $fileName = $this->_fileSrcPath . "/" . $newName; } else { $fileName = $this->_fileSrcPath . $this->_fileSrcName; } $destinationDir = isset($destination) ? $destination : $this->_fileSrcPath; if (!is_writable($destinationDir)) { try { $io = new Varien_Io_File(); $io->mkdir($destination); } catch (Exception $e) { throw new Exception("Unable to write file into directory '{$destinationDir}'. Access forbidden."); } } // keep alpha transparency $isAlpha = false; $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha); if ($isAlpha) { $this->_fillBackgroundColor($this->_imageHandler); } call_user_func($this->_getCallback('output'), $this->_imageHandler, $fileName); }
/** * Write Sample Data to File. Store in folder: "skin/frontend/default/ves theme name/import/" */ public function writeSampleDataFile($importDir, $file_name, $content = "") { $file = new Varien_Io_File(); //Create import_ready folder $error = false; if (!file_exists($importDir)) { $importReadyDirResult = $file->mkdir($importDir); $error = false; if (!$importReadyDirResult) { //Handle error $error = true; Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('Can not create folder "%s".', $importDir)); } } else { $file->open(array('path' => $importDir)); } if (!$file->write($importDir . $file_name, $content)) { //Handle error $error = true; Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('Can not save import sample file "%s".', $file_name)); } if (!$error) { Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('cms')->__('Successfully, Stored sample data file "%s".', $file_name)); } return !$error; }
public function save($destination = null, $newName = null) { $fileName = !isset($destination) ? $this->_fileName : $destination; if (isset($destination) && isset($newName)) { $fileName = $destination . "/" . $newName; } elseif (isset($destination) && !isset($newName)) { $info = pathinfo($destination); $fileName = $destination; $destination = $info['dirname']; } elseif (!isset($destination) && isset($newName)) { $fileName = $this->_fileSrcPath . "/" . $newName; } else { $fileName = $this->_fileSrcPath . $this->_fileSrcName; } $destinationDir = isset($destination) ? $destination : $this->_fileSrcPath; if (!is_writable($destinationDir)) { try { $io = new Varien_Io_File(); $io->mkdir($destination); } catch (Exception $e) { throw new Exception("Unable to write file into directory '{$destinationDir}'. Access forbidden."); } } if (!$this->_resized) { // keep alpha transparency $isAlpha = false; $isTrueColor = false; $this->_getTransparency($this->_imageHandler, $this->_fileType, $isAlpha, $isTrueColor); if ($isAlpha) { if ($isTrueColor) { $newImage = imagecreatetruecolor($this->_imageSrcWidth, $this->_imageSrcHeight); } else { $newImage = imagecreate($this->_imageSrcWidth, $this->_imageSrcHeight); } $this->_fillBackgroundColor($newImage); imagecopy($newImage, $this->_imageHandler, 0, 0, 0, 0, $this->_imageSrcWidth, $this->_imageSrcHeight); $this->_imageHandler = $newImage; } } $functionParameters = array(); $functionParameters[] = $this->_imageHandler; $functionParameters[] = $fileName; // set quality param for JPG file type if (!is_null($this->quality()) && $this->_fileType == IMAGETYPE_JPEG) { $functionParameters[] = $this->quality(); } // set quality param for PNG file type if (!is_null($this->quality()) && $this->_fileType == IMAGETYPE_PNG) { $quality = round($this->quality() / 100 * 10); if ($quality < 1) { $quality = 1; } elseif ($quality > 10) { $quality = 10; } $quality = 10 - $quality; $functionParameters[] = $quality; } call_user_func_array($this->_getCallback('output'), $functionParameters); }
public function editadditionalinfoAction() { $data = $this->getRequest()->getPost(); if ($data) { $customerid = $data["customerid"]; $collection = Mage::getModel("additionalinfo/additionalinfofields")->getCollection()->addFieldToFilter("status", 1); $store_id = Mage::app()->getStore()->getId(); if (count($collection)) { foreach ($collection as $record) { $store = $record->getStore(); $store = explode(",", $store); if (in_array($store_id, $store)) { $additionaldatas = Mage::getModel("additionalinfo/additionalinfodata")->getCollection(); $additionaldatas->addFieldToFilter("customer_id", $customerid); $additionaldatas->addFieldToFilter("field_id", $record->getId()); $additionaldatas->addFieldToFilter("store", $store_id); $fieldid = 0; foreach ($additionaldatas as $additionaldata) { $fieldid = $additionaldata->getId(); } if ($record->getInputtype() == "file") { $upload_dir = Mage::getBaseDir() . "/media/customeradditionalinfo/" . $customerid . "/"; $file = new Varien_Io_File(); $file->mkdir($upload_dir); $new_file_name = $_FILES[$record->getInputname()]["name"]; $imagename = time() . $new_file_name; if ($new_file_name) { move_uploaded_file($_FILES[$record->getInputname()]["tmp_name"], $upload_dir . $new_file_name); $newfile = $upload_dir . $imagename; $oldfile = $upload_dir . $new_file_name; copy($oldfile, $newfile); unlink($oldfile); $addtionaldata = array("field_id" => $record->getId(), "value" => $imagename, "customer_id" => $customerid, "store" => $store_id); } else { $addtionaldata = array("field_id" => $record->getId(), "customer_id" => $customerid, "store" => $store_id); } } elseif ($record->getInputtype() == "multiselect") { $addtionaldata = array("field_id" => $record->getId(), "value" => implode($data[$record->getInputname()], ","), "customer_id" => $customerid, "store" => $store_id); } else { $addtionaldata = array("field_id" => $record->getId(), "value" => $data[$record->getInputname()], "customer_id" => $customerid, "store" => $store_id); } if ($fieldid) { $model = Mage::getModel("additionalinfo/additionalinfodata")->load($fieldid)->addData($addtionaldata); $model->setId($fieldid)->save(); $fieldid = 0; } else { Mage::getModel("additionalinfo/additionalinfodata")->setData($addtionaldata)->save(); } } } } $this->_getSession()->addSuccess(Mage::helper("additionalinfo")->__("Info was successfully updated")); } $this->_redirect("additionalinfo/index/additionalinfo/"); }
public function customersaveafter($observer) { $data = Mage::getSingleton("core/app")->getRequest()->getParams(); $store_id = $data["store"]; $customer = $observer->getCustomer(); if ($data) { $customerid = $customer->getId(); $collection = Mage::getModel("additionalinfo/additionalinfofields")->getCollection()->addFieldToFilter("status", 1); if (count($collection)) { foreach ($collection as $record) { $store = $record->getStore(); $store = explode(",", $store); if (in_array($store_id, $store)) { $additionaldatas = Mage::getModel("additionalinfo/additionalinfodata")->getCollection(); $additionaldatas->addFieldToFilter("customer_id", $customerid); $additionaldatas->addFieldToFilter("field_id", $record->getId()); $additionaldatas->addFieldToFilter("store", $store_id); $fieldid = 0; foreach ($additionaldatas as $additionaldata) { $fieldid = $additionaldata->getId(); } if ($record->getInputtype() == "file") { $upload_dir = Mage::getBaseDir() . "/media/customeradditionalinfo/" . $customerid . "/"; $file = new Varien_Io_File(); $file->mkdir($upload_dir); $new_file_name = $_FILES[$record->getInputname()]["name"]; $imagename = time() . $new_file_name; if ($new_file_name) { move_uploaded_file($_FILES[$record->getInputname()]["tmp_name"], $upload_dir . $new_file_name); $newfile = $upload_dir . $imagename; $oldfile = $upload_dir . $new_file_name; copy($oldfile, $newfile); unlink($oldfile); $addtionaldata = array("field_id" => $record->getId(), "value" => $imagename, "customer_id" => $customerid, "store" => $store_id); } else { $addtionaldata = array("field_id" => $record->getId(), "customer_id" => $customerid, "store" => $store_id); } } elseif ($record->getInputtype() == "multiselect") { $addtionaldata = array("field_id" => $record->getId(), "value" => implode($data[$record->getInputname()], ","), "customer_id" => $customerid, "store" => $store_id); } else { $addtionaldata = array("field_id" => $record->getId(), "value" => $data[$record->getInputname()], "customer_id" => $customerid, "store" => $store_id); } if ($fieldid) { $model = Mage::getModel("additionalinfo/additionalinfodata")->load($fieldid)->addData($addtionaldata); $model->setId($fieldid)->save(); $fieldid = 0; } else { Mage::getModel("additionalinfo/additionalinfodata")->setData($addtionaldata)->save(); } } } } } }
/** * Returns path to cash dir * * @param array $options * * @return string */ protected function _getCacheDir($options) { $cacheDir = isset($options['cache_dir']) ? $options['cache_dir'] : self::DEFAULT_CACHE_DIR; $cacheDir = SELENIUM_TESTS_BASEDIR . DIRECTORY_SEPARATOR . $cacheDir; if (!is_dir($cacheDir)) { $io = new Varien_Io_File(); if (!$io->mkdir($cacheDir, 0777, true)) { throw new Exception('Cache dir is not defined'); } } return $cacheDir; }
public function __construct() { parent::__construct(); $this->_baseDir = Mage::getBaseDir('export'); // check for valid base dir $ioProxy = new Varien_Io_File(); $ioProxy->mkdir($this->_baseDir); if (!is_file($this->_baseDir . DS . '.htaccess')) { $ioProxy->open(array('path' => $this->_baseDir)); $ioProxy->write('.htaccess', 'deny from all', 0644); } $this->setOrder('file_created', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setCollectRecursively(false); }
/** * Set collection specific parameters and make sure backups folder will exist */ public function __construct() { parent::__construct(); $this->_baseDir = Mage::getBaseDir('var') . DS . Ebizmarts_Mailchimp_Model_BulkSynchro::FLDR; // check for valid base dir $ioProxy = new Varien_Io_File(); $ioProxy->mkdir($this->_baseDir); if (!is_file($this->_baseDir . DS . '.htaccess')) { $ioProxy->open(array('path' => $this->_baseDir)); $ioProxy->write('.htaccess', 'deny from all', 0644); } // set collection specific params $this->setOrder('time', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setFilesFilter('/^[a-z0-9\\-\\_]+\\.' . preg_quote(Ebizmarts_Mailchimp_Model_BulkSynchro::FILE_EXTENSION . "." . Ebizmarts_Mailchimp_Model_BulkSynchro::BULK_EXTENSION, '/') . '$/')->setCollectRecursively(false); }
/** * Hijacks the normal GD2 save method to add ImageCDN hooks. Fails back to parent method * as appropriate. * * @param string $destination * @param string $newName * @return none */ public function save($destination = null, $newName = null) { $cds = Mage::Helper('imagecdn')->factory(); $compression = Mage::getStoreConfig('imagecdn/general/compression'); if ($cds->useCdn()) { $temp = tempnam(sys_get_temp_dir(), 'cds'); parent::save($temp); //Compress images? if ($this->_fileType == IMAGETYPE_JPEG && $compression > 0) { $convert = round((9 - $compression) * (100 / 8)); //convert to imagejpeg's scale call_user_func('imagejpeg', $this->_imageHandler, $temp, $convert); } elseif ($this->_fileType == IMAGETYPE_PNG && $compression > 0) { $convert = round(($compression - 1) * (9 / 8)); //convert to imagepng's scale call_user_func('imagepng', $this->_imageHandler, $temp, $convert); } $filename = !isset($destination) ? $this->_fileName : $destination; if (isset($destination) && isset($newName)) { $filename = $destination . "/" . $filename; } elseif (isset($destination) && !isset($newName)) { $info = pathinfo($destination); $filename = $destination; $destination = $info['dirname']; } elseif (!isset($destination) && isset($newName)) { $filename = $this->_fileSrcPath . "/" . $newName; } else { $filename = $this->_fileSrcPath . $this->_fileSrcName; } if ($cds->save($filename, $temp)) { @unlink($temp); } else { if (!is_writable($destination)) { try { $io = new Varien_Io_File(); $io->mkdir($destination); } catch (Exception $e) { throw new Exception("Unable to write file into directory '{$destinationDir}'. Access forbidden."); } } @rename($temp, $filename); @chmod($filename, 0644); } } else { return parent::save($destination, $newName); } }
/** * * Move option image from Temp directory to Media directory * * @param string $fileName * @param int $attributeId * @param int $optionId * @return string */ public function moveImageFromTemp($fileName, $attributeId, $optionId) { $ioObject = new Varien_Io_File(); $targetDirectory = $this->_optionImageBasePath . $attributeId . DS . $optionId; try { $ioObject->rmdir($targetDirectory, true); $ioObject->mkdir($targetDirectory, 0777, true); $ioObject->open(array('path' => $targetDirectory)); } catch (Exception $e) { return false; } $fileName = trim($fileName, '.tmp'); $targetFile = Varien_File_Uploader::getNewFileName($fileName); $path = $targetDirectory . DS . $targetFile; $ioObject->mv(Mage::getSingleton('catalog/product_media_config')->getTmpMediaPath($fileName), $path); return $targetFile; }
/** * 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(); } }
/** * Move file from tmp path to base path * * @param string $baseTmpPath * @param string $basePath * @param string $file * @return string */ protected function _moveFileFromTmp($baseTmpPath, $basePath, $file) { $ioObject = new Varien_Io_File(); $destDirectory = dirname($this->getFilePath($basePath, $file)); try { $ioObject->open(array('path' => $destDirectory)); } catch (Exception $e) { $ioObject->mkdir($destDirectory, 0777, true); $ioObject->open(array('path' => $destDirectory)); } if (strrpos($file, '.tmp') == strlen($file) - 4) { $file = substr($file, 0, strlen($file) - 4); } $destFile = dirname($file) . $ioObject->dirsep() . Varien_File_Uploader::getNewFileName($this->getFilePath($basePath, $file)); $result = $ioObject->mv($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile)); return str_replace($ioObject->dirsep(), '/', $destFile); }
public function moveImageFromTmp($file) { $ioObject = new Varien_Io_File(); $destDirectory = Mage::getBaseDir('media') . '/option_image'; try { $ioObject->open(array('path' => $destDirectory)); } catch (Exception $e) { $ioObject->mkdir($destDirectory, 0777, true); $ioObject->open(array('path' => $destDirectory)); } if (strrpos($file, '.tmp') == strlen($file) - 4) { $file = substr($file, 0, strlen($file) - 4); } $destFile = Varien_File_Uploader::getNewFileName($file); $dest = $destDirectory . '/' . $destFile; $ioObject->mv($this->_getMadiaConfig()->getTmpMediaPath($file), $dest); return $destFile; }
public function save($destination = null, $newName = null) { $fileName = !isset($destination) ? $this->_fileName : $destination; if (isset($destination) && isset($newName)) { $fileName = $destination . "/" . $fileName; } elseif (isset($destination) && !isset($newName)) { $info = pathinfo($destination); $fileName = $destination; $destination = $info['dirname']; } elseif (!isset($destination) && isset($newName)) { $fileName = $this->_fileSrcPath . "/" . $newName; } else { $fileName = $this->_fileSrcPath . $this->_fileSrcName; } $destinationDir = isset($destination) ? $destination : $this->_fileSrcPath; if (!is_writable($destinationDir)) { try { $io = new Varien_Io_File(); $io->mkdir($destination); } catch (Exception $e) { throw new Exception("Unable to write file into directory '{$destinationDir}'. Access forbidden."); } } switch ($this->_fileType) { case IMAGETYPE_GIF: imagegif($this->_imageHandler, $fileName); break; case IMAGETYPE_JPEG: imagejpeg($this->_imageHandler, $fileName); break; case IMAGETYPE_PNG: imagepng($this->_imageHandler, $fileName); break; case IMAGETYPE_XBM: imagexbm($this->_imageHandler, $fileName); break; case IMAGETYPE_WBMP: imagewbmp($this->_imageHandler, $fileName); break; default: throw new Exception("Unsupported image format."); break; } }
/** * Set collection specific parameters and make sure backups folder will exist */ public function __construct() { parent::__construct(); $this->_baseDir = Mage::getBaseDir('var') . DS . 'backups'; // check for valid base dir $ioProxy = new Varien_Io_File(); $ioProxy->mkdir($this->_baseDir); if (!is_file($this->_baseDir . DS . '.htaccess')) { $ioProxy->open(array('path' => $this->_baseDir)); $ioProxy->write('.htaccess', 'deny from all', 0644); } // set collection specific params $extensions = Mage::helper('backup')->getExtensions(); foreach ($extensions as $key => $value) { $extensions[] = '(' . preg_quote($value, '/') . ')'; } $extensions = implode('|', $extensions); $this->setOrder('time', self::SORT_ORDER_DESC)->addTargetDir($this->_baseDir)->setFilesFilter('/^[a-z0-9\\-\\_]+\\.' . $extensions . '$/')->setCollectRecursively(false); }
/** * Perform snapshot */ function _snapshot() { # Check to make sure Magento is installed if (!Mage::isInstalled()) { echo "Application is not installed yet, please complete install wizard first."; exit; } # Initialize configuration values $connection = Mage::getConfig()->getNode('global/resources/default_setup/connection'); $rootpath = $this->_getRootPath(); $snapshot = $rootpath . 'snapshot'; # Create the snapshot directory if not exists $io = new Varien_Io_File(); $io->mkdir($snapshot); # Create the media archive exec("tar -chz -C \"{$rootpath}\" -f \"{$snapshot}/media.tgz\" media"); # Dump the database exec("mysqldump -h {$connection->host} -u {$connection->username} --password={$connection->password} {$connection->dbname} | gzip > \"{$snapshot}/{$connection->dbname}.sql.gz\""); }
protected function _moveFileFromTmp($baseTmpPath, $basePath, $file) { $ioObject = new Varien_Io_File(); $destDirectory = dirname($this->getFilePath($basePath, $file)); try { $ioObject->open(array('path' => $destDirectory)); } catch (Exception $e) { $ioObject->mkdir($destDirectory, 0777, true); $ioObject->open(array('path' => $destDirectory)); } if (strrpos($file, '.tmp') == strlen($file) - 4) { $file = substr($file, 0, strlen($file) - 4); } // DO NOT rename file if it exists. Overwrite it. Custumer request in ticket#2012120510000418 — Magento is losing connection to files $destFile = $file; //$destFile = dirname($file) . $ioObject->dirsep() // . Mage_Core_Model_File_Uploader::getNewFileName($this->getFilePath($basePath, $file)); //die ("destFile: $destFile<br>file: $file<br>basePath: $basePath<br>dirname: ".dirname($file)); Mage::helper('core/file_storage_database')->copyFile($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile)); $result = $ioObject->mv($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $destFile)); return str_replace($ioObject->dirsep(), '/', $destFile); }
/** * Return path of the current selected directory or root directory for startup * Try to create target directory if it doesn't exist * * @throws Mage_Core_Exception * @return string */ public function getCurrentPath() { if (!$this->_currentPath) { $currentPath = realpath($this->getStorageRoot()); $node = $this->_getRequest()->getParam($this->getTreeNodeName()); if ($node) { $path = realpath($this->convertIdToPath($node)); if (is_dir($path) && false !== stripos($path, $currentPath)) { $currentPath = $path; } } $io = new Varien_Io_File(); if (!$io->isWriteable($currentPath) && !$io->mkdir($currentPath)) { $message = Mage::helper('cms')->__('The directory %s is not writable by server.', $currentPath); Mage::throwException($message); } $this->_currentPath = $currentPath; } return $this->_currentPath; }
/** * Create thumbnail for image and save it to thumbnails directory * * @param string $source Image path to be resized * @param bool $keepRation Keep aspect ratio or not * @return bool|string Resized filepath or false if errors were occurred */ public function resizeFile($source, $keepRation = true) { if (!is_file($source) || !is_readable($source)) { return false; } $targetDir = $this->getThumbsPath($source); $io = new Varien_Io_File(); if (!$io->isWriteable($targetDir)) { $io->mkdir($targetDir); } if (!$io->isWriteable($targetDir)) { return false; } $image = Varien_Image_Adapter::factory('GD2'); $image->open($source); $width = $this->getConfigData('resize_width'); $height = $this->getConfigData('resize_height'); $image->keepAspectRatio($keepRation); $image->resize($width, $height); $dest = $targetDir . DS . pathinfo($source, PATHINFO_BASENAME); $image->save($dest); if (is_file($dest)) { return $dest; } return false; }
/** * Move image from temporary directory to normal * * @param string $file * @return string */ protected function _moveImageFromTmp($file) { $ioObject = new Varien_Io_File(); $destDirectory = dirname($this->_getConfig()->getMediaPath($file)); try { $ioObject->open(array('path' => $destDirectory)); } catch (Exception $e) { $ioObject->mkdir($destDirectory, 0777, true); $ioObject->open(array('path' => $destDirectory)); } if (strrpos($file, '.tmp') == strlen($file) - 4) { $file = substr($file, 0, strlen($file) - 4); } $destFile = $this->_getUniqueFileName($file, $ioObject->dirsep()); /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */ $storageHelper = Mage::helper('core/file_storage_database'); if ($storageHelper->checkDbUsage()) { $storageHelper->renameFile($this->_getConfig()->getTmpMediaShortUrl($file), $this->_getConfig()->getMediaShortUrl($destFile)); $ioObject->rm($this->_getConfig()->getTmpMediaPath($file)); $ioObject->rm($this->_getConfig()->getMediaPath($destFile)); } else { $ioObject->mv($this->_getConfig()->getTmpMediaPath($file), $this->_getConfig()->getMediaPath($destFile)); } return str_replace($ioObject->dirsep(), '/', $destFile); }
/** * Create Writeable directory if it doesn't exist * * @param string Absolute directory path * @return void */ protected function _createWriteableDir($path) { $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)); } }
public function saveBulkUploadFiles($filesDataArray) { $csvFilePath = $homeFolder = $imageFilePath = ''; /** Get Customer Id */ $sellerId = Mage::getSingleton('customer/session')->getCustomer()->getId(); /** * Getting Current Time */ $currentDateTime = date("Ymd_His", Mage::getModel('core/date')->timestamp(time())); foreach ($filesDataArray as $key => $value) { /** * Initilize file name */ $filename = $key; /** * Upload csv file */ if ($key == 'bulk-product-upload-csv-file' && isset($filesDataArray[$filename]['name']) && file_exists($filesDataArray[$filename]['tmp_name'])) { $csvFilePath = ''; $csvFilePath = array(); $uploader = new Varien_File_Uploader($filename); $uploader->setAllowedExtensions(array('csv')); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $path = Mage::getBaseDir('media') . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'csv' . DS; $uploader->save($path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.csv'); $csvFilePath = $path . $uploader->getUploadedFileName(); } /** * Upload csv image */ if ($key == 'bulk-product-upload-image-file' && isset($filesDataArray[$filename]['name']) && file_exists($filesDataArray[$filename]['tmp_name'])) { $uploader = new Varien_File_Uploader($filename); $uploader->setAllowedExtensions(array('zip')); $uploader->setAllowRenameFiles(true); $uploader->setFilesDispersion(false); $path = Mage::getBaseDir('media') . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'image' . DS; /** * Uploader save */ $uploader->save($path, 'seller_' . $sellerId . '_date_' . $currentDateTime . '.zip'); $imageFilePath = $path . $uploader->getUploadedFileName(); $ZipFileName = $imageFilePath; $homeFolder = Mage::getBaseDir('media') . DS . 'marketplace' . DS . 'bulk' . DS . 'product' . DS . 'image' . DS . 'seller_' . $sellerId . '_date_' . $currentDateTime; /** * New Varien File */ $file = new Varien_Io_File(); /** * Make Directory */ $file->mkdir($homeFolder); Mage::helper('marketplace/product')->exportZipFile($ZipFileName, $homeFolder); } } /** * Conver csv file path */ $productData = Mage::helper('marketplace/product')->convertCsvFileToUploadArray($csvFilePath); $this->bulkproductuploadfuncationality($imageFilePath, $productData, $homeFolder, $csvFilePath); return true; }
public function saveAction() { if ($data = $this->getRequest()->getPost()) { if ($data['filename']['delete'] == 1) { $data['filename'] = ''; } elseif (is_array($data['filename'])) { $data['filename'] = $data['filename']['value']; } $file = new Varien_Io_File(); $baseDir = Mage::getBaseDir(); $mediaDir = $baseDir . DS . 'media'; $imageDir = $mediaDir . DS . 'bsimages'; $thumbimageyDir = $mediaDir . DS . 'bsimages' . DS . 'thumbs'; if (!is_dir($imageDir)) { $imageDirResult = $file->mkdir($imageDir, 0777); } if (!is_dir($thumbimageyDir)) { $thumbimageDirResult = $file->mkdir($thumbimageyDir, 0777); } //$thumbimageDirResult = $file->mkdir($thumbimageyDir); if (isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') { try { /* Starting upload */ $uploader = new Varien_File_Uploader('filename'); // Any extention would work $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png')); $uploader->setAllowRenameFiles(false); // Set the file upload mode // false -> get the file directly in the specified folder // true -> get the file in the product like folders // (file.jpg will go in something like /media/f/i/file.jpg) $uploader->setFilesDispersion(false); // We set media as the upload dir //$path = Mage::getBaseDir('media') . DS ; $path = $imageDir . DS; $result = $uploader->save($path, $_FILES['filename']['name']); ############################################################################### // actual path of image $imageUrl = Mage::getBaseDir('media') . DS . "bsimages" . DS . $_FILES['filename']['name']; // path of the resized image to be saved // here, the resized image is saved in media/resized folder $imageResized = Mage::getBaseDir('media') . DS . "bsimages" . DS . "thumbs" . DS . $_FILES['filename']['name']; // resize image only if the image file exists and the resized image file doesn't exist // the image is resized proportionally with the width/height 135px if (!file_exists($imageResized) && file_exists($imageUrl)) { $imageObj = new Varien_Image($imageUrl); $imageObj->constrainOnly(TRUE); $imageObj->keepAspectRatio(FALSE); $imageObj->keepFrame(FALSE); $imageObj->quality(100); $imageObj->resize(80, 50); $imageObj->save($imageResized); } ################################################################################# $data['filename'] = $result['file']; } catch (Exception $e) { $data['filename'] = $_FILES['filename']['name']; } } $model = Mage::getModel('imageslider/imageslider'); $model->setData($data)->setId($this->getRequest()->getParam('id')); try { if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) { $model->setCreatedTime(now())->setUpdateTime(now()); } else { $model->setUpdateTime(now()); } //$model->setStores(implode(',',$data['stores'])); /*if (isset($data['category_ids'])){ $model->setCategories(implode(',',array_unique(explode(',',$data['category_ids'])))); }*/ $model->save(); Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('imageslider')->__('Banner Image was successfully saved')); Mage::getSingleton('adminhtml/session')->setFormData(false); if ($this->getRequest()->getParam('back')) { $this->_redirect('*/*/edit', array('id' => $model->getId())); return; } $this->_redirect('*/*/'); return; } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($data); $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id'))); return; } } Mage::getSingleton('adminhtml/session')->addError(Mage::helper('imageslider')->__('Unable to save Banner Image')); $this->_redirect('*/*/'); }
protected function initSavePath() { $path = dirname($this->getFeedPath()); $ioAdapter = new Varien_Io_File(); if (!is_dir($path)) { $ioAdapter->mkdir($path); if (!is_dir($path)) { Mage::throwException(sprintf('Not enough permissions, can\'t create dir [%s].', $path)); } } }
/** * Process File Queue * @return Mage_Catalog_Model_Product_Type_Abstract */ public function processFileQueue() { if (empty($this->_fileQueue)) { return $this; } foreach ($this->_fileQueue as &$queueOptions) { if (isset($queueOptions['operation']) && ($operation = $queueOptions['operation'])) { switch ($operation) { case 'receive_uploaded_file': $src = isset($queueOptions['src_name']) ? $queueOptions['src_name'] : ''; $dst = isset($queueOptions['dst_name']) ? $queueOptions['dst_name'] : ''; /** @var $uploader Zend_File_Transfer_Adapter_Http */ $uploader = isset($queueOptions['uploader']) ? $queueOptions['uploader'] : null; $path = dirname($dst); $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)); } $uploader->setDestination($path); if (empty($src) || empty($dst) || !$uploader->receive($src)) { /** * @todo: show invalid option */ if (isset($queueOptions['option'])) { $queueOptions['option']->setIsValid(false); } Mage::throwException(Mage::helper('catalog')->__("File upload failed")); } Mage::helper('core/file_storage_database')->saveFile($dst); break; case 'move_uploaded_file': $src = $queueOptions['src_name']; $dst = $queueOptions['dst_name']; move_uploaded_file($src, $dst); Mage::helper('core/file_storage_database')->saveFile($dst); break; default: break; } } $queueOptions = null; } return $this; }
protected function initSavePath() { if (!$this->isAlternateFeedPath()) { $path = dirname($this->getFeedPath()); $ioAdapter = new Varien_Io_File(); if (!is_dir($path)) { $ioAdapter->mkdir($path); if (!is_dir($path)) { Mage::throwException(sprintf('Not enough permissions, can\'t create dir [%s].', $path)); } } } else { if ($this->_setAlternateRealPath() === false) { Mage::throwException(sprintf('Can\'t save feed. Dir [%s] doesn\'t exist.', rtrim(Mage::getConfig()->getOptions()->getDir('base'), DS) . DS . rtrim(trim($this->getConfigVar('alternate_feed_dir')), DS))); } else { if (!is_writable(dirname($this->getFeedPath()))) { Mage::throwException(sprintf('Can\'t save feed. Dir [%s] hasn\'t enough permissions.', dirname($this->getFeedPath()))); } } } }
public function saveAction() { $action = ""; if ($data = $this->getRequest()->getPost()) { $action = $this->getRequest()->getParam('action'); $themecontrol = isset($data['themecontrol']) ? $data['themecontrol'] : ''; $internal_modules = isset($data['module']) ? $data['module'] : array(); if (isset($_FILES['bg_image']['name']) && $_FILES['bg_image']['name'] != '') { try { /* Starting upload */ $uploader = new Varien_File_Uploader('bg_image'); // Any extention would work $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png')); $uploader->setAllowRenameFiles(false); // Set the file upload mode // false -> get the file directly in the specified folder // true -> get the file in the product like folders // (file.jpg will go in something like /media/f/i/file.jpg) $uploader->setFilesDispersion(false); // We set media as the upload dir $path = Mage::getBaseDir('media') . '/ves_tempcp/upload/'; $uploader->save($path, $_FILES['bg_image']['name']); } catch (Exception $e) { } //this way the name is saved in DB $themecontrol['bg_image'] = 'ves_tempcp/upload/' . $_FILES['bg_image']['name']; } elseif (isset($themecontrol['bg_image']) && strpos($themecontrol['bg_image'], "ves_tempcp/upload/") === false) { $themecontrol['bg_image'] = "ves_tempcp/upload/" . $themecontrol['bg_image']; } elseif (isset($data['delete_bg_image']) && $data['delete_bg_image']) { if (file_exists(Mage::getBaseDir('media') . "/" . $themecontrol['bg_image'])) { @unlink(Mage::getBaseDir('media') . "/" . $themecontrol['bg_image']); } $themecontrol['bg_image'] = ""; } if (isset($themecontrol['custom_logo']) && strpos($themecontrol['custom_logo'], "images/") === false) { $themecontrol['custom_logo'] = "images/" . $themecontrol['custom_logo']; } elseif (isset($data['delete_custom_logo']) && $data['delete_custom_logo']) { if (file_exists(Mage::getBaseDir('skin') . "/frontend/" . $theme_group . "/images/" . $themecontrol['custom_logo'])) { @unlink(Mage::getBaseDir('skin') . "/frontend/" . $theme_group . "/images/" . $themecontrol['custom_logo']); } $themecontrol['custom_logo'] = ""; } if (isset($themecontrol['custom_logo_small']) && strpos($themecontrol['custom_logo_small'], "images/") === false) { $themecontrol['custom_logo_small'] = "images/" . $themecontrol['custom_logo_small']; } elseif (isset($data['delete_custom_logo_small']) && $data['delete_custom_logo_small']) { if (file_exists(Mage::getBaseDir('skin') . "/frontend/" . $theme_group . "/images/" . $themecontrol['custom_logo_small'])) { @unlink(Mage::getBaseDir('skin') . "/frontend/" . $theme_group . "/images/" . $themecontrol['custom_logo_small']); } $themecontrol['custom_logo_small'] = ""; } $data = array(); $custom_css = ""; if (isset($themecontrol['custom_css'])) { $custom_css = trim($themecontrol['custom_css']); unset($themecontrol['custom_css']); } $theme_id = $this->getRequest()->getParam('id'); $data['params'] = base64_encode(serialize($themecontrol)); $data['group'] = isset($themecontrol['default_theme']) ? $themecontrol['default_theme'] : 'ves default theme'; $data['is_default'] = 1; $data['stores'] = $this->getRequest()->getParam('stores'); $_model = Mage::getModel('ves_tempcp/theme')->load($theme_id); /* if(empty($data['theme_id']) && $_model->checkExistsByGroup($data['group'])){ Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('The Theme is exist, you can not create a same theme!')); */ // $this->_redirect('*/*/'); /* return; }*/ $_model->setData($data); if ($theme_id) { $_model->setId($theme_id); } try { $_model->save(); /*Save custom css*/ if (!empty($custom_css)) { $theme_group = $_model->getGroup(); $tmp_theme = explode("/", $theme_group); if (count($tmp_theme) == 1) { $theme_group = "default/" . $theme_group; } $custom_css_path = Mage::getBaseDir('skin') . "/frontend/" . $theme_group . "/css/local/"; if (!file_exists($custom_css_path)) { $file = new Varien_Io_File(); $file->mkdir($custom_css_path); $file->close(); } Mage::helper("ves_tempcp")->writeToCache($custom_css_path, "custom", $custom_css); } /*End save custom css*/ /*Save internal modules*/ $theme_id = $_model->getId(); Mage::getModel('ves_tempcp/module')->cleanModules($theme_id); if (!empty($internal_modules)) { foreach ($internal_modules as $position => $modules) { if ($modules) { foreach ($modules as $key => $module) { $_module_model = Mage::getModel('ves_tempcp/module'); $_data = array(); $_data['theme_id'] = $theme_id; $_data['module_name'] = trim($key); $_data['module_title'] = trim($module['module_title']); $_data['module_data'] = $module['module_data']; $_data['block_id'] = $module['block_id']; $_data['layout'] = implode(",", $module['layout']); $_data['status'] = $module['status']; $_data['sort_order'] = $module['sort_order']; $_data['position'] = isset($module['position']) ? trim($module['position']) : trim($position); $_module_model->setData($_data); if ($module_id = $_module_model->getModuleId($key)) { $_module_model->setId($module_id); } try { $_module_model->save(); } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($_data); } } } } } /*End Save internal modules*/ Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('ves_tempcp')->__('Theme was successfully saved')); Mage::getSingleton('adminhtml/session')->setFormData(false); if ($this->getRequest()->getParam('back')) { return; } if ($action == "save_stay") { $this->_redirect('*/*/edit', array('id' => $theme_id)); } else { $this->_redirect('*/*/'); } return; } catch (Exception $e) { Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); Mage::getSingleton('adminhtml/session')->setFormData($data); return; } } Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ves_tempcp')->__('Unable to find theme to save')); $this->_redirect('*/*/'); }