Exemplo n.º 1
0
 public function uploadAjaxAction()
 {
     $this->_helper->layout->setLayout('ajax');
     $data = $this->_request->getPost();
     $extraDados = "";
     if (isset($data['id'])) {
         $extraDados = $data['id'] . '-';
     }
     $path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'uploads';
     $upload = new Zend_File_Transfer_Adapter_Http();
     $upload->setDestination($path);
     // Returns all known internal file information
     $files = $upload->getFileInfo();
     foreach ($files as $file => $info) {
         // Se não existir arquivo para upload
         if (!$upload->isUploaded($file)) {
             print '<p class="alert alert-warning">Nenhum arquivo selecionado para upload<p>';
             continue;
         } else {
             $fileName = $extraDados . str_replace(' ', '_', strtolower($info['name']));
             // Renomeando o arquivo
             $upload->addFilter('Rename', array('target' => $path . DIRECTORY_SEPARATOR . $fileName, 'overwrite' => true));
         }
         // Validação do arquivo ?
         if (!$upload->isValid($file)) {
             print '<p class="alert alert-danger" > <b>' . $file . '</b>. Arquivo inválido </p>';
             continue;
         } else {
             if ($upload->receive($info['name'])) {
                 print '<p class="alert alert-success"> Arquivo: <b>' . $info['name'] . '</b> enviado com sucesso e renomeado para: <b>' . $fileName . '</b> </p>';
             }
         }
     }
 }
Exemplo n.º 2
0
 /**
  * @param string $attributeCode
  * @param string $type
  * @return bool
  */
 protected static function handleUpload($attributeCode, $type)
 {
     if (!isset($_FILES)) {
         return false;
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     if ($adapter->isUploaded('typecms_' . $attributeCode . '_')) {
         if (!$adapter->isValid('typecms_' . $attributeCode . '_')) {
             Mage::throwException(Mage::helper('typecms')->__('Uploaded ' . $type . ' is invalid'));
         }
         $upload = new Varien_File_Uploader('typecms[' . $attributeCode . ']');
         $upload->setAllowCreateFolders(true);
         if ($type == 'image') {
             $upload->setAllowedExtensions(array('jpg', 'gif', 'png'));
         }
         $upload->setAllowRenameFiles(true);
         $upload->setFilesDispersion(false);
         try {
             if ($upload->save(Mage::helper('typecms')->getBaseImageDir())) {
                 return $upload->getUploadedFileName();
             }
         } catch (Exception $e) {
             Mage::throwException('Uploaded ' . $type . ' is invalid');
         }
     }
     return false;
 }
Exemplo n.º 3
0
 /**
  * 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!');
     }
 }
Exemplo n.º 4
0
 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);
 }
Exemplo n.º 5
0
 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;
     }
 }
Exemplo n.º 6
0
 public function upload($params = array())
 {
     if (!is_dir($params['destination_folder'])) {
         mkdir($params['destination_folder'], 0777, true);
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($params['destination_folder']);
     $adapter->setValidators($params['validators']);
     if ($adapter->getValidator('ImageSize')) {
         $adapter->getValidator('ImageSize')->setMessages(array('fileImageSizeWidthTooBig' => $this->_('Image too large, %spx maximum allowed.', '%maxwidth%'), 'fileImageSizeWidthTooSmall' => $this->_('Image not large enough, %spx minimum allowed.', '%minwidth%'), 'fileImageSizeHeightTooBig' => $this->_('Image too high, %spx maximum allowed.', '%maxheight%'), 'fileImageSizeHeightTooSmall' => $this->_('Image not high enough, %spx minimum allowed.', '%minheight%'), 'fileImageSizeNotDetected' => $this->_("The image size '%s' could not be detected.", '%value%'), 'fileImageSizeNotReadable' => $this->_("The image '%s' does not exist", '%value%')));
     }
     if ($adapter->getValidator('Size')) {
         $adapter->getValidator('Size')->setMessages(array('fileSizeTooBig' => $this->_("Image too large, '%s' allowed.", '%max%'), 'fileSizeTooSmall' => $this->_("Image not large enough, '%s' allowed.", '%min%'), 'fileSizeNotFound' => $this->_("The image '%s' does not exist", '%value%')));
     }
     if ($adapter->getValidator('Extension')) {
         $adapter->getValidator('Extension')->setMessages(array('fileExtensionFalse' => $this->_("Extension not allowed, '%s' only", '%extension%'), 'fileExtensionNotFound' => $this->_("The file '%s' does not exist", '%value%')));
     }
     $files = $adapter->getFileInfo();
     $return_file = '';
     foreach ($files as $file => $info) {
         //Créé l'image sur le serveur
         if (!$adapter->isUploaded($file)) {
             throw new Exception($this->_('An error occurred during process. Please try again later.'));
         } else {
             if (!$adapter->isValid($file)) {
                 if (count($adapter->getMessages()) == 1) {
                     $erreur_message = $this->_('Error : <br/>');
                 } else {
                     $erreur_message = $this->_('Errors : <br/>');
                 }
                 foreach ($adapter->getMessages() as $message) {
                     $erreur_message .= '- ' . $message . '<br/>';
                 }
                 throw new Exception($erreur_message);
             } else {
                 $new_name = uniqid("file_");
                 if (isset($params['uniq']) and $params['uniq'] == 1) {
                     if (isset($params['desired_name'])) {
                         $new_name = $params['desired_name'];
                     } else {
                         $format = pathinfo($info["name"], PATHINFO_EXTENSION);
                         if (!in_array($format, array("png", "jpg", "jpeg", "gif"))) {
                             $format = "jpg";
                         }
                         $new_name = $params['uniq_prefix'] . uniqid() . ".{$format}";
                     }
                     $new_pathname = $params['destination_folder'] . '/' . $new_name;
                     $adapter->addFilter(new Zend_Filter_File_Rename(array('target' => $new_pathname, 'overwrite' => true)));
                 }
                 $adapter->receive($file);
                 $return_file = $new_name;
             }
         }
     }
     return $return_file;
 }
Exemplo n.º 7
0
 /**
  * Upload preview image
  *
  * @param string $scope the request key for file
  * @param string $destinationPath path to upload directory
  * @return bool
  * @throws \Magento\Framework\Exception\LocalizedException
  */
 public function uploadPreviewImage($scope, $destinationPath)
 {
     if (!$this->_transferAdapter->isUploaded($scope)) {
         return false;
     }
     if (!$this->_transferAdapter->isValid($scope)) {
         throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Uploaded image is not valid'));
     }
     $upload = $this->_uploaderFactory->create(['fileId' => $scope]);
     $upload->setAllowCreateFolders(true);
     $upload->setAllowedExtensions($this->_allowedExtensions);
     $upload->setAllowRenameFiles(true);
     $upload->setFilesDispersion(false);
     if (!$upload->checkAllowedExtension($upload->getFileExtension())) {
         throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Invalid image file type.'));
     }
     if (!$upload->save($destinationPath)) {
         throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Image can not be saved.'));
     }
     return $destinationPath . '/' . $upload->getUploadedFileName();
 }
 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;
 }
