public function __construct($arrParam = array(), $options = null) { ////////////////////////////////// //Kiem tra Name ///////////// ////////////////////////////////// if ($arrParam['action'] == 'add') { $options = array('table' => 'da_album', 'field' => 'album_name'); } elseif ($arrParam['action'] == 'edit') { $options = array('table' => 'da_album', 'field' => 'album_name', 'exclude' => array('field' => 'id', 'value' => $arrParam['id'])); } $validator = new Zend_Validate(); $validator->addValidator(new Zend_Validate_NotEmpty(), true)->addValidator(new Zend_Validate_StringLength(3, 100), true); if (!$validator->isValid($arrParam['album_name'])) { $message = $validator->getMessages(); $this->_messageError['album_name'] = 'Tên album: ' . current($message); $arrParam['album_name'] = ''; } ////////////////////////////////// //Kiem tra Picture small /////////// ////////////////////////////////// $upload = new Zend_File_Transfer_Adapter_Http(); $fileInfo = $upload->getFileInfo('picture'); $fileName = $fileInfo['picture']['name']; if (!empty($fileName)) { $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'picture'); $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'picture'); if (!$upload->isValid('picture')) { $message = $upload->getMessages(); $this->_messageError['picture'] = 'Hình ảnh đại diện: ' . current($message); } } ////////////////////////////////// //Kiem tra Order ///////////// ////////////////////////////////// $validator = new Zend_Validate(); $validator->addValidator(new Zend_Validate_StringLength(1, 10), true)->addValidator(new Zend_Validate_Digits(), true); if (!$validator->isValid($arrParam['order'])) { $message = $validator->getMessages(); $this->_messageError['order'] = 'Sắp xếp: ' . current($message); $arrParam['order'] = ''; } ////////////////////////////////// //Kiem tra Status ///////////// ////////////////////////////////// if (empty($arrParam['status']) || !isset($arrParam['status'])) { $arrParam['status'] = 0; } //======================================== // TRUYEN CAC GIA TRI DUNG VAO MANG $_arrData //======================================== $this->_arrData = $arrParam; }
/** * Provides an image browser feature for the rich text editor * * @return void */ public function browseAction() { $params = Zend_Registry::get('params'); // This is displayed inside the editor - so we need set a blank layout (no header/footer) $this->_helper->layout->setLayout('popup'); $gallery = new Datasource_Cms_Gallery(); $categoryID = $this->getRequest()->getParam('cid'); $editorFuncNum = $this->getRequest()->getParam('CKEditorFuncNum'); if ($this->getRequest()->isPost()) { // A new image has been sent - handle it $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination($params->cms->imageUploadPath); $upload->addValidator('Extension', false, 'jpg,jpeg,png,gif'); $upload->addValidator('Count', false, 1); $upload->addValidator('Size', false, 10240000); if ($upload->receive()) { // File has been uploaded succesfully $this->view->uploadSuccess = true; $imageFilename = $upload->getFileName(null, false); $imageLocation = $upload->getFileName(); list($imageWidth, $imageHeight) = getimagesize($imageLocation); $imageID = $gallery->addNew(0, $imageFilename, $imageWidth, $imageHeight); // Resize and save a few pr $cmsImage = new Application_Cms_Image(); if ($imageWidth > $imageHeight) { $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/200_' . $imageFilename, 200, null); $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/400_' . $imageFilename, 400, null); } else { $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/200_' . $imageFilename, null, 150); $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/400_' . $imageFilename, null, 400); } $this->_helper->getHelper('FlashMessenger')->addMessage(array('deleted' => true)); // $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/images/edit?id='. $imageID); // Forward to image editor $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/images/browse?CKEditorFuncNum=' . $editorFuncNum); } else { // An error occurred - deal with the error messages $errorMessages = $upload->getMessages(); } } else { // No image uploaded - show the gallery if (!$categoryID) { $categoryID = 0; } $imageList = $gallery->getImagesByCategoryID($categoryID); $this->view->imageList = $this->view->partialLoop('partials/image-browser-image.phtml', $imageList); $this->view->editorFuncNum = $editorFuncNum; } }
private function _uploadPlugin() { $this->_uploadHandler->addValidator('Extension', false, 'zip'); if ($this->_checkMime) { $this->_uploadHandler->addValidator(new Validators_MimeType(array('application/zip')), false); } $pluginArchive = $this->_uploadHandler->getFileInfo(); if (!$this->_uploadHandler->isValid()) { return array('error' => true); } $destination = $this->_uploadHandler->getDestination(); $zip = new ZipArchive(); $zip->open($pluginArchive['file']['tmp_name']); $unzipped = $zip->extractTo($destination); if ($unzipped !== true) { return array('name' => $pluginArchive['file']['name'], 'error' => 'Can\'t extract zip file to tmp directory'); } $pluginName = str_replace('.zip', '', $pluginArchive['file']['name']); $validateMessage = $this->_validatePlugin($pluginName); $miscConfig = Zend_Registry::get('misc'); if ($validateMessage === true) { $destinationDir = $this->_websiteConfig['path'] . $miscConfig['pluginsPath']; if (is_dir($destinationDir . $pluginName)) { Tools_Filesystem_Tools::deleteDir($destinationDir . $pluginName); } $res = $zip->extractTo($destinationDir); $zip->close(); Tools_Filesystem_Tools::deleteDir($destination . '/' . $pluginName); } else { $zip->close(); return array('name' => $pluginArchive['file']['name'], 'error' => $validateMessage); } return array('error' => false, 'name' => $pluginArchive['file']['name'], 'type' => $pluginArchive['file']['type'], 'size' => $pluginArchive['file']['size'], 'pluginname' => $pluginName); }
/** * Use the Zend Framework adapter to handle validation instead of the * built-in _validateFile() method. * * @see Omeka_File_Ingest_AbstractIngest::_validateFile() * @param Zend_Validate_Interface $validator * @return void */ public function addValidator(Zend_Validate_Interface $validator) { if (!$this->_adapter) { $this->_buildAdapter(); } $this->_adapter->addValidator($validator); }
public function uploadImage($scope) { // create an instance of class Zend_File_Transfer_Adapter_Http // and add validator $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->addValidator('ImageSize', true, $this->_imageSize); $adapter->addValidator('Size', true, self::MAX_FILE_SIZE); // if image can be uploaded if ($adapter->isUploaded($scope)) { //validate image if (!$adapter->isValid($scope)) { Mage::throwException(Mage::helper('ab_adverboard')->__('Uploaded image is not valid')); } // upload image $upload = new Varien_File_Uploader($scope); $upload->setAllowCreateFolders(true); $upload->setAllowedExtensions($this->_allowedExtensions); $upload->setAllowRenameFiles(false); $upload->setFilesDispersion(false); if ($upload->save($this->getBaseDir(), $_FILES['image']['name'])) { return $upload->getUploadedFileName(); } } return false; }
public function uploadAction() { $project_id = $this->_request->getParam('id'); //Validate that project belongs to user here. $project_helper = $this->_helper->Projects; if ($project_helper->isOwner($this->user_session->id, $project_id, $this->project_model)) { $adapter = new Zend_File_Transfer_Adapter_Http(); foreach ($adapter->getFileInfo() as $key => $file) { //Get extension $path = split("[/\\.]", $file['name']); $ext = end($path); try { $adapter->addValidator('Extension', false, array('extension' => 'jpg,gif,png', 'case' => true)); //Should probably use the array method below to enable overwriting $new_name = md5(rand()) . '-' . $project_id . '.' . $ext; //Add rename filter $adapter->addFilter('Rename', UPLOAD_PATH . $new_name); } catch (Zend_File_Transfer_Exception $e) { die($e->getMessage()); } try { //Store if ($adapter->receive($file['name'])) { $this->image_model->addOne($project_id, $new_name, $key); } } catch (Zend_File_Transfer_Exception $e) { die($e->getMessage()); } } header("Location: /account/project/id/{$project_id}"); } else { header("Location: /account"); } }
/** * handleFileTransfer * @author Thomas Schedler <*****@*****.**> */ private function handleFileTransfer() { $this->objUpload = new Zend_File_Transfer_Adapter_Http(); $this->objUpload->setOptions(array('useByteString' => false)); /** * validators for upload of media */ $arrExcludedExtensions = $this->core->sysConfig->upload->excluded_extensions->extension->toArray(); $this->objUpload->addValidator('Size', false, array('min' => 1, 'max' => $this->core->sysConfig->upload->max_filesize)); $this->objUpload->addValidator('ExcludeExtension', false, $arrExcludedExtensions); /** * check if medium is uploaded */ if (!$this->objUpload->isUploaded(self::UPLOAD_FIELD)) { $this->core->logger->warn('isUploaded: ' . implode('\\n', $this->objUpload->getMessages())); throw new Exception('File is not uploaded!'); } /** * check if upload is valid */ if (!$this->objUpload->isValid(self::UPLOAD_FIELD)) { $this->core->logger->warn('isValid: ' . implode('\\n', $this->objUpload->getMessages())); throw new Exception('Uploaded file is not valid!'); } }
function configAction() { // When the form is submitted $form_mess = ""; if (isset($_POST['confName'])) { $form_mess = $this->updateConfig($_POST, $this->db_v1, $this->view, $this->session); $this->config_v1 = GetConfig($this->db_v1); // Check whether the logo file has been transmitted $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination('images/'); $adapter->addValidator('IsImage', false); if ($adapter->receive()) { $name = $adapter->getFileName('logo_file'); //récupérer le nom du fichier sans avoir tout le chemin $name = basename($name); $this->db_v1->execRequete("UPDATE Config SET logo_file='{$name}'"); } $config = new Config(); $this->config = $config->fetchAll()->current(); $this->config->putInView($this->view); $registry = Zend_registry::getInstance(); $registry->set("Config", $this->config); } $this->view->config_message = $form_mess; $this->instantiateConfigVars($this->config_v1, $this->view); $this->view->setFile("content", "config.xml"); $this->view->setFile("form_config", "form_config.xml"); $form_mess = ""; $this->view->messages = $form_mess; // N.B: the config values ar eput in the views by the Myreview controller echo $this->view->render("layout"); }
public function imageAction() { if ($this->getRequest()->isPost()) { $upload = new Zend_File_Transfer_Adapter_Http(); $dirs = array('image' => array('gif', 'jpg', 'jpeg', 'png'), 'flash' => array('swf', 'flv')); $dir = $this->_getParam('dir'); if (!isset($dirs[$dir])) { $this->_alert('上传类型出错!'); } $savePath = UPLOAD_PATH . DS . $dir; //检查文件大小 $upload->addValidator('Size', false, 500000); if (false == $upload->isValid()) { $this->_alert('上传文件大小超过500KB限制。'); } //检查目录 if (@is_dir($savePath) === false) { $this->_alert('上传目录不存在。'); } //检查目录写权限 if (@is_writable($savePath) === false) { $this->_alert('上传目录没有写权限。'); } //获得文件类型 $upload->addValidator('Extension', false, $dirs[$dir]); if (false == $upload->isValid()) { $this->_alert('只能上传' . implode('、', $dirs[$dir]) . '文件类型'); } //设置保存的Path $upload->setDestination($savePath); //设置新的文件名 $fileInfo = $upload->getFileInfo(); $tmpFile = $fileInfo['imgFile']['name']; $extension = explode('.', $tmpFile); $extension = array_pop($extension); $newFile = md5($tmpFile . uniqid()) . '.' . $extension; $upload->addFilter('Rename', array('target' => $savePath . DS . $newFile, 'overwrite' => true)); //保存文件 $upload->receive(); //返回文件url echo Zend_Json::encode(array('error' => 0, 'url' => $this->view->baseUrl() . '/uploads/image/' . $newFile)); exit; } else { $this->_alert('请选择文件。'); exit; } }
/** * Returns an upload object based on the global accessible $_FILES variable. * The returned upload will be pre-configured with a validator for the * system's max upload size and the count of allowed simultaneusly uploads * set to 1. * * @return Zend_File_Transfer_Adapter_Http */ public function generateUploadObject() { // build up upload $upload = new Zend_File_Transfer_Adapter_Http(); // assign and check validators $upload->addValidator('Size', true, $this->_getUploadMaxFileSize()); $upload->addValidator('Count', true, array('min' => 1, 'max' => 1)); return $upload; }
/** * indexAction * @author Thomas Schedler <*****@*****.**> * @version 1.0 */ public function indexAction() { try { $this->core->logger->debug('media->controllers->UploadController->indexAction()'); $this->objUpload = new Zend_File_Transfer_Adapter_Http(); /** * validators for upload of media */ $arrExcludedExtensions = $this->core->sysConfig->upload->excluded_extensions->extension->toArray(); $this->objUpload->addValidator('Size', false, array('min' => 1, 'max' => $this->core->sysConfig->upload->max_filesize)); $this->objUpload->addValidator('ExcludeExtension', false, $arrExcludedExtensions); /** * check if medium is uploaded */ if (!$this->objUpload->isUploaded(self::UPLOAD_FIELD)) { $this->core->logger->warn('isUploaded: ' . implode('\\n', $this->objUpload->getMessages())); throw new Exception('File is not uploaded!'); } /** * check if upload is valid */ // if (!$this->objUpload->isValid(self::UPLOAD_FIELD)) { // $this->core->logger->warn('isValid: '.implode('\n', $this->objUpload->getMessages())); // throw new Exception('Uploaded file is not valid!'); // } if ($this->getRequest()->isPost()) { $objRequest = $this->getRequest(); $this->intParentId = $objRequest->getParam('folderId'); /** * check if is image or else document */ if ($this->intParentId > 0 && $this->intParentId != '') { if (strpos($this->objUpload->getMimeType(self::UPLOAD_FIELD), 'image/') !== false) { $this->handleImageUpload(); } else { $this->handleFileUpload(); } } } } catch (Exception $exc) { $this->core->logger->err($exc); } }
/** * 上传图片处理方法, * 还有中文bug */ public function upload($fileDir, $imgpath) { $adapter = new Zend_File_Transfer_Adapter_Http(); // 不需要渲染模板页 $this->getFrontController()->setParam('noViewRenderer', true); // 你存放上传文件的文件夹 $adapter->setDestination($fileDir); $adapter->addValidator('Extension', false, 'gif,jpeg,png,jpg'); //设置上传文件的后缀名 $adapter->addValidator('Count', false, array('min' => 1, 'max' => 5)); //设置上传文件的个数 $adapter->addValidator('ImageSize', false, array('minwidth' => 0, 'maxwidth' => 40960, 'minhight' => 0, 'maxhight' => 40960)); ////设置上传图片的大小 $adapter->addValidator('FilesSize', false, array('min' => '4KB', 'max' => '4096KB')); ////设置上传文件的大小 //添加过滤器来修改上传文件的名称 if ($imgpath) { $adapter->addFilter('Rename', array('target' => $imgpath, 'overwrite' => true)); } /* $fileInfo = $this->adapter->getFileInfo(); foreach ($fileInfo as $file=>$info) { //file-文件名 if ($this->adapter->isValid($file)) { var_dump($info);die; } } */ // 返回上传后出现在信息 if (!$adapter->receive()) { /* $messages = $adapter->getMessages (); echo implode ( "n", $messages ); */ $out[Response::ERRNO] = 0; $out[Response::MSG] = '上传成功!'; Response::out($out); exit; } else { $out[Response::ERRNO] = 1; $out[Response::MSG] = '上传失败!'; Response::out($out); exit; } }
public function uploadAction() { $this->_helper->layout->disableLayout(); if ($this->getRequest()->isPost()) { $cnt = 0; $mapper = new Application_Model_UploadMapper(); $upload = new Zend_File_Transfer_Adapter_Http(); $upload->addValidator('Size', false, 20000, 'file2'); $upload->setDestination('uploads/'); $files = $upload->getFileInfo(); foreach ($files as $file => $info) { //$transform = new Zend_Image_Transform( $image ); $ext = end(explode(".", $info['name'])); $uuid = uniqid(); $upload->addFilter('Rename', array('target' => 'uploads/' . $uuid . '.' . $ext, 'overwrite' => true)); if ($upload->isValid($file)) { $upload->receive($file); } $imageSize[0] = 150; $imageSize[1] = 150; $imageSize = getimagesize('uploads/' . $uuid . '.' . $ext); $name = $info['name']; $type = $info['type']; $size = $info['size']; $file = 'uploads/' . $name; $_post['file'] = $file; $_post['name'] = $name; $_post['type'] = $type; $_post['size'] = $size; $_post['uuid'] = $uuid; $_post['width'] = $imageSize[0]; $_post['height'] = $imageSize[1]; $_post['ext'] = $ext; $htmldata[$cnt] = $_post; $mapper->saveall($htmldata[$cnt]); $cnt++; } $data = json_encode($htmldata); echo $data; } }
private function upload() { $todir = $this->_cfg['temp']['path'] . $this->getRequest()->getParam('docid', 'unknown_doc'); if (!file_exists($todir)) { mkdir($todir); } $adapter = new Zend_File_Transfer_Adapter_Http(array('ignoreNoFile' => true)); $filename = $adapter->getFileName('upload', false); $adapter->addValidator('Extension', false, $this->getRequest()->getParam('type') == 'images' ? $this->imgExts : $this->fileExts)->addValidators($this->getRequest()->getParam('type') == 'images' ? $this->imgValidators : $this->fileValidators)->addFilter('Rename', array('target' => $todir . DIRECTORY_SEPARATOR . iconv('utf-8', FS_CHARSET, $filename), 'overwrite' => true)); // $adapter->setDestination($todir); $result = new stdClass(); $result->messages = array(); $result->uploadedUrl = ''; if (!$adapter->isValid()) { $result->messages = $adapter->getMessages(); } else { if ($adapter->receive() && $adapter->isUploaded()) { $result->uploadedUrl = ($this->getRequest()->getParam('type') == 'images' ? '' : 'downloads/') . $filename; } } $result->CKEditorFuncNum = $this->getRequest()->getParam('CKEditorFuncNum'); return $result; }
/** * * @return array */ public function uploadFiles() { $return = array('files' => array()); try { $dir = $this->getDirDocs(); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($dir); $typeValidator = new Zend_Validate_File_Extension($this->_extensions); $sizeFile = new Zend_Validate_File_Size($this->_maxSize); $adapter->addValidator($typeValidator, true)->addValidator($sizeFile, true); $files = $adapter->getFileInfo(); foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { continue; } $name = $this->_getNewFileName($dir, $info['name']); $fileInfo = array('size' => $info['size'], 'name' => $name); if (!$adapter->isValid($file)) { $messages = $adapter->getMessages(); $fileInfo['error'] = array_shift($messages); $return['files'][] = $fileInfo; continue; } $adapter->addFilter('Rename', $dir . $name, $file); $adapter->receive($file); $pathFile = $this->publicFileUrl($dir . $name); $fileInfo['url'] = $pathFile; $fileInfo['delete_url'] = '/client/document/delete/?file=' . $pathFile; $fileInfo['delete_type'] = 'DELETE'; $return['files'][] = $fileInfo; } return $return; } catch (Exception $e) { return $return; } }
/** Change staff profile image */ public function logoAction() { $contacts = new Contacts(); $people = $contacts->fetchRow($contacts->select()->where('dbaseID = ?', $this->getIdentityForForms())); $inst = $people->identifier; $this->view->inst = $inst; $logos = new InstLogos(); $logoslisted = $logos->getLogosInst($inst); $this->view->logos = $logoslisted; $form = new AddStaffLogoForm(); $form->details->setLegend('Add a logo: '); $this->view->form = $form; if ($this->_request->isPost()) { $formData = $this->_request->getPost(); if ($form->isValid($formData)) { $upload = new Zend_File_Transfer_Adapter_Http(); $upload->addValidator('NotExists', true, array(self::LOGOPATH)); if ($upload->isValid()) { $filename = $form->getValue('logo'); $largepath = self::LOGOPATH; $original = $largepath . $filename; $name = substr($filename, 0, strrpos($filename, '.')); $ext = '.jpg'; $converted = $name . $ext; $insertData = array(); $insertData['image'] = $converted; $insertData['instID'] = $inst; $insertData['created'] = $this->getTimeForForms(); $insertData['createdBy'] = $this->getIdentityForForms(); foreach ($insertData as $key => $value) { if (is_null($value) || $value == "") { unset($insertData[$key]); } } $replace = $form->getValue('replace'); if ($replace == 1) { foreach ($logoslisted as $l) { unlink(self::LOGOPATH . 'thumbnails/' . $l['image']); unlink(self::LOGOPATH . $l['image']); unlink(self::LOGOPATH . 'resized/' . $l['image']); } } $smallpath = self::LOGOPATH . 'thumbnails/' . $converted; $mediumpath = self::LOGOPATH . 'resized/' . $converted; //create medium size $phMagick = new phMagick($original, $mediumpath); $phMagick->resize(300, 0); $phMagick->convert(); $phMagick = new phMagick($original, $smallpath); $phMagick->resize(100, 0); $phMagick->convert(); $logos->insert($insertData); $upload->receive(); $this->getFlash()->addMessage('The image has been resized and zoomified!'); $this->redirect('/users/account/'); } else { $this->getFlash()->addMessage('There is a problem with your upload. Probably that image exists.'); $this->view->errors = $upload->getMessages(); } } else { $form->populate($formData); $this->getFlash()->addMessage('Check your form for errors'); } } }
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; }
/** * 上传头像 */ public function updateavatarAction() { //这种方式能得到urid $urid = $_GET['urid']; $imgName = md5($urid) . '.jpg'; $fileDir = __PUBLIC__ . '/upload/image/avatar/'; //ImgUploadController::upload($fileDir, $imgpath); $adapter = new Zend_File_Transfer_Adapter_Http(); // 不需要渲染模板页 $this->getFrontController()->setParam('noViewRenderer', true); // 你存放上传文件的文件夹 $adapter->setDestination($fileDir); $adapter->addValidator('Extension', false, 'gif,jpeg,png,jpg'); //设置上传文件的后缀名 $adapter->addValidator('Count', false, array('min' => 1, 'max' => 5)); //设置上传文件的个数 $adapter->addValidator('ImageSize', false, array('minwidth' => 0, 'maxwidth' => 40960, 'minhight' => 0, 'maxhight' => 40960)); ////设置上传图片的大小 $adapter->addValidator('FilesSize', false, array('min' => '4KB', 'max' => '4096KB')); ////设置上传文件的大小 //添加过滤器来修改上传文件的名称 if ($imgName) { $adapter->addFilter('Rename', array('target' => $imgName, 'overwrite' => true)); } //上传成功,把数据插入到数据库中 $imagePath = 'http://' . gethostbyname($_ENV['COMPUTERNAME']) . '/upload/image/avatar/' . $imgName; $result = $this->_userCenter->updateAvatar($urid, $imagePath); if ($result) { $out[Response::ERRNO] = 0; $out[Response::MSG] = '上传成功!'; Response::out($out); exit; } // 返回上传后出现在信息 if (!$adapter->receive()) { $out[Response::ERRNO] = 0; $out[Response::MSG] = '上传成功!'; Response::out($out); exit; } else { $out[Response::ERRNO] = 1; $out[Response::MSG] = '上传失败!'; Response::out($out); exit; } exit; }
public function videoAction() { /**Note *why invalid format??? */ try { $page = $this->_request->getParam('page_id'); $type = "videos"; $valid_videos = array('flv', 'mp4', '3gp', 'avi'); $upload = new Zend_File_Transfer_Adapter_Http(); $upload->addValidator('Extension', false, $valid_videos); if ($upload->isValid()) { $files = $upload->getFileInfo(); $data = array('title' => $this->_request->getParam('title'), 'description' => $this->_request->getParam('description'), 'source' => '@' . realpath($files['vid']['tmp_name'])); $video_post = $this->_postPage($page, $type, $data); if ($video_post) { echo $video_post['post_id']; exit; } } else { echo 'fail'; //$this->_redirect('') } } catch (FacebookApiException $e) { echo $e; exit; } }
/** * Upload image and return uploaded image file name or false * * @throws Mage_Core_Exception * @param string $scope the request key for file * @return bool|string */ public function uploadImage($scope) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->addValidator('ImageSize', true, $this->_imageSize); $adapter->addValidator('Size', true, self::MAX_FILE_SIZE); if ($adapter->isUploaded($scope)) { // validate image if (!$adapter->isValid($scope)) { Mage::throwException(Mage::helper('hello')->__('Uploaded image is not valid')); } $upload = new Varien_File_Uploader($scope); $upload->setAllowCreateFolders(true); $upload->setAllowedExtensions($this->_allowedExtensions); $upload->setAllowRenameFiles(true); $upload->setFilesDispersion(false); if ($upload->save($this->getBaseDir())) { return $upload->getUploadedFileName(); } } return false; }
/** * Store uploaded file in proper directory for module/page * * $params = array( * 'field' => 'form field name' * 'dir' => 'subdirectory for this file' * 'extensions' => array('jpg','png' ...) * 'mimetypes' => array('image/jpg', 'image/png') * ) * * @param array $params * @return string|false */ public function upload(array $params) { //check dir path $dir = $params['dir']; $paths = $this->getPath($dir); if ($paths === false) { $this->_lastErrorMessage = "Invalid dir [{$dir}]"; return false; } if (!isset($params['field'])) { $this->_lastErrorMessage = "Field not specifield"; return false; } $fieldName = $params['field']; $freeSpace = $this->getFreeSpace(); $extensions = array(); $mimeTypes = array(); //valid extensions if (isset($params['extensions']) && is_array($params['extensions'])) { $extensions = $params['extensions']; } //valid mime types if (isset($params['mimetypes']) && is_array($params['mimetypes'])) { $mimeTypes = $params['mimetypes']; } try { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->addValidator("Count", false, array("min" => 1, "max" => 5))->addValidator("Size", false, array("max" => $freeSpace))->addValidator("Extension", false, $extensions)->addValidator('MimeType', false, $mimeTypes); $adapter->setDestination($paths['real']); $files = $adapter->getFileInfo(); $result = array(); foreach ($files as $file => $info) { // file uploaded ? if (!$adapter->isUploaded($info['name']) || !$adapter->isValid($info['name'])) { $this->_lastErrorMessage = implode(" ", $adapter->getMessages()); continue; } if (strpos($file, $fieldName) !== 0) { continue; } if ($adapter->receive($info["name"])) { $result[] = $dir . "/" . $info["name"]; } } if (count($result)) { return $result; } else { if ($this->_lastErrorMessage == '') { $this->_lastErrorMessage = "No files uploaded"; } else { $this->_lastErrorMessage .= ". No files uploaded"; } return false; } } catch (Exception $ex) { $this->_lastErrorMessage = $ex->getMessage(); return false; } }
/** !! ************************************************************************ * The following methods take the request data, validate it, parse it, * and store it if there were no previous errors. ************************************************************************ */ public function basicProfileSave($request_data) { global $error_msg; $thumb = null; $file_name = null; $file_mime_type = null; $file_size = null; $apiDataArray = array('person' => null); $this->isError = TRUE; if (empty($request_data['first_name'])) { $this->message = __('Fields marked with * can not be empty, First name can not be empty.'); } else { if (!empty($request_data['pass']) || !empty($request_data['conpass'])) { $set_new_password = true; $new_password_ok = false; if ($request_data['pass'] != $request_data['conpass']) { $this->message = __('Password and confirm password should match.'); } else { if (strlen($request_data['pass']) < PA::$password_min_length) { $this->message = sprintf(__('Password should be of %s characters or more.'), PA::$password_min_length); } else { if (strlen($request_data['pass']) > PA::$password_max_length) { $this->message = sprintf(__('Password should be less than %s charcaters.'), PA::$password_max_length); } else { // all is good $new_password_ok = true; } } } } } if (isset($request_data['postal_code']) && isset($request_data['postal_code']['value']) && !empty($request_data['postal_code']['value'])) { $zipCode = trim($request_data['postal_code']['value']); $validator = new Zend_Validate_PostCode("en_US"); if (!$validator->isValid($zipCode)) { $this->message = "The zip code is invalid."; } else { $request_data['postal_code']['value'] = $zipCode; $apiDataArray['person']['zip_code'] = $zipCode; } } if (isset($request_data['about']) && isset($request_data['about']['value']) && !empty($request_data['about']['value'])) { $about = trim($request_data['about']['value']); $validator = new Zend_Validate_StringLength(array('max' => 500)); if (!$validator->isValid($about)) { $this->message = "The about field is limited to 500 characters. There are " . strlen($about) . " characters in the about field"; } } if ($request_data['deletepicture'] == "true") { $this->handleDeleteUserPic($request_data); } /* Parag Jagdale - 10/27/2010: Upload files with Zend library, Resize files and upload to AmazonS3 */ if (empty($this->message) && !empty($_FILES['userfile']['name'])) { $file = null; // Recieve uploaded file $zendUploadAdapter = new Zend_File_Transfer_Adapter_Http(); $zendUploadAdapter->setDestination(PA::$upload_path); $zendUploadAdapter->addValidator('Size', false, '1MB')->addValidator('Count', false, 1)->addValidator('FilesSize', false, array('min' => '1kB', 'max' => '2MB'))->addValidator('Extension', false, array('jpeg', 'jpg', 'png', 'gif'))->addValidator('ImageSize', false, array('minwidth' => 40, 'maxwidth' => 1024, 'minheight' => 40, 'maxheight' => 768)); if (!$zendUploadAdapter->isValid()) { // Invalid image, so show errors $this->message = __("The image you selected as your photo has some errors: <br />" . implode("<br />", $zendUploadAdapter->getMessages())); } try { $zendUploadAdapter->receive(); } catch (Zend_File_Transfer_Exception $e) { $this->message = $e->getMessage(); } if (empty($this->message)) { //If there is no error message then try saving to amazon s3 // save images to amazon s3 global $app; $aws_key = null; $aws_secret_key = null; $aws_key = $app->configData['configuration']['api_keys']['value']['amazon_aws_key']['value']; $aws_secret_key = $app->configData['configuration']['api_keys']['value']['amazon_aws_secret']['value']; $amazon_bucket_name = $app->configData['configuration']['api_keys']['value']['amazon_s3_bucket']['value']; if (isset($aws_key) && isset($aws_secret_key)) { $s3 = null; $bucketAvailable = false; $bucketCreated = false; $s3 = new Zend_Service_Amazon_S3($aws_key, $aws_secret_key); if (isset($s3)) { $bucketCreated = false; $bucketAvailable = $s3->isBucketAvailable($amazon_bucket_name); if (!$bucketAvailable) { if ($s3->createBucket($amazon_bucket_name)) { // new bucket was created $bucketCreated = true; } } else { $bucketCreated = true; } if ($bucketCreated == true) { // delete old amazon s3 pictures $this->handleDeleteUserPic($request_data); $file_path = $zendUploadAdapter->getFileName('userfile', true); $file_name = $zendUploadAdapter->getFileName('userfile', false); $file_size = $zendUploadAdapter->getFileSize('userfile'); $file_name = $this->cleanupFileName($file_name); $file_info = getimagesize($file_path); $file_mime_type = isset($file_info) && isset($file_info['mime']) && !empty($file_info['mime']) ? $file_info['mime'] : null; $apiDataArray['person'] = array('avatar' => array('file_name' => $file_name, 'content_type' => $file_mime_type, 'file_size' => $file_size)); // api_call needs to be set to true in order for the User class to update the avatar and avatar_small fields $this->user_info->api_call = true; foreach ($this->_image_sizes as $imageSizeType => $imageDimensions) { // Resize image into thumbnails $imageAsString = null; try { $thumb = PhpThumbFactory::create($file_path); if (!isset($this->user_info->core_id) && !empty($this->user_info->core_id)) { $this->user_info->core_id = 0; } $objectPath = $this->buildAmazonS3ObjectURL($imageSizeType, $this->user_info->core_id, $file_name); if (isset($imageDimensions) && !empty($imageDimensions)) { // if this is an original size image, the width and height dont need to be set $thumb->adaptiveResize($imageDimensions['width'], $imageDimensions['height']); } $imageAsString = $thumb->getImageAsString(); $amazonURL = "http://s3.amazonaws.com/" . $amazon_bucket_name; switch ($imageSizeType) { case "large": $this->user_info->picture = $objectPath; $this->user_info->picture_dimensions = $imageDimensions; break; case "standard": $this->user_info->avatar = $objectPath; $this->user_info->avatar_dimensions = $imageDimensions; break; case "medium": $this->user_info->avatar_small = $objectPath; $this->user_info->avatar_small_dimensions = $imageDimensions; break; default: break; } } catch (Exception $e) { $this->message = $e->getMessage(); break; } if (isset($imageAsString) && !empty($imageAsString)) { // send object to AmazonS3 $s3->putObject($amazon_bucket_name . $objectPath, $imageAsString, array(Zend_Service_Amazon_S3::S3_ACL_HEADER => Zend_Service_Amazon_S3::S3_ACL_PUBLIC_READ)); } } } } } } } if (empty($this->message)) { // Add first name and last name if they have been changed to the api update data array if ($this->user_info->first_name != $request_data['first_name'] || $this->user_info->last_name != $request_data['last_name']) { $apiDataArray['person']['name'] = $request_data['first_name'] . ' ' . $request_data['last_name']; } //If there is no error message then try saving the user information. $this->user_info->first_name = $request_data['first_name']; $this->user_info->last_name = $request_data['last_name']; try { if (!empty($request_data['pass'])) { $passwordSaltArray = $this->EncryptPassword($request_data['pass']); if (isset($passwordSaltArray)) { list($encryptedPassword, $salt) = $passwordSaltArray; $this->user_info->password = $encryptedPassword; $apiDataArray['person']['encrypted_password'] = $encryptedPassword; // remove last $ from salt because ruby doesn't like it $salt = rtrim($salt, '$'); $apiDataArray['person']['password_salt'] = $salt; } else { $this->message = "Your password could not be changed, please contact the administrator."; } } } catch (Exception $e) { $this->message = $e->getMessage(); } } if (empty($this->message)) { try { $this->user_info->save(); $dynProf = new DynamicProfile($this->user_info); $dynProf->processPOST('basic'); $dynProf->save('basic', GENERAL); $this->message = __('Profile updated successfully.'); // $this->redirect2 = PA_ROUTE_EDIT_PROFILE; // $this->queryString = '?type='.$this->profile_type; //TODO: change URL after the contributions activity stream URLs have been changed $url = CC_APPLICATION_URL . CC_APPLICATION_URL_TO_API . $this->user_info->user_id; // Try to send updated data to Core (Ruby) $this->sendUserDataToCivicCommons($url, $apiDataArray); $this->isError = FALSE; } catch (PAException $e) { $this->message = $e->message; } } $error_msg = $this->message; }
/** * @param \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object * @param \Magento\Catalog\Model\Product\Option $option * @param array $fileFullPath * @return \Zend_File_Transfer_Adapter_Http|\Zend_Validate $object * @throws \Magento\Framework\Exception\InputException */ protected function buildImageValidator($object, $option, $fileFullPath = null) { $dimensions = []; if ($option->getImageSizeX() > 0) { $dimensions['maxwidth'] = $option->getImageSizeX(); } if ($option->getImageSizeY() > 0) { $dimensions['maxheight'] = $option->getImageSizeY(); } if (count($dimensions) > 0) { if ($fileFullPath !== null && !$this->isImage($fileFullPath)) { throw new \Magento\Framework\Exception\InputException(__('File \'%1\' is not an image.', $option->getTitle())); } $object->addValidator(new \Zend_Validate_File_ImageSize($dimensions)); } // File extension $allowed = $this->parseExtensionsString($option->getFileExtension()); if ($allowed !== null) { $object->addValidator(new \Zend_Validate_File_Extension($allowed)); } else { $forbidden = $this->parseExtensionsString($this->getConfigData('forbidden_extensions')); if ($forbidden !== null) { $object->addValidator(new \Zend_Validate_File_ExcludeExtension($forbidden)); } } $object->addValidator(new \Zend_Validate_File_FilesSize(['max' => $this->fileSize->getMaxFileSize()])); return $object; }
public function __construct($arrParam = array(), $options = null) { ////////////////////////////////// //Kiem tra group_name ///////////// ////////////////////////////////// if ($arrParam['action'] == 'add') { $options = array('table' => 'da_user_group', 'field' => 'group_name'); } elseif ($arrParam['action'] == 'edit') { $options = array('table' => 'da_user_group', 'field' => 'group_name', 'exclude' => array('field' => 'id', 'value' => $arrParam['id'])); } $validator = new Zend_Validate(); $validator->addValidator(new Zend_Validate_NotEmpty(), true)->addValidator(new Zend_Validate_StringLength(3, 32), true)->addValidator(new Zend_Validate_Regex('#^[a-zA-Z0-9\\-_\\.\\s]+$#'), true)->addValidator(new Zend_Validate_Db_NoRecordExists($options), true); if (!$validator->isValid($arrParam['group_name'])) { $message = $validator->getMessages(); $this->_messageError['group_name'] = 'Group name: ' . current($message); $arrParam['group_name'] = ''; } ////////////////////////////////// //Kiem tra Avatar /////////// ////////////////////////////////// $upload = new Zend_File_Transfer_Adapter_Http(); $fileInfo = $upload->getFileInfo('avatar'); $fileName = $fileInfo['avatar']['name']; if (!empty($fileName)) { $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'avatar'); $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'avatar'); if (!$upload->isValid('avatar')) { $message = $upload->getMessages(); $this->_messageError['avatar'] = 'Avatar: ' . current($message); } } ////////////////////////////////// //Kiem tra ranking /////////// ////////////////////////////////// $upload = new Zend_File_Transfer_Adapter_Http(); $fileInfo = $upload->getFileInfo('ranking'); $fileName = $fileInfo['ranking']['name']; if (!empty($fileName)) { $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'ranking'); $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'ranking'); if (!$upload->isValid('ranking')) { $message = $upload->getMessages(); $this->_messageError['ranking'] = 'Ranking: ' . current($message); } } ////////////////////////////////// //Kiem tra Admin Control Panel ///////////// ////////////////////////////////// if (empty($arrParam['group_acp']) || !isset($arrParam['group_acp'])) { $arrParam['group_acp'] = 0; } ////////////////////////////////// //Kiem tra Group Default ///////////// ////////////////////////////////// if (empty($arrParam['group_default']) || !isset($arrParam['group_default'])) { $arrParam['group_default'] = 0; } ////////////////////////////////// //Kiem tra Status ///////////// ////////////////////////////////// if (empty($arrParam['status']) || !isset($arrParam['status'])) { $arrParam['status'] = 0; } ////////////////////////////////// //Kiem tra order ///////////// ////////////////////////////////// $validator = new Zend_Validate(); $validator->addValidator(new Zend_Validate_Digits(), true); if (!$validator->isValid($arrParam['order'])) { $message = $validator->getMessages(); $this->_messageError['order'] = 'Order: ' . current($message); $arrParam['order'] = ''; } //======================================== // TRUYEN CAC GIA TRI DUNG VAO MANG $_arrData //======================================== $this->_arrData = $arrParam; }
public function importAction() { $this->_helper->layout->disableLayout(); try { $upload = new Zend_File_Transfer_Adapter_Http(); $upload->addValidator('Count', 1, 1)->addValidator('Extension', false, 'csv'); if (!$upload->isValid()) { throw new Zend_Validate_Exception(); } $files = $upload->getFileInfo(); $filename = $files['data']['tmp_name']; if (!file_exists($filename) || !($fp = fopen($filename, 'r'))) { throw new Axis_Exception(Axis::translate('core')->__("Can't open file : %s", $filename)); } $siteId = $this->_getParam('site_id', Axis::getSiteId()); $keys = fgetcsv($fp); $rowSize = count($keys); $model = Axis::model('shippingTable/rate'); $countrySet = Axis::model('location/country')->select(array('iso_code_3', 'id'))->fetchPairs(); while (!feof($fp)) { $value = fgetcsv($fp); if (!is_array($value)) { continue; } $value = array_pad($value, $rowSize, ''); $value = array_combine($keys, $value); $countryId = 0; if (isset($countrySet[$value['Country']])) { $countryId = $countrySet[$value['Country']]; } $zoneSet = Axis::model('location/zone')->select(array('code', 'id'))->where('country_id = ?', $countryId)->fetchPairs(); $zoneId = 0; if (isset($zoneSet[$value['Region/State']])) { $zoneId = $zoneSet[$value['Region/State']]; } $model->getRow(array('site_id' => $siteId, 'country_id' => $countryId, 'zone_id' => $zoneId, 'zip' => $value['Zip'], 'value' => $value['Value'], 'price' => $value['Price']))->save(); } } catch (Zend_Exception $e) { return $this->getResponse()->appendBody(Zend_Json::encode(array('success' => false, 'messages' => array('error' => $e->getMessage())))); } return $this->getResponse()->appendBody(Zend_Json::encode(array('success' => true, 'messages' => array('success' => Axis::translate('admin')->__('Data was imported successfully'))))); }
/** * Uploads a batch file to the rig client. The user must already been to be * assigned to a rig. * <br /> * Unlike the other functions in this controller, the response is not JSON but * a text string with the format: * <ul> * <li>true - Succeeding uploading and invoking batch control.</li> * <li>false; <error reason;> - Failed uploading or invoking batch * control with a provided reason.</li> * </ul> */ public function torigclientAction() { $this->_helper->viewRenderer->setNoRender(); $this->_helper->layout()->disableLayout(); $response = Sahara_Soap::getSchedServerSessionClient()->getSessionInformation(array('userQName' => $this->_auth->getIdentity())); if (!$response->isInSession) { /* Not in session, so unable to determine the rig clients address. */ $error = array('success' => 'false', 'error' => array('code' => -1, 'operation' => 'Batch control request', 'reason' => 'not in session')); echo "error; Not in session."; return; } $adapter = new Zend_File_Transfer_Adapter_Http(); $dest = $this->_config->upload->dir; if (!$dest) { $this->_logger->error("Batch download directory not configured, 'upload.dir' property."); throw new Exception("Batch download directory not configured."); } $adapter->setDestination($dest)->addValidator('Count', false, 1); /* Size file validator. */ if ($size = $this->_config->upload->size) { $adapter->addValidator('FilesSize', false, $size); } /* Extension file validator. */ if ($ext = $this->_config->upload->extension) { $adapter->addValidator('Extension', false, $ext); } if (!$adapter->receive()) { $error = 'File validation has failed.'; foreach ($adapter->getMessages() as $k => $v) { switch ($k) { case 'fileExtensionFalse': $error .= ' The file extension was incorrect.'; break; case 'fileUploadErrorIniSize': case 'fileUploadErrorFormSize': $error .= ' The file size was too large.'; break; default: $error .= ' ' . $v; break; } } echo "error; {$error}"; return; } $file = $adapter->getFileName(); list($ns, $name) = explode(':', $this->_auth->getIdentity()); $request = array('requestor' => $name, 'fileName' => basename($file), 'batchFile' => file_get_contents($file)); if (!$request['batchFile']) { $this->_logger->warn("Failed to read batch file {$file}."); echo 'false; Upload to read batch file.'; return; } unlink($file); try { $rigClient = new Sahara_Soap($response->contactURL . '?wsdl'); header('Content-Type', 'text/plain'); $response = $rigClient->performBatchControl($request); echo $response->success ? 'true' : 'false; ' . $response->error->reason; } catch (Exception $ex) { $this->_logger->error("Soap error calling batch 'performPrimitiveControl'. Message: " . $ex->getMessage() . ', code: ' . $ex->getCode() . '.'); echo 'false; ' . $ex->getMessage(); } }
/** * 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; }
/** * 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; }
/** Give them a logo * @access public * @return void * */ public function logoAction() { $form = new AddStaffLogoForm(); $form->details->setLegend('Add a logo: '); $this->view->form = $form; if ($this->_request->isPost()) { $formData = $this->_request->getPost(); if ($form->isValid($formData)) { $upload = new Zend_File_Transfer_Adapter_Http(); $upload->addValidator('NotExists', true, array(self::LOGOPATH)); if ($upload->isValid()) { $filename = $form->getValue('image'); $insertData = array(); $insertData['host'] = $filename; $insertData['updated'] = $this->getTimeForForms(); $insertData['updatedBy'] = $this->getIdentityForForms(); $regions = new StaffRegions(); $where = array(); $where[] = $regions->getAdapter()->quoteInto('id = ?', $this->getParam('id')); $regions->update($insertData, $where); $upload->receive(); $this->getFlash()->addMessage('The image has been resized and zoomified!'); $this->redirect('/admin/contacts/institution/id/' . $this->getParam('id')); } else { $this->getFlash()->addMessage('There is a problem with your upload. Probably that image exists.'); $this->view->errors = $upload->getMessages(); } } else { $form->populate($formData); $this->getFlash()->addMessage('Check your form for errors'); } } }
/** * Metdo responsavel por persistir os uploads * @param type $destino * @param type $thumb * @param type $validFile * @param type $invalidFile * @return type */ public static function upload($destino = 'anexoArtefato', $thumb = FALSE, $validFile = TRUE, $invalidFile = TRUE, $validImageSize = TRUE) { $configs = \Core_Registry::get('configs'); $upload = new \Zend_File_Transfer_Adapter_Http(); $files = $upload->getFileInfo(); $filesUp = array(); $return = array(); $error = false; $pasta = 'anexo-material'; if ($destino == 'anexoArtefato') { $pasta = 'anexo-artefato'; } $path = current(explode('application', __DIR__)) . 'data' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . $pasta . DIRECTORY_SEPARATOR; foreach ($files as $file => $info) { $upload = new \Zend_File_Transfer_Adapter_Http(); $upload->setDestination($path); $upload->setValidators(array()); $upload->addValidator('Size', TRUE, array('max' => '100MB', 'messages' => "O tamanho do arquivo é superior ao permitido. O tamanho permitido é 100MB.")); self::_invalidFile($invalidFile, $upload); self::_validFile($validFile, $upload); self::_validImageSize($validImageSize, $upload); self::_getValidator($upload); if ($upload->isValid($file)) { $fileinfo = pathinfo($info['name']); $upload->receive($file); $filesUp[] = $upload->getFileName($file); $return[] = array('name' => $upload->getFileName($file), 'size' => $upload->getFileSize($file)); } else { $error = $upload->getMessages(); break; } } if ($error) { if (count($filesUp)) { foreach ($filesUp as $file) { unlink($file); } } return array('errors' => $error); } if ($thumb) { $pasta = current(explode('application', __DIR__)) . 'data' . DIRECTORY_SEPARATOR . 'upload' . DIRECTORY_SEPARATOR . 'thumbs' . DIRECTORY_SEPARATOR; foreach ($filesUp as $endereco) { $fileinfo = pathinfo($endereco); $image = \WideImage::load($endereco); $image->resize(300, 300, 'outside')->crop('50% - 150', '50% - 150', 300, 300)->saveToFile($pasta . $fileinfo['filename'] . '_300_X_300.' . strtolower($fileinfo['extension'])); $image->resize(133, 89, 'outside')->crop('50% - 67', '50% - 45', 133, 89)->saveToFile($pasta . $fileinfo['filename'] . '_133_X_89.' . strtolower($fileinfo['extension'])); } } return $return; }