/** * 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; } }
/** * Update profile Employee * @return type */ public function updateProfileAction() { $this->view->headTitle('Update Profile'); $form = new Employee_Form_UpdateProfile(); $id = (int) $this->getParam('id', ''); if (!$id) { $this->_helper->redirector('list-profile'); } $employeeMapper = new Employee_Model_EmployeeMapper(); $result = $employeeMapper->findId($id); if (!$result) { $this->view->message = "Nhan vien khong ton tai"; return; } $this->view->form = $form; //set up URL image $adapter = new Zend_File_Transfer_Adapter_Http(); $uploadPath = APPLICATION_PATH . '/../public/images/avatar'; $adapter->setDestination($uploadPath); $adapter->addFilter('Rename', $result->getEmployeeId() . '.jpg'); $this->view->fileName = $result->getEmployeeId() . '.jpg'; if (!$adapter->receive()) { $messages = $adapter->getMessages(); } $avatar = $adapter->getFileName(); $this->_processShowForm($form, $result); if ($this->_processUpdateFormProfile($form)) { echo "Update success"; $this->view->message = "Update success"; $params = array('id' => $id); $this->_helper->redirector("show-profile", 'profile', 'employee', $params); } }
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 uploadFile($object, $type, $subtype) { $sheets = new SxModule_Sheets(); $base = realpath(APPLICATION_PATH . '/../public_html/securedocs/'); $path = $type . '/' . $subtype; if (!is_dir($base . '/' . $path)) { echo $base . '/' . $path; mkdir($base . '/' . $type); mkdir($base . '/' . $path); } if ($object->getFile() == null) { $object->setFile(''); } $uploadAdapter = new Zend_File_Transfer_Adapter_Http(); $uploadAdapter->setDestination($base . '/' . $path); $uploadAdapter->setOptions(array('ignoreNoFile' => true)); $uploadAdapter->receive(); $files = $uploadAdapter->getFileName(null, true); foreach ($_FILES['file']['name'] as $key => $filename) { if (!$filename) { continue; } $file = $base . '/' . $path . '/' . $filename; $date = date('Y-m-d His'); $path_info = pathinfo($filename); $myfilename = str_replace(' ', '_', $path_info['filename'] . '_' . $date . '.' . $path_info['extension']); $myfilename = $sheets->createFileName($myfilename); $newfile = $base . '/' . $path . '/' . $myfilename; rename($file, $newfile); $object->setFile($myfilename); } }
public function uploadphotoAction() { if ($this->getRequest()->isPost()) { if ($_FILES['photo']['name'][0] != '') { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(Zend_Registry::get('userImagesPath')); $files = $adapter->getFileInfo(); $i = 1; foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { $this->view->sendConfirm = 'Problem uploading files'; return $this->render('error'); } $extension = strtolower(end(explode('.', $info['name']))); $name = time() . '4' . $i . "." . $extension; $i++; $adapter->addFilter('Rename', array('target' => Zend_Registry::get('userImagesPath') . $name, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { return $this->render('error'); } } $filename = $adapter->getFileName(); $filename = basename($filename); $profile = array('photo' => $filename); if (($edited = $this->profileService->editProfile(2, $profile)) === TRUE) { $this->view->profile = $this->profileService->fetchProfile(2); } else { $this->view->profile = $edited; } $this->render('getprofile'); } } }
public function addAction() { SxCms_Acl::requireAcl('securedocs', 'securedocs.add'); $base = realpath(APPLICATION_PATH . '/../public_html/securedocs/'); $path = base64_decode($this->_getParam('path')); if ($this->getRequest()->isPost()) { $uploadAdapter = new Zend_File_Transfer_Adapter_Http(); $uploadAdapter->setDestination($base . $path); $uploadAdapter->setOptions(array('ignoreNoFile' => true)); $uploadAdapter->receive(); $files = $uploadAdapter->getFileName(null, true); foreach ($_FILES['file']['name'] as $key => $filename) { if (!$filename) { continue; } $summary = $this->_getParam('samenvatting'); $mail = $this->_getParam('mail', ''); $file = $base . $path . '/' . $filename; $newfile = $base . $path . '/' . str_replace(" ", "", $filename); rename($file, $newfile); $file = new SxModule_Securedocs_File($newfile); $file->setPath($path); $file->setSummary($summary[$key]); $file->setMail(isset($mail[$key]) ? "1" : "0"); $file->save(); if ($mail[$key]) { $groups = explode('/', $path); $control = $path; if ($control != "") { $proxy = new SxModule_Securedocs_Folder_Proxy(); $folder = $proxy->getByFolder($groups[1]); $folderId = $folder->getFolderId(); $proxy = new SxModule_Securedocs_Group_Proxy(); $groups = $proxy->getAllByMap($folderId); $aantal = count($groups); $q = 0; $groupids = '('; foreach ($groups as $group) { $q++; if ($q != $aantal) { $groupids .= $group->getGroupId() . ","; } else { $groupids .= $group->getGroupId(); } } $groupids .= ')'; $proxy = new SxModule_Members_Proxy(); $members = $proxy->getAllByGroups($groupids); foreach ($members as $member) { $member->sendDocument($file); } } } } $this->_redirect('/admin/securedocs/index/path/' . base64_encode($path)); } $this->view->path = $path; $this->view->messages = Sanmax_MessageStack::getInstance('SxModule_Securedocs_File'); }
/** * upload */ public function uploadAction() { // disable layouts for this action: $this->_helper->layout->disableLayout(); if ($this->_request->isPost()) { try { $destination = PUBLIC_PATH . "/uploads/files"; /* Check destination folder */ if (!is_dir($destination)) { if (is_writable(PUBLIC_PATH . "/uploads")) { mkdir($destination); } else { throw new Exception("Uploads directory is not writable"); } } /* Uploading Document File on Server */ $upload = new Zend_File_Transfer_Adapter_Http(); try { // upload received file(s) $upload->receive(); } catch (Zend_File_Transfer_Exception $e) { $e->getMessage(); } // you MUST use following functions for knowing about uploaded file // Returns the file name for 'doc_path' named file element $filePath = $upload->getFileName('file'); // pathinfo $name = pathinfo($filePath, PATHINFO_FILENAME); $ext = pathinfo($filePath, PATHINFO_EXTENSION); // prepare filename $name = strtolower($name); $name = preg_replace('/[^a-z0-9_-]/', '-', $name); // prepare extension if ($ext == 'php' or $ext == 'php4' or $ext == 'php5' or $ext == 'phtml') { $ext = 'phps'; } // rename uploaded file $renameFile = $name . '.' . $ext; $counter = 0; while (file_exists($destination . '/' . $renameFile)) { $counter++; $renameFile = $name . '-' . $counter . '.' . $ext; } $fileIco = $this->getIco($ext); $fullFilePath = $destination . '/' . $renameFile; // Rename uploaded file using Zend Framework $filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true)); $filterFileRename->filter($filePath); $this->_helper->viewRenderer->setNoRender(true); $link = '<a href="javascript:void(null);" rel="' . $renameFile . '" class="redactor_file_link redactor_file_ico_' . $fileIco . '" title="' . $renameFile . '">' . $renameFile . '</a>'; echo $link; } catch (Exception $e) { $this->_forwardError($e->getMessage()); } } else { $this->_forwardError('Internal Error of Uploads controller'); } }
/** * Use the Zend_File_Transfer adapter to upload the file. * * @internal The resulting filename is retrieved via the adapter's * getFileName() method. * * @param array $fileInfo * @param string $originalFilename * @return string Path to the file in Omeka. */ protected function _transferFile($fileInfo, $originalFilename) { // Upload a single file at a time. if (!$this->_adapter->receive($fileInfo['form_index'])) { throw new Omeka_File_Ingest_InvalidException(join("\n\n", $this->_adapter->getMessages())); } // Return the path to the file as it is listed in Omeka. return $this->_adapter->getFileName($fileInfo['form_index']); }
public function indexAction() { SxCms_Acl::requireAcl('filemanager', 'filemanager.index'); $base = APPLICATION_PATH . '/../public_html/files/'; $base = realpath($base); $path = base64_decode($this->_getParam('path')); if ($this->getRequest()->isPost()) { if (null !== $this->_getParam('folder')) { SxCms_Acl::requireAcl('filemanager', 'filemanager.add.folder'); if (strlen($this->_getParam('folder'))) { $dirname = $path . '/' . $this->_getParam('folder'); mkdir($base . $dirname); $this->_redirect('/admin/filemanager/index/path/' . base64_encode($path)); } } else { SxCms_Acl::requireAcl('filemanager', 'filemanager.add.file'); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(realpath($base) . $path); if ($adapter->receive()) { $filename = realpath($adapter->getFileName('filename')); $file = new SxCms_File($filename); $path = $file->getPathnameFromBase(); $nfile = $path . '/' . $file->getBasename(); $this->_redirect('/admin/filemanager/edit/file/' . base64_encode($nfile) . '/path/' . base64_encode($path)); } else { $msg = Sanmax_MessageStack::getInstance('SxCms_Filemanager'); $msg->addMessage('file', $adapter->getMessages()); } } } $this->view->messages = Sanmax_MessageStack::getInstance('SxCms_Filemanager'); try { $it = new SxCms_Filesystem(realpath($base . $path)); } catch (Exception $e) { $it = new SxCms_Filesystem($base); $path = ''; $e; } $topdir = explode('/', $path); if (count($topdir) > 1) { array_pop($topdir); $topdir = implode('/', $topdir); } else { $topdir = ''; } $this->view->files = $it; $this->view->path = $path; $this->view->showpath = explode('/', $path); $this->view->topdir = $topdir; if ($this->_getParam('full')) { $this->_helper->layout->setLayout('nolayout'); $this->view->full = true; } }
/** * Processa os dados do formulário de importação de RPS [json] * * @return void */ public function rpsProcessarAction() { parent::noLayout(); $oForm = new Contribuinte_Form_ImportacaoArquivo(); $oForm->renderizaCamposRPS(); // Adiciona a validação do arquivo junto ao restante das mensagens de erro do form $aDados = array_merge($this->getRequest()->getPost(), array('isUploaded' => $oForm->arquivo->isUploaded())); // Valida o formulario e processa a importação if ($this->getRequest()->isPost() && $oForm->arquivo->isUploaded()) { $oArquivoUpload = new Zend_File_Transfer_Adapter_Http(); try { $oArquivoUpload->setDestination(APPLICATION_PATH . '/../public/tmp/'); // Confirma o upload e processa o arquivo if ($oArquivoUpload->receive()) { $oImportacaoModelo1 = new Contribuinte_Model_ImportacaoArquivoRpsModelo1(); $oImportacaoModelo1->setArquivoCarregado($oArquivoUpload->getFileName()); $oArquivoCarregado = $oImportacaoModelo1->carregar(); if ($oArquivoCarregado != NULL && $oImportacaoModelo1->validaArquivoCarregado()) { // Valida as regras de negócio e processa a importação $oImportacaoProcessamento = new Contribuinte_Model_ImportacaoArquivoProcessamento(); $oImportacaoProcessamento->setCodigoUsuarioLogado($this->usuarioLogado->getId()); $oImportacaoProcessamento->setArquivoCarregado($oArquivoCarregado); // Processa a importação $oImportacao = $oImportacaoProcessamento->processarImportacaoRps(); if ($oImportacao->getId()) { $sUrlRecibo = "/contribuinte/importacao-arquivo/rps-recibo/id/{$oImportacao->getId()}"; $aRetornoJson['status'] = TRUE; $aRetornoJson['url'] = $this->view->baseUrl($sUrlRecibo); $aRetornoJson['success'] = $this->translate->_('Arquivo importado com sucesso.'); } else { throw new Exception($this->translate->_('Ocorreu um erro ao importar o arquivo.')); } } else { throw new Exception($oImportacaoModelo1->processaErroSistema()); } } } catch (DBSeller_Exception_ImportacaoXmlException $oErro) { $aRetornoJson['status'] = FALSE; $aRetornoJson['error'] = array_merge(array('<b>' . $this->translate->_('Ocorreu um erro ao importar o arquivo:') . '</b><br>'), $oErro->getErrors()); } catch (Exception $oErro) { $aRetornoJson['status'] = FALSE; $aRetornoJson['error'][] = $oErro->getMessage(); } if (is_file($oArquivoUpload->getFileName())) { unlink($oArquivoUpload->getFileName()); } } else { $aRetornoJson['status'] = FALSE; $aRetornoJson['fields'] = array_keys($oForm->getMessages()); $aRetornoJson['error'][] = $this->translate->_('Preencha os dados corretamente.'); } echo $this->getHelper('json')->sendJson($aRetornoJson); }
/** * Upload Function * * Esta função faz upload do arquivo, renomeia e seta os atriutos * filename, filehash, filesize * * @return boolean */ public function upload() { /* Verifica se ha arquivo para upload */ $upload = new Zend_File_Transfer_Adapter_Http(); if ($upload->isValid($this->field)) { $this->filename = $upload->getFileName($this->field, false); $this->filehash = md5(time() . microtime(true)) . "." . $this->getExtension($this->filename); $this->filesize = $upload->getFileSize(); $upload->setDestination($this->path)->setFilters(array("Rename" => $this->filehash)); return $upload->receive($this->field); } else { return false; } }
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); } } }
public function save($path, $extension, $userid = 0) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $files = $adapter->getFileInfo(); foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { return false; } $filename = $this->generateFileName($extension, $userid); $adapter->addFilter('Rename', array('target' => $path . $filename, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { return false; } } $filename = $adapter->getFileName(); $filename = basename($filename); return $filename; }
public function addAction() { $this->view->title = "Добавить страницу"; $this->view->headTitle($this->view->title, 'PREPEND'); $frmPage = new Form_Page(); if ($this->_request->isPost()) { if ($frmPage->isValid($this->_request->getParams())) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(SITE_PATH . 'img' . DS . 'upload'); $adapter->receive(); $fileName = $adapter->getFileName('image', false); $paramStr = $frmPage->getValues(); $paramStr['image'] = $fileName; $mdlPages = new Model_Admin(); $mdlPages->fill($paramStr); $mdlPages->save(); $this->_helper->redirector('index'); } } $this->view->form = $frmPage; }
/** * Action resposável pela importção da DES-IF */ public function processarImportacaoAction() { parent::noLayout(); try { $aDados = $this->getRequest()->getPost(); $oForm = new Contribuinte_Form_ImportacaoDesif(); if ($oForm->isValid($aDados)) { $oArquivoUpload = new Zend_File_Transfer_Adapter_Http(); if ($oArquivoUpload->receive()) { $aArquivos = $oArquivoUpload->getFileName(); $aArquivoContas = file($aArquivos['arquivoContas']); $aArquivoReceita = file($aArquivos['arquivoReceita']); $oContribuinte = $this->_session->contribuinte; $oImportacaoDesif = new Contribuinte_Model_Desif($oContribuinte, $aArquivoContas, $aArquivoReceita); $iImportacaoDesifId = $oImportacaoDesif->processarArquivo(); //Gera protocolo e vincula com a importação $sMensagem = 'Processamento efetuado com sucesso!'; $oProtocolo = $this->adicionaProtocolo(2, $sMensagem); $oDesif = Contribuinte_Model_ImportacaoDesif::getById($iImportacaoDesifId); $oDesif->setProtocolo($oProtocolo); $oDesif->persist(); $aRetornoJson['status'] = TRUE; $aRetornoJson['success'] = $this->translate->_($sMensagem); $aRetornoJson['protocolo'] = $oProtocolo->getProtocolo(); } } else { throw new Exception("Preencha os dados corretamente."); } } catch (Exception $oErro) { //Gera Protocolo $sMensagem = $oErro->getMessage(); $oProtocolo = $this->adicionaProtocolo(1, $sMensagem); $aRetornoJson['status'] = FALSE; $aRetornoJson['error'][] = $sMensagem; $aRetornoJson['protocolo'] = $oProtocolo->getProtocolo(); } echo $this->getHelper('json')->sendJson($aRetornoJson); }
public function uploadAction() { $this->_helper->layout->disableLayout(); if (!isset($_FILES['Filedata']) || !is_uploaded_file($_FILES['Filedata']['tmp_name'])) { $this->view->status = false; $this->view->error = Zend_Registry::get('Zend_Translate')->_('Invalid Upload'); return; } $destination = "public/book/"; if (!is_dir($destination)) { mkdir($destination); } $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination($destination); $fullFilePath = $destination . time() . '_' . $upload->getFileName('Filedata', false); $image = Engine_Image::factory(); $image->open($_FILES['Filedata']['tmp_name'])->resize(720, 720)->write($fullFilePath); $this->view->status = true; $this->view->name = $_FILES['Filedata']['name']; $this->view->photo_url = Zend_Registry::get('StaticBaseUrl') . $fullFilePath; $this->view->photo_width = $image->getWidth(); $this->view->photo_height = $image->getHeight(); }
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; }
/** * Enter description here ... */ public function saveAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $post = $this->getRequest()->getPost(); $data = array('name' => $post['name'], 'alias' => $post['alias'], 'link' => $post['link'], 'sort' => $post['sort'], 'description' => $post['desc']); if (isset($post['active'])) { $data['active'] = 1; } if ($_FILES['icon']['name'] != '') { $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination($_SERVER['DOCUMENT_ROOT'] . "/upload/icons/"); $name = $upload->getFileName('icon', false); $ext = split("\\.", $name); $newName = md5($name) . '.' . $ext[count($ext) - 1]; $upload->addFilter('Rename', array('target' => $_SERVER['DOCUMENT_ROOT'] . "/upload/icons/" . $newName, 'overwrite' => true)); try { $upload->receive(); $data['logo'] = $newName; } catch (Zend_File_Transfer_Exception $e) { $e->getMessage(); } } //Zend_Debug::dump($post); $intro = new Intro(); if ($post['id'] == "") { $intro->insertIntro($data); } else { $intro->updateIntro($data, $post['id']); } if ($post['savenew'] == 0) { $this->_redirect('admin/intro/show'); } else { $this->_redirect('admin/intro/new'); } }
public function inserirAction() { $noticias = new Application_Model_DbTable_Noticias(); $request = $this->getRequest(); // Capturamos aqui o dados enviados via post //$data = $this->_request->getPost(); // Instancia o adaptador do Zend para tranferência de arquivos via $upload_adapter = new Zend_File_Transfer_Adapter_Http(); //FORMA ANTIGA CARREGANDO IMG NO APPLICATON $upload_adapter->setDestination( APPLICATION_PATH.'/noticias/imagens' ); //FORMA NOVA, CARREGANDO NA PUBLIC $upload_adapter->setDestination('imagens/noticias/imagens'); //CARREGA NO SERVIDOR $upload_adapter->receive(); //var_dump($upload_adapter); exit; $imagem = basename($upload_adapter->getFileName()); /*PEGA OS DADOS DO BENEFICIARIO*/ $inserir = array("titulo" => $request->getParam('titulo'), "data" => $this->dataSql($request->getParam('data')), "descricao" => $request->getParam('descricao'), "img" => "/noticias/imagens/" . $imagem); $cadastraNoticia = $noticias->insert($inserir); if ($cadastraNoticia) { $this->_redirect('/'); } else { echo "<script> alert('ERRO'); </script> "; } }
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; }
/** * 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(); } }
private function _getUploadedFile() { $fullFilePath = ''; $upload = new Zend_File_Transfer_Adapter_Http(); if ($upload->getFileName('photo')) { $destination = "public/ynvideo_category/"; if (!is_dir($destination)) { mkdir($destination); } $upload->setDestination($destination); $fullFilePath = $destination . time() . '_' . $upload->getFileName('photo', false); $image = Engine_Image::factory(); $image->open($_FILES['photo']['tmp_name']) ->resize(128, 128) ->write($fullFilePath); } return $fullFilePath; }
// for the template files $view = new Zend_View(); $view->setScriptPath(__DIR__); // Tell all the elements in the form which view to use when rendering foreach ($form as $item) { $item->setView($view); } // process or display the form if (isset($_POST['submit']) && $form->isValid($_POST)) { $uploadHandler = new Zend_File_Transfer_Adapter_Http(); $uploadHandler->setDestination(__DIR__ . '/uploads/'); try { $uploadHandler->receive(); $data = $form->getValues(); Zend_Debug::dump($data, 'Form Data:'); $fullPath = $uploadHandler->getFileName('file'); $size = $uploadHandler->getFileSize('file'); $mimeType = $uploadHandler->getMimeType('file'); $fileInfo = pathinfo($fullPath); $name = $fileInfo['basename'] . '<br>'; // rename the file for security purpose $newName = 'RM_' . time() . '_' . $fileInfo['basename']; $fullFilePath = __DIR__ . '/uploads/' . $newName; $filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true)); $filterFileRename->filter($fullPath); echo 'thanks <br />'; } catch (Zend_File_Transfer_Exception $e) { echo $e->getMessage(); } } else { echo $form->render($view);
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 changeprofileimgAction() { if ($this->getRequest()->isPost()) { if (!empty($_FILES['photo']['name'])) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(Zend_Registry::get('profileImagesPath')); $files = $adapter->getFileInfo(); $i = 1; foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { return $this->_redirect('/profile'); } $extension = strtolower(end(explode('.', $info['name']))); $name = time() . $this->_user->id . $i++ . "." . $extension; $adapter->addFilter('Rename', array('target' => Zend_Registry::get('profileImagesPath') . $name, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { $this->view->error = 'There was a problem uploading the photo. Please try again later'; return $this->render('error'); } } $filename = $adapter->getFileName(); $filename = basename($filename); $changes = array('photo' => $filename); $profileService = new Service_Profile(); if ($edited = $profileService->editProfile($this->_user->profileid, $changes)) { return $this->_redirect('/profile'); } else { $this->view->error = 'There was a problem updating your profile. Please try again later'; return $this->render('error'); } } } else { $this->_redirect('/profile'); } }
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'); } }
/** * Index * * @throws Exception */ public function uploadAction() { // disable layouts for this action: $this->_helper->layout->disableLayout(); if ($this->_request->isPost()) { try { $destination = PUBLIC_PATH . $this->_uploadPath . DS . $this->_getUploadDir(); $publicPath = $this->_uploadPath . DS . $this->_getUploadDir(); /* Check destination folder */ if (!is_dir($destination)) { if (is_writable(PUBLIC_PATH . $this->_uploadPath)) { mkdir($destination, 0777, true); } else { throw new Exception("Uploads directory is not writable"); } } /* Uploading Document File on Server */ $upload = new Zend_File_Transfer_Adapter_Http(); try { // upload received file(s) $upload->receive(); } catch (Zend_File_Transfer_Exception $e) { $e->getMessage(); } // you MUST use following functions for knowing about uploaded file // Returns the file name for 'doc_path' named file element $filePath = $upload->getFileName('file'); // Returns the mimetype for the 'file' form element $mimeType = $upload->getMimeType('file'); // mimeType validation switch ($mimeType) { case 'image/jpg': case 'image/jpeg': case 'image/pjpeg': $ext = 'jpg'; break; case 'image/png': $ext = 'png'; break; case 'image/gif': $ext = 'gif'; break; default: throw new Exception('Wrong mimetype of uploaded file. Received "' . $mimeType . '"'); break; } // prepare filename $name = pathinfo($filePath, PATHINFO_FILENAME); $name = strtolower($name); $name = preg_replace('/[^a-z0-9_-]/', '-', $name); // rename uploaded file $renameFile = $name . '.' . $ext; $counter = 0; while (file_exists($destination . '/' . $renameFile)) { $counter++; $renameFile = $name . '-' . $counter . '.' . $ext; } $fullFilePath = $destination . '/' . $renameFile; // rename uploaded file using Zend Framework $filterFileRename = new Zend_Filter_File_Rename(array('target' => $fullFilePath, 'overwrite' => true)); $filterFileRename->filter($filePath); $this->_helper->viewRenderer->setNoRender(true); // create thumb $this->_createThumb($fullFilePath); echo "<img src='{$publicPath}/{$renameFile}' alt='' />"; } catch (Exception $e) { $this->_forwardError($e->getMessage()); } } else { $this->_forwardError('Internal Error of Uploads controller'); } }
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; }
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']); } }
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"); }