Exemplo n.º 9
0
 public function uploadAction()
 {
     if (!empty($_FILES)) {
         try {
             $path = '/var/apps/iphone/';
             $base_path = Core_Model_Directory::getBasePathTo($path);
             $filename = uniqid() . '.pem';
             if (!is_dir($base_path)) {
                 mkdir($base_path, 0775, true);
             }
             $adapter = new Zend_File_Transfer_Adapter_Http();
             $adapter->setDestination($base_path);
             $adapter->setValidators(array('Extension' => array('pem', 'case' => false)));
             $adapter->getValidator('Extension')->setMessages(array('fileExtensionFalse' => $this->_("Extension not allowed, \\'%s\\' only", '%extension%')));
             $files = $adapter->getFileInfo();
             foreach ($files as $file => $info) {
                 if (!$adapter->isUploaded($file)) {
                     throw new Exception($this->_('An error occurred during process. Please try again later.'));
                 } else {
                     if (!$adapter->isValid($file)) {
                         if (count($adapter->getMessages()) == 1) {
                             $erreur_message = $this->_('Error : <br/>');
                         } else {
                             $erreur_message = $this->_('Errors : <br/>');
                         }
                         foreach ($adapter->getMessages() as $message) {
                             $erreur_message .= '- ' . $message . '<br/>';
                         }
                         throw new Exception($erreur_message);
                     } else {
                         $adapter->addFilter(new Zend_Filter_File_Rename(array('target' => $base_path . $filename, 'overwrite' => true)));
                         $adapter->receive($file);
                     }
                 }
             }
             $certificat = new Push_Model_Certificat();
             $certificat->find('ios', 'type');
             if (!$certificat->getId()) {
                 $certificat->setType('ios');
             }
             $certificat->setPath($path . $filename)->save();
             $datas = array('success' => 1, 'files' => 'eeeee', 'message_success' => $this->_('Infos successfully saved'), 'message_button' => 0, 'message_timeout' => 2);
         } catch (Exception $e) {
             $datas = array('error' => 1, 'message' => $e->getMessage());
         }
         $this->getLayout()->setHtml(Zend_Json::encode($datas));
     }
 }
Exemplo n.º 10
0
 public function addAction()
 {
     $userNs = new Zend_Session_Namespace("members");
     $this->view->title = "City - Add";
     $this->view->headTitle(" -  " . $this->view->title);
     $form = new Admin_Form_City();
     $this->view->form = $form;
     $this->view->successMsg = "";
     if ($this->getRequest()->isPost()) {
         $formData = $this->getRequest()->getPost();
         if ($form->isValid($formData)) {
             $upload = new Zend_File_Transfer_Adapter_Http();
             //---main image
             if ($upload->isValid('logo')) {
                 $upload->setDestination("images/logo/");
                 try {
                     $upload->receive('logo');
                 } catch (Zend_File_Transfer_Exception $e) {
                     $msg = $e->getMessage();
                 }
                 $upload->setOptions(array('useByteString' => false));
                 $id = time();
                 $file_name = $upload->getFileName('logo');
                 $cardImageTypeArr = explode(".", $file_name);
                 $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                 $target_file_name = "logo_" . $id . ".{$ext}";
                 $targetPath = 'media/picture/city/logo/' . $target_file_name;
                 $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                 $filterFileRename->filter($file_name);
                 $formData['logo'] = $target_file_name;
                 /*--- Generate Thumbnail ---*/
                 $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                 $thumb->resize(100, 100);
                 $thumb->save($targetPath = 'media/picture/city/logo/thumb_' . $target_file_name);
             }
             $usersNs = new Zend_Session_Namespace("members");
             $formData['userId'] = $usersNs->userId;
             $this->view->warningMsg = '';
             $model = new Application_Model_City($formData);
             $id = $model->save($model);
             $form->reset();
             $this->view->successMsg = "City added successfully. City Id : {$id}";
         } else {
             $form->populate($formData);
         }
     }
 }
