public function importarEmailsAction() { $post = $this->getRequest(); $diretorio = preg_replace('/application/', '', realpath(APPLICATION_PATH)) . 'public' . DIRECTORY_SEPARATOR . 'excel' . DIRECTORY_SEPARATOR; // $req = $this->getRequest(); $params = $post->getParams(); $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination($diretorio); $upload->addValidator('Size', false, 8000000); $upload->addValidator('Extension', false, array('extension1' => 'xlsx,xls,sxc,pdf,csv,dbf,dif,ods,pts,pxl,sdc,slk,stc,vor,xlt')); // print_r($upload->getFileName(null, false)); die(); if ($post->isPost() && !$upload->isValid()) { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-file'); } if (!$upload->isValid()) { $this->view->classe = 'danger'; // var_dump($upload->getMessages()); $this->sessao->infoUpload = $this->treatMessagesUpload($upload->getErrors()); } // if (file_exists($upload->getFileName())) { // // $messages = array(0 => 'O arquivo ' . $upload->getFileName(null, false) . ' Já existe no diretório.'); // $this->sessao->infoUpload = $this->treatMessagesUpload($messages); // } // $rename = substr(md5(rand(000, 999) . time()), 0, 5) . '_' . strtolower($upload->getFileName()); // $upload->addFilter('Rename', $this->public_dir_upload, $rename); try { if (!$upload->isValid()) { $this->view->classe = 'danger'; $this->sessao->infoUpload = $this->treatMessagesUpload($upload->getErrors()); } else { $upload->receive(); $this->sessao->infoUpload = $upload->getFileInfo(); $arr = array('url_file' => $upload->getFileName(null, false), 'file' => $params['emails']); $file_to_include = $diretorio . $arr['url_file']; if (is_file($file_to_include)) { // print_r($file_to_include); die(); $identify = PHPExcel_IOFactory::identify($file_to_include); $excelReader = PHPExcel_IOFactory::createReader($identify); $reader = $excelReader->load($file_to_include); $this->sessao->infoUpload = ''; $listEmails = array(); $email = array(); $nome = array(); $dinamic_text = array(); $addmails = array(); $email_collection = array(); if (!count($reader->getActiveSheet()->getRowIterator())) { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-read'); } else { foreach ($reader->getActiveSheet()->getRowIterator() as $rowKey => $rows) { $cellIterator = $rows->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); if (!count($cellIterator)) { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-read'); } else { foreach ($cellIterator as $cellIteratorIteratorKey => $cell) { if (preg_match('/@/', $cell->getValue())) { $email[] = $cell->getValue(); $this->sessao->infoUpload .= "email: " . $email . "<br>"; } else { if (preg_match('/^\\{(.*)\\}$/', $cell->getValue(), $return)) { $dinamic_text[] = $return[1]; $this->sessao->infoUpload .= "email: " . $dinamic_text . "<br>"; } else { $nome[] = $cell->getValue(); $this->sessao->infoUpload .= "email: " . $nome . "<br>"; } } // $data[$rowKey][$cell->getCoordinate()] = $cell->getValue(); //$data[$rowKey][$cell->getCoordinate()] = $cell->getValue(); // $data[$rowKey] = $cell->getValue(); } } } } if (!empty($email)) { array_unique($email); $listEmails = array('nomes' => $nome, 'emails' => $email, 'dinamic_contents' => $dinamic_text); } else { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-imported'); } if (count($listEmails['emails'])) { foreach ($listEmails['emails'] as $key => $email) { if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $email_collection = array('nome' => $listEmails['nomes'][$key], 'dinamic_content' => $listEmails['dinamic_contents'][$key], 'email' => $email); $addmails[] = $email_collection; } if (count($addmails)) { $gravaEmail = new Application_Model_Contatos(); $gravaEmail->addContato($email_collection); } else { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-imported'); } } $this->redirect($this->view->site . '/index/cadastrar-emails/data/imported'); } else { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-imported'); } } else { $this->redirect($this->view->site . '/index/cadastrar-emails/data/not-imported'); } } } catch (Zend_File_Transfer_Exception $e) { $this->sessao->infoUpload = $e->getMessage(); } $this->view->info = $this->sessao->infoUpload; }
/** * 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; }
/** * 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) { if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) { $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle()); } elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) { $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle()); } elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG || $errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG) { $errors[] = AO::helper('catalog')->__("Maximum allowed image size for '%s' is %sx%s px.", $option->getTitle(), $option->getImageSizeX(), $option->getImageSizeY()); } } if (count($errors) > 0) { $this->setIsValid(false); AO::throwException(implode("\n", $errors)); } } else { $this->setIsValid(false); AO::throwException(AO::helper('catalog')->__('Please specify the product required option(s)')); } return $this; }
/** * Save attribute file for given object * * @param Mage_Core_Model_Abstract $object * @return BL_FileAttributes_Model_Attribute_Backend_File */ protected function _saveAttributeFile($object) { $helper = Mage::helper('fileattributes'); $attribute = $this->getAttribute(); $value = $object->getData($attribute->getName()); $label = $attribute->getFrontendLabel(); $maxFileSize = $this->getUploadMaxFilesize(); /* Using enableHeaderCheck() on Zend "mime-type" file validators seems to be not useful, as it checks the type retrieved from Zend_File_Transfer, and Zend_File_Transfer_Adapter_Abstract::_detectMimeType() seems to not be using a different detection than those validators, actually it does just return "application/octet-stream" by default */ //$allowMimeHeaderCheck = Mage::helper('fileattributes/config')->getAllowMimeHeaderCheck(); if (is_array($value) && !empty($value['delete'])) { // Just reset value, files deletion is accessible from elsewhere if ($object->getId()) { $this->_saveObjectAttributeValue($object, ''); } else { $this->_pendingSaveObject = $object; $this->_pendingSaveValue = ''; } return $this; } $upload = new Zend_File_Transfer_Adapter_Http(); $file = $attribute->getName(); try { $origData = $object->getOrigData(); $origFile = isset($origData[$file]) ? $origData[$file] : null; $newFile = is_array($value) ? $value['value'] : $value; if (!$upload->isUploaded($file) && (!$attribute->getIsRequired() || $newFile == $origFile)) { // No need to go further return $this; } $fileInfo = $upload->getFileInfo($file); $fileInfo = $fileInfo[$file]; $fileInfo['title'] = $fileInfo['name']; } catch (Exception $e) { // Upload error if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] < $maxFileSize) { $size = Mage::helper('fileattributes')->getFileSizeForDisplay($maxFileSize, 2); Mage::throwException($helper->__('The file you uploaded for "%s" attribute is larger than the %s allowed by server', $label, $size)); } else { Mage::throwException($helper->__('An error occured during file upload for "%s" attribute', $label)); } } $config = Mage::helper('fileattributes/config')->getAttributeConfiguration($attribute->getId()); // Validation for MIME types if (isset($config['allowed_mime_types']) && is_array($validate = $config['allowed_mime_types'])) { $upload->addValidator('MimeType', false, array_keys($validate)); //$upload->getValidator('MimeType')->enableHeaderCheck($allowMimeHeaderCheck); } elseif (isset($config['forbidden_mime_types']) && is_array($validate = $config['forbidden_mime_types'])) { $upload->addValidator('ExcludeMimeType', false, array_keys($validate)); //$upload->getValidator('ExcludeMimeType')->enableHeaderCheck($allowMimeHeaderCheck); } // Validation for image-only flag if (isset($config['image_only']) && $config['image_only']) { $upload->addValidator('IsImage', false); //$upload->getValidator('IsImage')->enableHeaderCheck($allowMimeHeaderCheck); } // Validation for image dimensions $validate = array(); if ($config['image_min_width'] > 0) { $validate['minwidth'] = $config['image_min_width']; } if ($config['image_max_width'] > 0) { $validate['maxwidth'] = $config['image_max_width']; } if ($config['image_min_height'] > 0) { $validate['minheight'] = $config['image_min_height']; } if ($config['image_max_height'] > 0) { $validate['maxheight'] = $config['image_max_height']; } if (count($validate) > 0) { $upload->addValidator('ImageSize', false, $validate); } // Validation for file extensions if (isset($config['allowed_file_extensions']) && is_array($validate = $config['allowed_file_extensions'])) { $upload->addValidator('Extension', false, $validate); } elseif (isset($config['forbidden_file_extensions']) && is_array($validate = $config['forbidden_file_extensions'])) { $upload->addValidator('ExcludeExtension', false, $validate); } // Validation for maximum filesize (take the smallest between config and server ones) $validate = $config['file_max_size'] > 0 ? min($config['file_max_size'], $maxFileSize) : $maxFileSize; $upload->addValidator('FilesSize', false, array('max' => $validate)); // Let's upload (if possible) ! if ($upload->isUploaded($file) && $upload->isValid($file)) { try { $uploader = new Varien_File_Uploader($attribute->getName()); $uploader->setAllowCreateFolders(true)->setAllowRenameFiles(true)->setFilesDispersion(false); if (!$uploader->save($this->getTargetDir())) { Mage::throwException($helper->__('File "%s" upload failed for "%s" attribute', $fileInfo['name'], $label)); } if ($object->getId()) { $this->_saveObjectAttributeValue($object, $uploader->getUploadedFileName()); } else { $this->_pendingSaveObject = $object; $this->_pendingSaveValue = $uploader->getUploadedFileName(); } } catch (Exception $e) { Mage::throwException($helper->__('An error occured during file "%s" upload for "%s" attribute : "%s"', $fileInfo['name'], $label, $e->getMessage())); } } elseif (($errors = $upload->getErrors()) && ($errors = $this->_parseValidatorErrors($errors, $fileInfo, $label)) && count($errors) > 0) { // Known upload error(s) Mage::throwException(implode("<br />", $errors)); } else { // Unknown or not handled upload error Mage::throwException($helper->__('You must upload a valid file for "%s" attribute', $label)); } }
public function receiveformAction() { if ($this->getRequest()->isPost()) { $xmlHttpRequest = $this->_request->isXmlHttpRequest(); $formParams = $this->getRequest()->getParams(); $sessionHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('Session'); if (!empty($formParams)) { $websiteConfig = Zend_Controller_Action_HelperBroker::getExistingHelper('config')->getConfig(); $formMapper = Application_Model_Mappers_FormMapper::getInstance(); // get the form details $form = $formMapper->findByName($formParams['formName']); $useCaptcha = $form->getCaptcha(); //hidden input validation $formName = $form->getName(); $formId = $form->getId(); if (!isset($formParams[md5($formName . $formId)]) || $formParams[md5($formName . $formId)] != '') { if ($xmlHttpRequest) { $this->_helper->response->success($form->getMessageSuccess()); } $this->_redirect($formParams['formUrl']); } unset($formParams[md5($formName . $formId)]); //validating recaptcha if ($useCaptcha == 1) { if (!empty($websiteConfig) && !empty($websiteConfig[Tools_System_Tools::RECAPTCHA_PUBLIC_KEY]) && !empty($websiteConfig[Tools_System_Tools::RECAPTCHA_PRIVATE_KEY]) && isset($formParams['recaptcha_challenge_field']) || isset($formParams['captcha'])) { if (isset($formParams['recaptcha_challenge_field']) && isset($formParams['recaptcha_response_field'])) { if ($formParams['recaptcha_response_field'] == '') { if ($xmlHttpRequest) { $this->_helper->response->fail($this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.')); } $sessionHelper->toasterFormError = $this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.'); $this->_redirect($formParams['formUrl']); } $recaptcha = new Zend_Service_ReCaptcha($websiteConfig[Tools_System_Tools::RECAPTCHA_PUBLIC_KEY], $websiteConfig[Tools_System_Tools::RECAPTCHA_PRIVATE_KEY]); $result = $recaptcha->verify($formParams['recaptcha_challenge_field'], $formParams['recaptcha_response_field']); if (!$result->isValid()) { if ($xmlHttpRequest) { $this->_helper->response->fail($this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.')); } $sessionHelper->toasterFormError = $this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.'); $this->_redirect($formParams['formUrl']); } unset($formParams['recaptcha_challenge_field']); unset($formParams['recaptcha_response_field']); } else { //validating captcha if (!$this->_validateCaptcha(strtolower($formParams['captcha']), $formParams['captchaId'])) { if ($xmlHttpRequest) { $this->_helper->response->fail($this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.')); } $sessionHelper->toasterFormError = $this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.'); $this->_redirect($formParams['formUrl']); } } } else { if ($xmlHttpRequest) { $this->_helper->response->fail($this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.')); } $sessionHelper->toasterFormError = $this->_helper->language->translate('You\'ve entered an incorrect security text. Please try again.'); $this->_redirect($formParams['formUrl']); } } $sessionHelper->formName = $formParams['formName']; $sessionHelper->formPageId = $formParams['formPageId']; unset($formParams['formPageId']); unset($formParams['submit']); if (isset($formParams['conversionPageUrl'])) { $conversionPageUrl = $formParams['conversionPageUrl']; unset($formParams['conversionPageUrl']); } $attachment = array(); if (!$xmlHttpRequest) { //Adding attachments to email $websitePathTemp = $this->_helper->website->getPath() . $this->_helper->website->getTmp(); $uploader = new Zend_File_Transfer_Adapter_Http(); $uploader->setDestination($websitePathTemp); $uploader->addValidator('Extension', false, self::ATTACHMENTS_FILE_TYPES); //Adding Size limitation $uploader->addValidator('Size', false, $formParams['uploadLimitSize'] * 1024 * 1024); //Adding mime types validation $uploader->addValidator('MimeType', true, array('application/pdf', 'application/xml', 'application/zip', 'text/csv', 'text/plain', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'application/msword', 'application/vnd.ms-excel')); $files = $uploader->getFileInfo(); foreach ($files as $file => $fileInfo) { if ($fileInfo['name'] != '') { if ($uploader->isValid($file)) { $uploader->receive($file); $at = new Zend_Mime_Part(file_get_contents($uploader->getFileName($file))); $at->type = $uploader->getMimeType($file); $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT; $at->encoding = Zend_Mime::ENCODING_BASE64; $at->filename = $fileInfo['name']; $attachment[] = $at; unset($at); Tools_Filesystem_Tools::deleteFile($this->_helper->website->getPath() . $this->_helper->website->getTmp() . $fileInfo['name']); } else { $validationErrors = $uploader->getErrors(); $errorMessage = ''; foreach ($validationErrors as $errorType) { if ($errorType == 'fileMimeTypeFalse') { $errorMessage .= 'Invalid file format type. '; } if ($errorType == 'fileSizeTooBig') { $errorMessage .= $this->_helper->language->translate('Maximum size upload') . ' ' . $formParams['uploadLimitSize'] . 'mb.'; } if ($errorType == 'fileExtensionFalse') { $errorMessage .= 'File extension not valid. '; } } $sessionHelper->toasterFormError = $this->_helper->language->translate($errorMessage); $this->_redirect($formParams['formUrl']); } } } } unset($formParams['uploadLimitSize']); // sending mails $sysMailWatchdog = new Tools_Mail_SystemMailWatchdog(array('trigger' => Tools_Mail_SystemMailWatchdog::TRIGGER_FORMSENT, 'data' => $formParams, 'attachment' => $attachment)); $mailWatchdog = new Tools_Mail_Watchdog(array('trigger' => Tools_Mail_SystemMailWatchdog::TRIGGER_FORMSENT, 'data' => $formParams, 'attachment' => $attachment)); $mailWatchdog->notify($form); $mailsSent = $sysMailWatchdog->notify($form); if ($mailsSent) { $form->notifyObservers(); if ($xmlHttpRequest) { $this->_helper->response->success($form->getMessageSuccess()); } //redirect to conversion page if ($conversionPageUrl) { $this->_redirect($conversionPageUrl); } $sessionHelper->toasterFormSuccess = $form->getMessageSuccess(); $this->_redirect($formParams['formUrl']); } if ($xmlHttpRequest) { $this->_helper->response->fail($form->getMessageError()); } $sessionHelper->toasterFormError = $form->getMessageError(); $this->_redirect($formParams['formUrl']); } } }
/** * * 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())); } } if (count($errors) > 0) { return $errors; } } else { $errors[] = Mage::helper('avatar')->__('File upload failed'); return $errors; } }
public function upload() { if ($this->_helper->Identity()) { //Check if images path directory is writable if (!is_writable(IMAGE_PATH)) { throw new Pas_Exception_NotAuthorised('The images directory is not writable', 500); } // Create the imagedir path $imagedir = IMAGE_PATH . '/' . $this->_helper->Identity()->username; //Check if a directory and if not make directory if (!is_dir($imagedir)) { mkdir($imagedir, 0775, true); } //Check if the personal image directory is writable if (!is_writable($imagedir)) { throw new Pas_Exception_NotAuthorised('The user image directory is not writable', 500); } // Get images and do the magic $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($imagedir); $adapter->setOptions(array('useByteString' => false)); // Only allow good image files! $adapter->addValidator('Extension', false, 'jpg, tiff'); $adapter->addValidator('NotExists', false, array($imagedir)); $files = $adapter->getFileInfo(); // Create an array for the images $images = array(); // Loop through the submitted files foreach ($files as $file => $info) { // file uploaded & is valid // if (!$adapter->isUploaded($file)) continue; // if (!$adapter->isValid($file)) continue; // Clean up the image name for crappy characters $filename = pathinfo($adapter->getFileName($file)); // Instantiate the renamer $reNamer = new Pas_Image_Rename(); // Clean the filename $cleaned = $reNamer->strip($filename['filename'], $filename['extension']); // Rename the file $adapter->addFilter('rename', $cleaned); // receive the files into the user directory $adapter->receive($file); // this has to be on top if (!$adapter->hasErrors()) { // Create the object for reuse $image = new stdClass(); $image->cleaned = $cleaned; $image->basename = $filename['basename']; $image->extension = $filename['extension']; $image->thumbnailUrl = $this->createThumbnailUrl($adapter->getFileName($file, false)); $image->deleteUrl = $this->_createUrl($adapter->getFileName($file, false)); $image->path = $adapter->getFileName($file); $image->name = $adapter->getFileName($file, false); $image->size = $adapter->getFileSize($file); $image->mimetype = $adapter->getMimeType($file); // The secure ID stuff for linking images $image->secuid = $this->_helper->GenerateSecuID(); // Get the image dims $imagesize = getimagesize($adapter->getFileName($file)); $image->width = $imagesize[0]; $image->height = $imagesize[1]; $params = $this->getAllParams(); $image->findID = $params['findID']; // Create the raw image url $image->url = $this->_createUrl($adapter->getFileName($file, false)); $image->deleteType = 'DELETE'; $images[] = $image; $slides = new Slides(); $insert = $slides->addAndResize($images); $this->view->data = $images; $this->_helper->solrUpdater->update('images', (int) $insert); $this->_helper->solrUpdater->update('objects', $params['findID'], 'artefacts'); } else { $image = new stdClass(); $image->error = $adapter->getErrors(); $images[] = $image; $this->view->data = $images; } } } else { throw new Pas_Exception_NotAuthorised('Your account does not seem enabled to do this', 500); } }