本文整理汇总了PHP中Varien_File_Uploader::getDispretionPath方法的典型用法代码示例。如果您正苦于以下问题:PHP Varien_File_Uploader::getDispretionPath方法的具体用法?PHP Varien_File_Uploader::getDispretionPath怎么用?PHP Varien_File_Uploader::getDispretionPath使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Varien_File_Uploader
的用法示例。
在下文中一共展示了Varien_File_Uploader::getDispretionPath方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _moveImageFromTmp
protected function _moveImageFromTmp($file)
{
if (!Mage::helper('magefm_cdn')->isEnabled()) {
return parent::_moveImageFromTmp($file);
}
$ioObject = new Varien_Io_File();
if (strrpos($file, '.tmp') == strlen($file) - 4) {
$file = substr($file, 0, strlen($file) - 4);
}
$dispretionPath = Varien_File_Uploader::getDispretionPath($file);
$tmpFile = $this->_getConfig()->getBaseTmpMediaPathAddition() . $dispretionPath . '/' . $file;
$file = $this->_getUniqueFileName($this->_getConfig()->getBaseMediaPathAddition() . $dispretionPath, $file);
$newPath = $this->_getConfig()->getBaseMediaPathAddition() . $dispretionPath . '/' . $file;
$storageHelper = Mage::helper('magefm_cdn/storage');
if (!$storageHelper->renameFile($tmpFile, $newPath)) {
throw new Exception('Error while renaming image.');
}
return $dispretionPath . '/' . $file;
}
示例2: saveProductTabData
/**
* This method will run when the product is saved from the Magento Admin
* Use this function to update the product model, process the
* data or anything you like
*
* @param Varien_Event_Observer $observer
*/
public function saveProductTabData(Varien_Event_Observer $observer)
{
if (self::$_singletonFlag) {
return;
}
self::$_singletonFlag = true;
$product = $observer->getEvent()->getProduct();
$storeId = $product->getStoreId();
try {
$files = $this->_getRequest()->getPost('infofile_file');
$names = $this->_getRequest()->getPost('infofile_name');
$labels = $this->_getRequest()->getPost('infofile_label');
for ($i = 1; $i < count($files); $i++) { // Skip $i=0, because it contains the template!
$fileName = $files[$i];
$originalName = $names[$i];
// move the file from the tmp media folder to the real folder
$currentFile = Mage::getSingleton('catalog/product_media_config')->getTmpMediaPath($fileName);
$dispretionPath = Varien_File_Uploader::getDispretionPath($originalName);
$destinationFolder = Mage::getSingleton('catalog/product_media_config')->getMediaPath($dispretionPath);
$destFile = Mage::getSingleton('catalog/product_media_config')->getMediaPath($dispretionPath . DS . $originalName);
if (!(@is_dir($destinationFolder) || @mkdir($destinationFolder, 0777, true))) {
throw new Exception("Unable to create directory '{$destinationFolder}'.");
}
// adds a counter to the filename
$destFilename = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($destFile);
$destFile = Mage::getSingleton('catalog/product_media_config')
->getMediaPath($destFilename);
rename($currentFile, $destFile);
// add entry in the database
$model = Mage::getModel('n98infofiles/file');
$model->setFilename($destFilename);
$label = trim($labels[$i]);
if (empty($label)) {
$label = $originalName;
}
$model->setLabel($label);
$model->setProductId($product->getId());
$model->setStoreId($storeId);
$model->save();
}
// process existing files
$exLabels = $this->_getRequest()->getPost('infofile_existing_label');
$exRemove = $this->_getRequest()->getPost('infofile_existing_remove');
if (count($exRemove) > 0) {
foreach ($exLabels as $id => $label) {
$fileModel = Mage::getModel('n98infofiles/file');
$fileModel->load($id);
if (isset($exRemove[$id])) {
// delete file from disk
$filename = Mage::getSingleton('catalog/product_media_config')->getMediaPath($fileModel->getFilename());
unlink($filename);
// delete record
$fileModel->delete();
continue;
}
$fileModel->setLabel($label);
$fileModel->save();
}
}
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
示例3: saveAction
public function saveAction()
{
if ($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('magenotification/feedback');
$model->load($this->getRequest()->getParam('id'));
$model->addData($data);
$helper = Mage::helper('magenotification');
//upload files
$attachedfiles = array();
if (count($_FILES)) {
$path = Mage::getBaseDir('media') . DS . 'feedback';
foreach ($_FILES as $fileId => $file) {
if (!$file['name']) {
continue;
}
$uploader = new Varien_File_Uploader($fileId);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(true);
$uploader->save($path, $file['name']);
$attachedfiles[] = $uploader->getDispretionPath($file['name']) . DS . $file['name'];
}
}
if (count($attachedfiles)) {
$attachedfiles = implode(',', $attachedfiles);
$attachedfiles = str_replace(DS, '/', $attachedfiles);
$data['file'] = $attachedfiles;
}
//save message
$message = Mage::getModel('magenotification/feedbackmessage');
if ($model->getId() && isset($data['message']) && $data['message']) {
$message->setData($data)->setFeedbackId($model->getId())->setFeedbackCode($model->getCode())->setPostedTime(now())->setIsCustomer(1)->setIsSent(2)->setUser(Mage::getSingleton('admin/session')->getUser()->getUsername());
unset($data['file']);
}
$model->addData($data);
$model->setExtensionVersion($helper->getExtensionVersion($model->getExtension()));
if (!$model->getId()) {
$code = strtoupper($helper->getDomain(Mage::getBaseUrl())) . time();
$code = str_replace('WWW.', '', $code);
$model->setCode($code);
}
if ($model->getCreated() == NULL || $model->getUpdated() == NULL) {
$model->setCreated(now());
}
// post feedback
if (!$model->getId() || $model->getId() && $model->getMessage()) {
try {
Mage::helper('magenotification/feedback')->postFeedback($model);
$model->setIsSent(1);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$model->setIsSent(2);
}
}
// post message
if ($message->getData()) {
try {
Mage::helper('magenotification/feedback')->postMessage($message);
$message->setIsSent(1);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$message->setIsSent(2);
}
}
try {
$model->save();
//save message
if ($message->getData()) {
$message->save();
}
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('magenotification')->__('Item 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('magenotification')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
示例4: addImage
/**
* 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);
if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), array('jpg', 'jpeg', 'gif', 'png'))) {
Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.'));
}
$fileName = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = Varien_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));
if ($move) {
$ioAdapter->mv($file, $this->_getConfig()->getTmpMediaPath($fileName));
} else {
$ioAdapter->cp($file, $this->_getConfig()->getTmpMediaPath($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;
}
示例5: validateUserValue
/**
* Validate user input for option
*
* @throws Mage_Core_Exception
* @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
* @return Mage_Catalog_Model_Product_Option_Type_Default
*/
public function validateUserValue($values)
{
AO::getSingleton('checkout/session')->setUseNotice(false);
$this->setIsValid(true);
$option = $this->getOption();
// Set option value from request (Admin/Front reorders)
if (isset($values[$option->getId()]) && is_array($values[$option->getId()])) {
if (isset($values[$option->getId()]['order_path'])) {
$orderFileFullPath = AO::getBaseDir() . $values[$option->getId()]['order_path'];
} else {
$this->setUserValue(null);
return $this;
}
$ok = is_file($orderFileFullPath) && is_readable($orderFileFullPath) && isset($values[$option->getId()]['secret_key']) && substr(md5(file_get_contents($orderFileFullPath)), 0, 20) == $values[$option->getId()]['secret_key'];
$this->setUserValue($ok ? $values[$option->getId()] : null);
return $this;
} elseif ($this->getProduct()->getSkipCheckRequiredOption()) {
$this->setUserValue(null);
return $this;
}
/**
* Upload init
*/
$upload = new Zend_File_Transfer_Adapter_Http();
$file = 'options_' . $option->getId() . '_file';
try {
$runValidation = $option->getIsRequire() || $upload->isUploaded($file);
if (!$runValidation) {
$this->setUserValue(null);
return $this;
}
$fileInfo = $upload->getFileInfo($file);
$fileInfo = $fileInfo[$file];
} catch (Exception $e) {
$this->setIsValid(false);
AO::throwException(AO::helper('catalog')->__("Files upload failed"));
}
/**
* 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);
}
}
/**
* Upload process
*/
$this->_initFilesystem();
if ($upload->isUploaded($file) && $upload->isValid($file)) {
$extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
$fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
$dispersion = Varien_File_Uploader::getDispretionPath($fileName);
$filePath = $dispersion;
$destination = $this->getQuoteTargetDir() . $filePath;
$this->_createWriteableDir($destination);
$upload->setDestination($destination);
$fileHash = md5(file_get_contents($fileInfo['tmp_name']));
$filePath .= DS . $fileHash . '.' . $extension;
$fileFullPath = $this->getQuoteTargetDir() . $filePath;
$upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
if (!$upload->receive()) {
$this->setIsValid(false);
AO::throwException(AO::helper('catalog')->__("File upload failed"));
}
$_imageSize = @getimagesize($fileFullPath);
if (is_array($_imageSize) && count($_imageSize) > 0) {
$_width = $_imageSize[0];
$_height = $_imageSize[1];
} else {
$_width = 0;
$_height = 0;
}
$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 = array();
foreach ($upload->getErrors() as $errorCode) {
//.........这里部分代码省略.........
示例6: _processDownloadableProduct
protected function _processDownloadableProduct($product, &$importData)
{
// comment if --------------------------
//if ($new) {
$filearrayforimports = array();
$downloadableitems = array();
$downloadableitemsoptionscount = 0;
//THIS IS FOR DOWNLOADABLE OPTIONS
$commadelimiteddata = explode('|', $importData['downloadable_options']);
foreach ($commadelimiteddata as $data) {
$configBundleOptionsCodes = $this->userCSVDataAsArray($data);
$downloadableitems['link'][$downloadableitemsoptionscount]['is_delete'] = 0;
$downloadableitems['link'][$downloadableitemsoptionscount]['link_id'] = 0;
$downloadableitems['link'][$downloadableitemsoptionscount]['title'] = $configBundleOptionsCodes[0];
$downloadableitems['link'][$downloadableitemsoptionscount]['price'] = $configBundleOptionsCodes[1];
$downloadableitems['link'][$downloadableitemsoptionscount]['number_of_downloads'] = $configBundleOptionsCodes[2];
$downloadableitems['link'][$downloadableitemsoptionscount]['is_shareable'] = 2;
if (isset($configBundleOptionsCodes[5])) {
#$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '[]', 'type' => 'url', 'url' => '' . $configBundleOptionsCodes[5] . '');
} else {
$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
}
$downloadableitems['link'][$downloadableitemsoptionscount]['file'] = '';
$downloadableitems['link'][$downloadableitemsoptionscount]['type'] = $configBundleOptionsCodes[3];
#$downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
if ($configBundleOptionsCodes[3] == "file") {
#$filearrayforimport = array('file' => 'media/import/mypdf.pdf' , 'name' => 'asdad.txt', 'size' => '316', 'status' => 'old');
#$document_directory = Mage :: getBaseDir( 'media' ) . DS . 'import' . DS;
#echo "DIRECTORY: " . $document_directory;
#$filearrayforimport = '[{"file": "/home/discou33/public_html/media/import/mypdf.pdf", "name": "mypdf.pdf", "status": "new"}]';
#$filearrayforimport = '[{"file": "mypdf.pdf", "name": "quickstart.pdf", "size": 324075, "status": "new"}]';
#$product->setLinksPurchasedSeparately(0);
#$product->setLinksPurchasedSeparately(false);
#$files = Zend_Json::decode($filearrayforimport);
#$files = "mypdf.pdf";
//--------------- upload file ------------------
$document_directory = Mage::getBaseDir('media') . DS . 'import' . DS . $this->__vendorName . DS;
$files = '' . $configBundleOptionsCodes[4] . '';
$link_file = $document_directory . $files;
$file = realpath($link_file);
if (!$file || !file_exists($file)) {
Mage::throwException(Mage::helper('catalog')->__($rowInfo . 'Link file ' . $file . ' not exists'));
}
$pathinfo = pathinfo($file);
$linkfile = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
$dispretionPath = Varien_File_Uploader::getDispretionPath($linkfile);
$linkfile = $dispretionPath . DS . $linkfile;
$linkfile = $dispretionPath . DS . Varien_File_Uploader::getNewFileName(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
$ioAdapter = new Varien_Io_File();
$ioAdapter->setAllowCreateFolders(true);
$distanationDirectory = dirname(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
try {
$ioAdapter->open(array('path' => $distanationDirectory));
$ioAdapter->cp($file, Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
$ioAdapter->chmod(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile, 0777);
} catch (exception $e) {
Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage()));
}
//{"file": "/2/_/2.jpg", "name": "2.jpg", "size": 23407, "status": "new"}
$linkfile = str_replace(DS, '/', $linkfile);
$filearrayforimports = array(array('file' => $linkfile, 'name' => $pathinfo['filename'] . '.' . $pathinfo['extension'], 'status' => 'new', 'size' => filesize($file)));
if (isset($configBundleOptionsCodes[5])) {
if ($configBundleOptionsCodes[5] == 0) {
$linkspurchasedstatus = 0;
$linkspurchasedstatustext = false;
} else {
$linkspurchasedstatus = 1;
$linkspurchasedstatustext = true;
}
$product->setLinksPurchasedSeparately($linkspurchasedstatus);
$product->setLinksPurchasedSeparately($linkspurchasedstatustext);
}
//$downloadableitems['link'][$downloadableitemsoptionscount]['link_file'] = $linkfile;
$downloadableitems['link'][$downloadableitemsoptionscount]['file'] = Mage::helper('core')->jsonEncode($filearrayforimports);
} else {
if ($configBundleOptionsCodes[3] == "url") {
$downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
}
}
$downloadableitems['link'][$downloadableitemsoptionscount]['sort_order'] = 0;
$product->setDownloadableData($downloadableitems);
$downloadableitemsoptionscount += 1;
}
#print_r($downloadableitems);
//}
}
示例7: _validateImageFile
protected function _validateImageFile(&$filename, $toDir)
{
$ds = '/';
if (file_exists($toDir . $ds . $filename)) {
return true;
}
$prefix = str_replace('\\', $ds, Varien_File_Uploader::getDispretionPath($filename));
if (file_exists(rtrim($toDir) . rtrim($prefix, $ds) . $ds . ltrim($filename, $ds))) {
$filename = rtrim($prefix, $ds) . $ds . ltrim($filename, $ds);
return true;
}
$warning = $this->__('Related file image does not exist');
if ($this->_missingImageAction == 'error') {
throw new Unirgy_RapidFlow_Exception_Row($warning);
}
$result = false;
switch ($this->_missingImageAction) {
case '':
case 'warning_save':
$result = true;
break;
case 'warning_skip':
$warning .= '. ' . $this->__('Image field was not updated');
break;
case 'warning_empty':
$warning .= '. ' . $this->__('Image field was reset');
$filename = null;
$result = true;
break;
}
$this->_profile->addValue('num_warnings');
$this->_profile->getLogger()->warning($warning);
return $result;
}
示例8: _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';
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'] > $this->_getUploadMaxFilesize()) {
$this->setIsValid(false);
Mage::throwException(Mage::helper('catalog')->__("The file you uploaded is larger than %s Megabytes allowed by server", $this->_bytesToMbytes($this->_getUploadMaxFilesize())));
} else {
switch ($this->getProcessMode()) {
case Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL:
Mage::throwException(Mage::helper('catalog')->__('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' => $this->_getUploadMaxFilesize()));
/**
* Upload process
*/
$this->_initFilesystem();
if ($upload->isUploaded($file) && $upload->isValid($file)) {
$extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
$fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
$dispersion = Varien_File_Uploader::getDispretionPath($fileName);
$filePath = $dispersion;
$fileHash = md5(file_get_contents($fileInfo['tmp_name']));
$filePath .= DS . $fileHash . '.' . $extension;
$fileFullPath = $this->getQuoteTargetDir() . $filePath;
$upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
$this->getProduct()->getTypeInstance(true)->addFileQueue(array('operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this));
$_width = 0;
$_height = 0;
if (is_readable($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('catalog')->__('Please specify the product required option(s)'));
//.........这里部分代码省略.........
示例9: processImage
/**
*
* Save the avatar image after checks
*/
public function processImage()
{
$session = $this->_getSession();
$upload = new Zend_File_Transfer_Adapter_Http();
$file = 'photo';
try {
$runValidation = $upload->isUploaded($file);
if (!$runValidation) {
return array();
}
$fileInfo = $upload->getFileInfo($file);
$fileInfo = $fileInfo[$file];
} catch (Exception $e) {
// when file exceeds the upload_max_filesize, $_FILES is empty
if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $this->_getUploadMaxFilesize()) {
$errors[] = Mage::helper('avatar')->__("The file you uploaded is larger than %s Megabytes allowed by server", $this->_bytesToMbytes($this->_getUploadMaxFilesize()));
return $errors;
/*Mage::throwException(
Mage::helper('catalog')->__("The file you uploaded is larger than %s Megabytes allowed by server",
$this->_bytesToMbytes($this->_getUploadMaxFilesize())
)
);*/
} else {
Mage::throwException(Mage::helper('avatar')->__("error uploading image"));
}
}
/**
* Option Validations
*/
// Image dimensions
$_dimentions = array();
$_dimentions['maxwidth'] = '2000';
$_dimentions['maxheight'] = '2000';
if (count($_dimentions) > 0) {
$upload->addValidator('ImageSize', false, $_dimentions);
}
// File extension
$_allowed = $this->_parseExtensionsString("jpg/gif/png");
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' => $this->_getUploadMaxFilesize()));
/**
* Upload process
*/
$this->_initFilesystem();
if ($upload->isUploaded($file) && $upload->isValid($file)) {
$extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
$fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
$dispersion = Varien_File_Uploader::getDispretionPath($fileName);
$filePath = $dispersion;
$destination = $this->getPhotoTargetDir() . $filePath;
$this->_createWriteableDir($destination);
$upload->setDestination($destination);
$fileHash = md5(file_get_contents($fileInfo['tmp_name']));
$filePath .= DS . $fileHash . '-' . time() . "." . $extension;
$fileFullPath = $this->getPhotoTargetDir() . $filePath;
$upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
if (!$upload->receive($file)) {
Mage::throwException(Mage::helper('avatar')->__("File upload failed"));
}
$_imageSize = @getimagesize($fileFullPath);
if (is_array($_imageSize) && count($_imageSize) > 0) {
$_width = $_imageSize[0];
$_height = $_imageSize[1];
} else {
$_width = 0;
$_height = 0;
}
$imageObj = new Varien_Image($fileFullPath);
$imageObj->constrainOnly(TRUE);
$imageObj->keepAspectRatio(TRUE);
$imageObj->keepTransparency(TRUE);
$imageObj->resize(50);
$imageObj->save($fileFullPath);
return $filePath;
} elseif ($upload->getErrors()) {
$errors = array();
foreach ($upload->getErrors() as $errorCode) {
if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) {
$errors[] = Mage::helper('avatar')->__("The file '%s' has an invalid extension", $fileInfo['name']);
} elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) {
$errors[] = Mage::helper('avatar')->__("The file '%s' has an invalid extension", $fileInfo['name']);
} elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG) {
$errors[] = Mage::helper('avatar')->__("Maximum allowed image width for '%s' is %s px.", $fileInfo['name'], $_dimentions['maxwidth']);
} elseif ($errorCode == Zend_Validate_File_ImageSize::HEIGHT_TOO_BIG) {
$errors[] = Mage::helper('avatar')->__("Maximum allowed image height for '%s' is %s px.", $fileInfo['name'], $_dimentions['maxheight']);
} elseif ($errorCode == Zend_Validate_File_FilesSize::TOO_BIG) {
$errors[] = Mage::helper('avatar')->__("The file you uploaded is larger than %s Megabytes allowed by server", $fileInfo['name'], $this->_bytesToMbytes($this->_getUploadMaxFilesize()));
}
//.........这里部分代码省略.........
示例10: uploadThumbnail
public function uploadThumbnail($thumbnail, $correctFile = null)
{
// If no thumbnail specified, use placeholder image
if (!$thumbnail) {
// Check if placeholder defined in config
$isConfigPlaceholder = Mage::getStoreConfig("catalog/placeholder/image_placeholder");
$configPlaceholder = '/placeholder/' . $isConfigPlaceholder;
if ($isConfigPlaceholder && file_exists(Mage::getBaseDir('media') . '/catalog/product' . $configPlaceholder)) {
$thumbnail = Mage::getBaseDir('media') . '/catalog/product' . $configPlaceholder;
} else {
// Replace file with skin or default skin placeholder
$skinBaseDir = Mage::getDesign()->getSkinBaseDir();
$skinPlaceholder = "/images/catalog/product/placeholder/image.jpg";
$thumbnail = $skinPlaceholder;
if (file_exists($skinBaseDir . $thumbnail)) {
$baseDir = $skinBaseDir;
} else {
$baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default'));
if (!file_exists($baseDir . $thumbnail)) {
$baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default', '_package' => 'base'));
}
if (!file_exists($baseDir . $thumbnail)) {
$baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default', '_package' => 'default'));
}
}
$thumbnail = str_replace('adminhtml', 'frontend', $baseDir) . $thumbnail;
}
}
if (!$correctFile) {
$correctFile = basename($thumbnail);
}
$tempFile = null;
if (Mage::helper('videogallery')->isUrl($thumbnail)) {
// Get Temporary location where we can save thumbnail to
$adapter = new Varien_Io_File();
$tempFile = $adapter->getCleanPath(Mage::getBaseDir('tmp')) . $correctFile;
// Download to the temp location
$thumbData = Mage::helper('videogallery')->file_get_contents_curl($thumbnail);
@file_put_contents($tempFile, $thumbData);
@chmod($tempFile, 0777);
unset($thumbData);
$thumbnail = $tempFile;
}
// Getting ready to download and save thumbnail
$fileName = Varien_File_Uploader::getCorrectFileName($correctFile);
$dispretionPath = Varien_File_Uploader::getDispretionPath($fileName);
//$fileName = $dispretionPath . DS . $fileName;
$fileName = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($fileName));
$ioAdapter = new Varien_Io_File();
$ioAdapter->setAllowCreateFolders(true);
$destinationDirectory = dirname($this->_getConfig()->getMediaPath($fileName));
try {
$ioAdapter->open(array('path' => $destinationDirectory));
if (!$ioAdapter->cp($thumbnail, $this->_getConfig()->getMediaPath($fileName))) {
return false;
}
$ioAdapter->chmod($this->_getConfig()->getMediaPath($fileName), 0777);
if ($tempFile) {
$ioAdapter->rm($tempFile);
}
} catch (Exception $e) {
Mage::throwException(Mage::helper('videogallery')->__($e->getMessage()));
}
$fileName = str_replace(DS, '/', $fileName);
return $fileName;
}