Exemplo n.º 11
0
 public function uploadAction()
 {
     $request = $this->getRequest();
     $table = new Model_DbTable_Sheets();
     $select = $table->select();
     $select->where('id = ?', $request->id);
     $sheet = $table->fetchRow($select);
     if (!$this->view->authenticated || $sheet->user_id != $this->view->identity->id) {
         $this->_redirector->gotoRoute(array(), 'login');
     }
     if ($request->isPost()) {
         $path = UPLOAD_PATH . '/sheets/';
         if (!file_exists($path)) {
             mkdir(str_replace('//', '/', $path), 0755, true);
         }
         $upload = new Zend_File_Transfer_Adapter_Http();
         $upload->setDestination($path);
         $upload->addValidators(array(array('Count', false, 5), array('Size', false, '2MB'), array('Extension', false, array('pdf', 'midi', 'mid'))));
         if ($upload->isValid()) {
             $table = new Model_DbTable_Downloads();
             $pattern = array('/-/', '/_/', '/\\s+/');
             $replace = array(' - ', ' ', ' ');
             foreach ($upload->getFileInfo() as $file => $contents) {
                 $info = pathinfo($contents['name']);
                 $row = $table->createRow();
                 $row->sheet_id = $sheet->id;
                 $row->type = strtolower($info['extension']) == 'pdf' ? 'PDF' : 'MIDI';
                 $title = preg_replace($pattern, $replace, $info['filename']);
                 $row->title = ucwords($title);
                 $row->save();
                 $name = $row->id . ($row->type == 'MIDI' ? '.mid' : '.pdf');
                 $upload->addFilter('Rename', array('target' => $name), $file);
                 $upload->receive($file);
             }
             if ($upload->isReceived()) {
                 return $this->_redirector->gotoRoute(array('controller' => 'sheet', 'id' => $request->id), 'view');
             }
         }
         $this->view->errors = $upload->getMessages();
     }
     $this->view->headTitle('Upload sheet file(s)');
     $this->view->headScript()->appendFile('/js/multifile.js');
     $this->view->headScript()->appendFile('/js/upload.js');
     $this->view->sheetId = $request->id;
 }
 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;
 }
Exemplo n.º 13
0
 /**
  *
  * @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;
     }
 }
Exemplo n.º 14
0
 public function addCountryImageEXPAction()
 {
     $this->_helper->layout->disableLayout();
     //$this->_helper->viewRenderer->setNoRender(true);
     //get request variables
     $id = $this->_getParam("id");
     $page = $this->_getParam("page");
     $selTab = $this->_getParam("tab", "tabs-7");
     $this->view->cityId = $id;
     //create image upload form
     $uploadForm = new Admin_Form_CityImages();
     $elements = $uploadForm->getElements();
     $uploadForm->clearDecorators();
     foreach ($elements as $element) {
         $element->removeDecorator('label');
         $element->removeDecorator('td');
         $element->removeDecorator('tr');
         $element->removeDecorator('row');
         $element->removeDecorator('HtmlTag');
         $element->removeDecorator('placement');
         $element->removeDecorator('data');
     }
     $this->view->uploadForm = $uploadForm;
     //selects country images to edit
     $oldImageArr = array();
     $oldImageSortingArr = array();
     $lonelyPlanetCountryM = new Application_Model_LonelyPlanetCountry();
     $lonelyPlanetCountryM = $lonelyPlanetCountryM->find($id);
     if (false !== $lonelyPlanetCountryM) {
         $oldImageArr = unserialize($lonelyPlanetCountryM->getImages());
         //echo "<pre>";
         //print_r($oldImageArr);
         for ($oCnt = 0; $oCnt < count($oldImageArr); $oCnt++) {
             $imgArr = $oldImageArr[$oCnt];
             $imgArr["alt_text"] = "";
             $imgArr["slide_link_url"] = "";
             $imgArr["slide_link_target"] = "";
             $imgArr["weight"] = $oCnt + 1;
             $oldImageSortingArr[] = $imgArr;
         }
         //print_r($oldImageSortingArr);
         //echo "</pre>";
         //exit;
     }
     $request = $this->getRequest();
     if ($request->isPost()) {
         $options = $request->getPost();
         if ($uploadForm->isValid($options)) {
             $target_file_name = "";
             //Upload image strat here
             $upload = new Zend_File_Transfer_Adapter_Http();
             if ($upload->isValid()) {
                 $upload->setDestination("media/picture/country/");
                 try {
                     $upload->receive();
                 } catch (Zend_File_Transfer_Exception $e) {
                     $msg = $e->getMessage();
                 }
                 $upload->setOptions(array('useByteString' => false));
                 $file_name = $upload->getFileName('countryImage');
                 $cardImageTypeArr = explode(".", $file_name);
                 $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                 $target_file_name = "country{$country_id}_" . time() . ".{$ext}";
                 $targetPath = "media/picture/country/images/" . $target_file_name;
                 $targetPathThumb = "media/picture/country/images/thumbs/" . $target_file_name;
                 $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                 $filterFileRename->filter($file_name);
                 $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                 $thumb->resize(625, 330);
                 $thumb->save($targetPathThumb);
             }
             //end if
             //upload image Ends here
             //set country Image array
             $addImageArr = array();
             $addImageArr["image_caption"] = $options["slideTitle"];
             $addImageArr["image_photographer"] = "Gap Daemon";
             $addImageArr["image_filename"] = "/images/" . $target_file_name;
             $addImageArr["image_thumbnail_filename"] = "/images/thumbs/" . $target_file_name;
             $addImageArr["alt_text"] = $options["altText"];
             $addImageArr["slide_link_url"] = $options["slideLinkUrl"];
             $addImageArr["slide_link_target"] = $options["slideLinkTarget"];
             $addImageArr["weight"] = $options["weight"];
             $oldImageSortingArr[count($oldImageSortingArr)] = $addImageArr;
             $newCountryImageArr = serialize($oldImageSortingArr);
             $lonelyPlanetCountryM->setImages($newCountryImageArr);
             $resImg = $lonelyPlanetCountryM->save();
             if ($resImg) {
                 $_SESSION['errorMsg'] = "Images has been saved successfully.";
                 echo "<script>window.opener.location='/admin/featured-city/edit-country/id/{$id}/page/{$page}/tab/{$selTab}';</script>";
                 echo "<script>window.close();</script>";
             } else {
                 $this->view->errorMsg = "Error occured, please try again later.";
             }
         } else {
             $uploadForm->reset();
             $uploadForm->populate($options);
         }
     }
     //end if
     $this->render("add-city-image");
 }
Exemplo n.º 15
0
 public function isValidParent($files = null)
 {
     return parent::isValid($files);
 }
Exemplo n.º 16
0
 /** 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');
         }
     }
 }
Exemplo n.º 17
0
 public function editAction()
 {
     $type = "module";
     if ($this->_getParam('type') != "") {
         $type = $this->_getParam('type');
     }
     $this->view->type = $type;
     $id = $this->_getParam('id');
     $page = $this->_getParam('page');
     $model = new Application_Model_Content();
     $model = $model->find($id);
     $options['title'] = $model->getTitle();
     $options['alias'] = $model->getAlias();
     $options['body'] = $model->getBody();
     $options['status'] = $model->getStatus();
     $options['weight'] = $model->getWeight();
     $request = $this->getRequest();
     $form = new Admin_Form_Content();
     /****************************  Show/Hide fields as per module structure START ***************/
     //by default fields should be enabled
     $displayEditor = true;
     //remove form fields for fixed content
     if (in_array($model->getAlias(), $this->fixedTextMod)) {
         $form->removeElement('weight');
         $form->removeElement('status');
         $form->removeElement('whereText');
         $form->removeElement('whereUrl');
         $form->removeElement('whereUrlTarget');
         $form->removeElement('whereBodyText');
         $form->removeElement('whereBodyUrl');
         $form->removeElement('whereBodyUrlTarget');
         $form->removeElement('weekPhoto');
     } else {
         if ($model->getAlias() == "home_login_where_i_am") {
             $form->removeElement('body');
             $displayEditor = false;
             $arrBodyText = unserialize($model->getBody());
             foreach ($arrBodyText as $key => $value) {
                 $options[$key] = $value;
             }
             $form->removeElement('weekPhoto');
         } else {
             if ($model->getAlias() == "home_journal" || $model->getAlias() == "home_advertise") {
                 $form->removeElement('body');
                 $displayEditor = false;
                 $form->removeElement('whereText');
                 $form->removeElement('whereUrl');
                 $form->removeElement('whereUrlTarget');
                 $form->removeElement('whereBodyText');
                 $form->removeElement('whereBodyUrl');
                 $form->removeElement('whereBodyUrlTarget');
                 $form->removeElement('weekPhoto');
             } else {
                 if ($model->getAlias() == "home_photo_week") {
                     $form->removeElement('whereText');
                     $form->removeElement('whereUrl');
                     $form->removeElement('whereUrlTarget');
                     $form->removeElement('whereBodyText');
                     $form->removeElement('whereBodyUrl');
                     $form->removeElement('whereBodyUrlTarget');
                     $photoBodyArr = unserialize($model->getBody());
                     $target_file_name = $photoBodyArr["weekPhoto"];
                     //$options['weekPhoto'] = $photoBodyArr["weekPhoto"];
                     $this->view->weekPhoto = $target_file_name;
                     $options['body'] = $photoBodyArr["body"];
                 } else {
                     $form->removeElement('whereText');
                     $form->removeElement('whereUrl');
                     $form->removeElement('whereUrlTarget');
                     $form->removeElement('whereBodyText');
                     $form->removeElement('whereBodyUrl');
                     $form->removeElement('whereBodyUrlTarget');
                     $form->removeElement('weekPhoto');
                 }
             }
         }
     }
     //display editor as per module requirement
     $this->view->displayEditor = $displayEditor;
     /****************************  Show/Hide fields as per module structure END ***************/
     //populate form options
     $form->populate($options);
     if ($this->getRequest()->isPost()) {
         $options = $request->getPost();
         if ($form->isValid($options)) {
             //create array for module as per their structure and save in database as serialize array
             if ($options["alias"] == "home_login_where_i_am") {
                 $bodyTextArr["whereText"] = $options["whereText"];
                 $bodyTextArr["whereUrl"] = $options["whereUrl"];
                 $bodyTextArr["whereUrlTarget"] = $options["whereUrlTarget"];
                 $bodyTextArr["whereBodyText"] = $options["whereBodyText"];
                 $bodyTextArr["whereBodyUrl"] = $options["whereBodyUrl"];
                 $bodyTextArr["whereBodyUrlTarget"] = $options["whereBodyUrlTarget"];
                 $options["body"] = serialize($bodyTextArr);
             }
             //upload photo image for Photo of The Week Module
             if ($options["alias"] == "home_photo_week") {
                 //Upload image start here
                 $upload = new Zend_File_Transfer_Adapter_Http();
                 if ($upload->isValid()) {
                     $upload->setDestination("media/picture/home/");
                     try {
                         $upload->receive();
                     } catch (Zend_File_Transfer_Exception $e) {
                         $msg = $e->getMessage();
                     }
                     $upload->setOptions(array('useByteString' => false));
                     $file_name = $upload->getFileName('weekPhoto');
                     $cardImageTypeArr = explode(".", $file_name);
                     $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                     //unlink existing image
                     if ($ext != "" && $target_file_name != "") {
                         if (file_exists("media/picture/home/" . $target_file_name)) {
                             unlink("media/picture/home/" . $target_file_name);
                             unlink("media/picture/home/thumb_" . $target_file_name);
                         }
                     }
                     //$target_file_name = "weekPhoto_".time().".{$ext}";
                     $target_file_name = "photo-of-the-week.{$ext}";
                     $targetPath = "media/picture/home/" . $target_file_name;
                     $targetPathThumb = "media/picture/home/thumb_" . $target_file_name;
                     $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                     $filterFileRename->filter($file_name);
                     $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                     $thumb->resize(278, 129);
                     $thumb->save($targetPathThumb);
                 }
                 //upload image Ends here
                 $bodyTextArr["weekPhoto"] = $target_file_name;
                 $bodyTextArr["body"] = $options["body"];
                 $options["body"] = serialize($bodyTextArr);
             }
             $model->setOptions($options);
             $model->save();
             return $this->_helper->redirector('index', 'content', "admin", array('type' => $type, 'msg' => base64_encode("Content has been saved successfully!")));
         } else {
             $form->reset();
             $form->populate($options);
         }
     }
     $this->view->msg = base64_decode($this->getRequest()->getParam("msg"));
     // Assign the form to the view
     $this->view->form = $form;
     //render different view for Photo Of The Week module
     if ($model->getAlias() == "home_photo_week") {
         //clear form element decorators
         $elements = $form->getElements();
         $form->clearDecorators();
         foreach ($elements as $element) {
             $element->removeDecorator('label');
             $element->removeDecorator('td');
             $element->removeDecorator('tr');
             $element->removeDecorator('row');
             $element->removeDecorator('HtmlTag');
             $element->removeDecorator('class');
             $element->removeDecorator('placement');
             $element->removeDecorator('data');
         }
         $this->render('edit-photo');
     }
 }
Exemplo n.º 18
0
 public function homepageBottomContentAction()
 {
     $id = $this->_getParam('id', 1);
     $modelRes = new Application_Model_HomeBottomContent();
     $modelRes = $modelRes->find($id);
     $options = array('leftTitle' => $modelRes->getLeftTitle(), 'leftText' => $modelRes->getLeftText(), 'rightText' => $modelRes->getRightText(), 'rightTitle' => $modelRes->getRightTitle(), 'backgroundImage' => $modelRes->getBackgroundImage(), 'status' => $modelRes->getStatus());
     $form = new Admin_Form_HomeBottomContent();
     $this->view->backgroundImage = $modelRes->getBackgroundImage();
     $form->populate($options);
     //clear form element decorators
     $elements = $form->getElements();
     $form->clearDecorators();
     foreach ($elements as $element) {
         $element->removeDecorator('label');
         $element->removeDecorator('td');
         $element->removeDecorator('tr');
         $element->removeDecorator('row');
         $element->removeDecorator('HtmlTag');
         $element->removeDecorator('class');
         $element->removeDecorator('placement');
         $element->removeDecorator('data');
     }
     //submit form
     $request = $this->getRequest();
     if ($request->isPost()) {
         $options = $request->getPost();
         if ($form->isValid($options)) {
             //set previous image name if not uploaded new one
             $target_file_name = $modelRes->getBackgroundImage();
             // Image Upload START
             $upload = new Zend_File_Transfer_Adapter_Http();
             if ($upload->isValid()) {
                 $upload->setDestination("media/picture/home/");
                 try {
                     $upload->receive();
                 } catch (Zend_File_Transfer_Exception $e) {
                     $msg = $e->getMessage();
                 }
                 //unlink previous uploaded image file if exists
                 if (file_exists("media/picture/home/" . $modelRes->getBackgroundImage())) {
                     unlink("media/picture/home/" . $modelRes->getBackgroundImage());
                     unlink("media/picture/home/thumb_" . $modelRes->getBackgroundImage());
                 }
                 $upload->setOptions(array('useByteString' => false));
                 $file_name = $upload->getFileName('backgroundImage');
                 $cardImageTypeArr = explode(".", $file_name);
                 $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                 $target_file_name = "bottom_" . time() . ".{$ext}";
                 $targetPath = "media/picture/home/" . $target_file_name;
                 $targetPathThumb = "media/picture/home/thumb_" . $target_file_name;
                 $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                 $filterFileRename->filter($file_name);
                 $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                 $thumb->resize(641, 299);
                 $thumb->save($targetPathThumb);
             }
             //Image Upload END
             //set image
             $options['backgroundImage'] = $target_file_name;
             //set user id
             $usersNs = new Zend_Session_Namespace("members");
             $options['userId'] = $usersNs->userId;
             $modelRes->setOptions($options);
             $updateRes = $modelRes->save();
             if ($updateRes) {
                 $_SESSION['errorMsg'] = "Content has been updated successfully.";
                 $this->_helper->redirector('homepage-bottom-content', 'widgets', 'admin', array('id' => $id));
             } else {
                 $this->view->errorMsg = "Error occured, please try again later.";
             }
         } else {
             $form->reset();
             $form->populate($options);
         }
     }
     //end if
     //set form
     $this->view->form = $form;
     //set message
     if (isset($_SESSION['errorMsg'])) {
         $this->view->errorMsg = $_SESSION['errorMsg'];
         unset($_SESSION['errorMsg']);
     }
 }
Exemplo n.º 19
0
 public function editAction()
 {
     $id = $this->_getParam('id');
     $preview = false;
     $preview = $this->_getParam('preview');
     //echo "diana==>".base64_encode(85);
     $this->view->id = $id;
     $this->view->preview = $preview;
     $page = new Application_Model_Advice();
     $page = $page->find($id);
     $options = array('categoryId' => $page->getCategoryId(), 'title' => $page->getTitle(), 'identifire' => $page->getIdentifire(), 'name' => $page->getName(), 'content' => $page->getContent(), 'synopsis' => $page->getSynopsis(), 'metaTitle' => $page->getMetaTitle(), 'metaDescription' => $page->getMetaDescription(), 'metaKeyword' => $page->getMetaKeyword(), 'status' => $page->getStatus(), 'name' => $page->getName(), 'userId' => $page->getUserId());
     $request = $this->getRequest();
     $form = new Admin_Form_Advice();
     //clear form element decorators
     $elements = $form->getElements();
     $form->clearDecorators();
     foreach ($elements as $element) {
         $element->removeDecorator('label');
         $element->removeDecorator('td');
         $element->removeDecorator('tr');
         $element->removeDecorator('row');
         $element->removeDecorator('HtmlTag');
         $element->removeDecorator('class');
         $element->removeDecorator('placement');
         $element->removeDecorator('data');
     }
     //$this->view->type = $page->getType();
     $this->view->imgName = $page->getName();
     $form->populate($options);
     if ($request->isPost()) {
         $options = $request->getPost();
         if (trim($options['identifire']) == "") {
             $sanitize = new Base_Sanitize();
             $options['identifire'] = $options['title'];
         }
         if (trim($options['identifire']) != "") {
             $sanitize = new Base_Sanitize();
             $options['identifire'] = $sanitize->clearInputs($options['identifire']);
             $options['identifire'] = $sanitize->sanitize($options['identifire']);
             //update seo url table
             $seo_url_title = $options['identifire'];
             $adviceM = new Application_Model_Advice();
             $advice = $adviceM->find($id);
             $seo_url = "";
             $actual_url = "/advice/detail/id/{$id}";
             if (false !== $advice) {
                 $sanitizeM = new Base_Sanitize();
                 //$category_id	=	$advice->getCategoryId();
                 $category_id = $options['categoryId'];
                 $categoryM = new Application_Model_Category();
                 $category = $categoryM->find($category_id);
                 if (false !== $category) {
                     $seo_url = "/advice/" . $sanitizeM->sanitize($category->getName()) . "/" . $seo_url_title;
                 }
             }
             $seoUrlM = new Application_Model_SeoUrl();
             $soeUrl = $seoUrlM->fetchRow("actual_url='{$actual_url}'");
             if (false !== $soeUrl) {
                 if ($seo_url != "") {
                     $soeUrl->setSeoUrl($seo_url);
                     $soeUrl->save();
                 }
             } else {
                 if ($seo_url != "") {
                     $seoUrl = new Application_Model_SeoUrl();
                     $seoUrl->setActualUrl($actual_url);
                     $seoUrl->setSeoUrl($seo_url);
                     $seoUrl->save();
                 }
             }
         }
         //save data
         if ($form->isValid($options)) {
             //set previous image name if not uploaded new one
             $options['name'] = $page->getName();
             /*------------------------------ Image Upload START ---------------------------*/
             $upload = new Zend_File_Transfer_Adapter_Http();
             if ($upload->isValid()) {
                 $upload->setDestination("images/advice/");
                 try {
                     $upload->receive();
                 } catch (Zend_File_Transfer_Exception $e) {
                     $msg = $e->getMessage();
                 }
                 //unlink previous uploaded image files
                 unlink("images/advice/" . $page->getName());
                 unlink("images/advice/thumb_" . $page->getName());
                 $upload->setOptions(array('useByteString' => false));
                 $file_name = $upload->getFileName('name');
                 $cardImageTypeArr = explode(".", $file_name);
                 $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                 $target_file_name = "advice_" . time() . ".{$ext}";
                 $targetPath = 'images/advice/' . $target_file_name;
                 $targetPathThumb = 'images/advice/thumb_' . $target_file_name;
                 $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                 $filterFileRename->filter($file_name);
                 $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                 $thumb->resize(128, 84);
                 $thumb->save($targetPathThumb);
                 // file name
                 $options['name'] = $target_file_name;
             }
             /*------------------------------ Image Upload END ---------------------------*/
             $options['status'] = $page->getStatus();
             if ($options["saveUnpublish"] == "Save and Unpublish") {
                 $options['status'] = 0;
             }
             if ($options["savePublish"] == "Save and Publish") {
                 $options['status'] = 1;
             }
             $page->setOptions($options);
             $page->save();
             //return $this->_helper->redirector('index','advice',"admin",Array('msg'=>base64_encode("'{$page->getTitle()}' has been updated successfully!")));
             if ($options["savePublish"] == "Save and Publish") {
                 $_SESSION['errorMsg'] = "Article has been saved & published successfully.";
                 $this->_helper->redirector('index', 'advice', 'admin');
             } else {
                 if ($options["saveUnpublish"] == "Save and Unpublish") {
                     $_SESSION['errorMsg'] = "Article has been saved successfully.";
                     $this->_helper->redirector('index', 'advice', 'admin');
                 } else {
                     $this->_helper->redirector('edit', 'advice', 'admin', array('id' => $id, 'preview' => 'true'));
                 }
             }
         } else {
             $form->reset();
             $form->populate($options);
         }
     }
     $this->view->form = $form;
 }
 /**
  * Accepts the form
  *
  * Takes two roundtrips:
  * - first we get a HEAD request that should be answerd with
  *   responsecode 204
  * - then we get a post that only submits $_FILES (so actual $_POST will be empty)
  *   this will be an xml file for the actuel response and optionally images and/or video
  *   proper responses are
  *      201 received and stored
  *      202 received ok, not stored
  */
 public function submissionAction()
 {
     $this->makeRosaResponse();
     if ($this->getRequest()->isHead()) {
         $this->getResponse()->setHttpResponseCode(204);
     } elseif ($this->getRequest()->isPost()) {
         //Post
         // We get $_FILES variable holding the formresults as xml and all possible
         // attachments like photo's and video's
         $upload = new \Zend_File_Transfer_Adapter_Http();
         // We should really add some validators here see http://framework.zend.com/manual/en/zend.file.transfer.validators.html
         // Returns all known internal file information
         $files = $upload->getFileInfo();
         foreach ($files as $file => $info) {
             // file uploaded ?
             if (!$upload->isUploaded($file)) {
                 print "Why haven't you uploaded the file ?";
                 continue;
             }
             // validators are ok ?
             if (!$upload->isValid($file)) {
                 print "Sorry but {$file} is not what we wanted";
                 continue;
             }
         }
         //Dit moet een filter worden (rename filter) http://framework.zend.com/manual/en/zend.file.transfer.filters.html
         $upload->setDestination($this->responseDir);
         //Hier moeten we denk ik eerst de xml_submission_file uitlezen, en daar
         //iets mee doen
         if ($upload->receive('xml_submission_file')) {
             $xmlFile = $upload->getFileInfo('xml_submission_file');
             $answerXmlFile = $xmlFile['xml_submission_file']['tmp_name'];
             $resultId = $this->processReceivedForm($answerXmlFile);
             if ($resultId === false) {
                 //form not accepted!
                 foreach ($xml->children() as $child) {
                     $log->log($child->getName() . ' -> ' . $child, \Zend_Log::ERR);
                 }
             } else {
                 //$log->log(print_r($files, true), \Zend_Log::ERR);
                 //$log->log($deviceId, \Zend_Log::ERR);
                 \MUtil_File::ensureDir($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
                 $upload->setDestination($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/');
                 foreach ($upload->getFileInfo() as $file => $info) {
                     if ($info['received'] != 1) {
                         //Rename to responseid_filename
                         //@@TODO: move to form subdir, for better separation
                         $upload->addFilter('Rename', $resultId . '_' . $info['name'], $file);
                     }
                 }
                 //Now receive the other files
                 if (!$upload->receive()) {
                     $messages = $upload->getMessages();
                     echo implode("\n", $messages);
                 }
                 $this->getResponse()->setHttpResponseCode(201);
                 //Form received ok
             }
         }
     }
 }
Exemplo n.º 21
0
 /**
  * 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;
 }
Exemplo n.º 22
0
 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;
     }
 }
Exemplo n.º 23
0
 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 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;
 }
Exemplo n.º 25
0
 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')))));
 }
Exemplo n.º 26
0
 public function addAction()
 {
     $request = $this->getRequest();
     $form = new Admin_Form_Articles();
     //clear form element decorators
     $elements = $form->getElements();
     $form->clearDecorators();
     foreach ($elements as $element) {
         $element->removeDecorator('label');
         $element->removeDecorator('td');
         $element->removeDecorator('tr');
         $element->removeDecorator('row');
         $element->removeDecorator('HtmlTag');
         $element->removeDecorator('class');
         $element->removeDecorator('placement');
         $element->removeDecorator('data');
     }
     $model = new Application_Model_Articles();
     $page_id = $this->_getParam('id');
     $this->view->msg = "";
     if ($this->_getParam('m') == 's') {
         $this->view->msg = "Article has been saved successfully.";
     }
     //select logged in user as default seleted for Author
     $usersNs = new Zend_Session_Namespace("members");
     $author = array('userId' => $usersNs->userId);
     $form->populate($author);
     /*-----------------------------------------*/
     if ($this->getRequest()->isPost()) {
         $options = $request->getPost();
         if (trim($options['identifire']) == "") {
             $options['identifire'] = $options['title'];
         }
         if (trim($options['identifire']) != "") {
             $sanitize = new Base_Sanitize();
             $options['identifire'] = $sanitize->clearInputs($options['identifire']);
             $options['identifire'] = $sanitize->sanitize($options['identifire']);
         }
         if ($form->isValid($options)) {
             /*------------------------------Image Upload ---------------------------*/
             $upload = new Zend_File_Transfer_Adapter_Http();
             $target_file_name = "";
             if ($upload->isValid()) {
                 $upload->setDestination("images/articles/");
                 try {
                     $upload->receive();
                 } catch (Zend_File_Transfer_Exception $e) {
                     $msg = $e->getMessage();
                 }
                 $upload->setOptions(array('useByteString' => false));
                 $file_name = $upload->getFileName('image');
                 $cardImageTypeArr = explode(".", $file_name);
                 $ext = strtolower($cardImageTypeArr[count($cardImageTypeArr) - 1]);
                 $target_file_name = "art_" . time() . ".{$ext}";
                 $targetPath = 'images/articles/' . $target_file_name;
                 $targetPathThumb = 'images/articles/thumb_' . $target_file_name;
                 $filterFileRename = new Zend_Filter_File_Rename(array('target' => $targetPath, 'overwrite' => true));
                 $filterFileRename->filter($file_name);
                 $thumb = Base_Image_PhpThumbFactory::create($targetPath);
                 $thumb->resize(100, 64);
                 $thumb->save($targetPathThumb);
             }
             //end if
             /*------------------------------Image Upload ---------------------------*/
             $params = $options;
             $params['status'] = 1;
             if ($options["savePublish"] != "Save and Publish") {
                 $params['status'] = 0;
             }
             //commented by mahipal on 29-dec-2010 and replaced with user dropdown list
             //$usersNs = new Zend_Session_Namespace("members");
             //$params['userId']		=	$usersNs->userId;
             $params['image'] = $target_file_name;
             // file name
             $model = new Application_Model_Articles($params);
             $id = $page_id = $model->save();
             $seo_url_title = $options['identifire'];
             $articleM = new Application_Model_Articles();
             $article = $articleM->find($id);
             $seo_url = "";
             $actual_url = "/work-study-volunteer/article-detail/id/{$id}";
             if (false !== $article) {
                 $sanitizeM = new Base_Sanitize();
                 $category_id = $article->getCategoryId();
                 $categoryM = new Application_Model_Category();
                 $category = $categoryM->find($category_id);
                 if (false !== $category) {
                     //$seo_url="/work-study-volunteer/".$category->getType()."/".$sanitizeM->sanitize($category->getName())."/".$seo_url_title;
                     $seo_url = "/work-study-volunteer/" . $sanitizeM->sanitize($category->getName()) . "/" . $seo_url_title;
                 }
             }
             $seoUrlM = new Application_Model_SeoUrl();
             $seoUrl = $seoUrlM->fetchRow("actual_url='{$actual_url}'");
             if (false !== $seoUrl) {
                 if ($seo_url != "") {
                     $seoUrl->setSeoUrl($seo_url);
                     $seoUrl->save();
                 }
             } else {
                 if ($seo_url != "") {
                     $seoUrl = new Application_Model_SeoUrl();
                     $seoUrl->setActualUrl($actual_url);
                     $seoUrl->setSeoUrl($seo_url);
                     $seoUrl->save();
                 }
             }
             //$this->_helper->redirector('add','articles','admin',array('id'=>$page_id,'m'=>'s'));
             if ($options["savePublish"] == "Save and Publish") {
                 $_SESSION['errorMsg'] = "Article has been saved & published successfully.";
                 $this->_helper->redirector('index', 'articles', 'admin');
             } else {
                 if ($options["saveUnpublish"] == "Save and Unpublish") {
                     $_SESSION['errorMsg'] = "Article has been saved successfully.";
                     $this->_helper->redirector('index', 'articles', 'admin');
                 } else {
                     $this->_helper->redirector('edit', 'articles', 'admin', array('id' => $page_id, 'preview' => 'true'));
                 }
             }
         }
         //end if
     }
     //end if
     $this->view->form = $form;
 }
Exemplo n.º 27
0
 public function indexAction()
 {
     $this->view->breadcrumb = Snep_Breadcrumb::renderPath(array($this->view->translate("Configure"), $this->view->translate("CNL Update")));
     $config = Zend_Registry::get('config');
     $this->view->pathweb = $config->system->path->web;
     // verification procedure
     $db = Zend_Registry::get('db');
     $select = $db->select()->from('state');
     $stmt = $select->query();
     $result = $stmt->fetchAll();
     // insert state data
     if (count($result) < 26) {
         $brStates = array('AC' => 'Acre', 'AL' => 'Alagoas', 'AM' => 'Amazonas', 'AP' => 'Amapá', 'BA' => 'Bahia', 'CE' => 'Ceará', 'DF' => 'Distrito Federal', 'ES' => 'Espírito Santo', 'GO' => 'Goiás', 'MA' => 'Maranhão', 'MG' => 'Minas Gerais', 'MS' => 'Mato Grosso do Sul', 'MT' => 'Mato Grosso', 'PA' => 'Pará', 'PB' => 'Paraíba', 'PE' => 'Pernambuco', 'PI' => 'Piauí', 'PR' => 'Paraná', 'RJ' => 'Rio de Janeiro', 'RN' => 'Rio Grande do Norte', 'RO' => 'Rondônia', 'RR' => 'Roraima', 'RS' => 'Rio Grande do Sul', 'SC' => 'Santa Catarina', 'SE' => 'Sergipe', 'SP' => 'São Paulo', 'TO' => 'Tocantins');
         foreach ($brStates as $uf => $state) {
             $db->beginTransaction();
             try {
                 $_state = array('ds_code' => $uf, 'ds_name' => $state);
                 $db->insert('state', $_state);
                 $db->commit();
             } catch (Exception $ex) {
                 $db->rollBack();
                 throw $ex;
             }
         }
     }
     $form = new Snep_Form();
     $form->setAction($this->getFrontController()->getBaseUrl() . "/default/cnl/index");
     $this->view->formAction = $this->getFrontController()->getBaseUrl() . "/default/cnl/index";
     $element = new Zend_Form_Element_File('cnl');
     $element->setLabel($this->view->translate('CNL File'))->setDestination('/tmp/')->setRequired(true);
     $element->addValidator('Extension', false, array('bz2', 'json'));
     $element->removeDecorator('DtDdWrapper');
     $form->addElement($element, 'cnl');
     $form->getElement("submit")->setLabel($this->view->translate("Save"));
     $form->setAttrib('enctype', 'multipart/form-data');
     $this->view->valid = true;
     if ($this->_request->getPost()) {
         $form_isValid = $form->isValid($_POST);
         $this->view->valid = $form_isValid;
         if ($form_isValid) {
             $data = $_POST;
             $adapter = new Zend_File_Transfer_Adapter_Http();
             if ($adapter->isValid()) {
                 $adapter->receive();
                 $fileName = $adapter->getFileName();
                 $json = file_get_contents($fileName);
                 $cnl = Zend_Json_Decoder::decode($json, Zend_Json::TYPE_ARRAY);
                 $data = $cnl["operadoras"];
                 unset($cnl["operadoras"]);
                 $db->delete('city_code');
                 $db->delete('carrier_prefix');
                 $db->delete('city');
                 foreach ($data as $carrier => $id) {
                     Snep_Cnl::addOperadora($id, $carrier);
                 }
                 foreach ($cnl as $data => $id) {
                     foreach ($id as $state => $es) {
                         foreach ($es as $ddd => $d) {
                             foreach ($d as $city => $pre) {
                                 $stateId = Snep_Cnl::fetchStateId($state);
                                 $cityId = Snep_Cnl::addCidade($city);
                                 Snep_Cnl::addDDD($ddd, $stateId, $cityId);
                                 foreach ($pre as $prefix => $op) {
                                     Snep_Cnl::addPrefixo($prefix, $cityId, $op);
                                 }
                             }
                         }
                     }
                 }
                 $this->view->message = $this->view->translate('A lista de informações CNL foi atualizada com sucesso.');
             } else {
                 throw new ErrorException($this->view->translate("File format is not valid"));
             }
         }
     }
     $this->view->form = $form;
 }
 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;
 }
Exemplo n.º 29
0
 /**
  * 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;
 }
Exemplo n.º 30
0
 /** 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');
         }
     }
 }