/** * Sube el archivo a temporal * @return string */ public function upload($extenciones = array('kml', 'kmz')) { $correcto = true; $upload = new Zend_File_Transfer(); $upload->addValidator('Extension', false, $extenciones); $upload->addValidator('FilesSize', false, array('min' => '0.001kB', 'max' => '64MB')); $file = $upload->getFileInfo(); foreach ($file as $field_name => $file_data) { if (!$upload->isUploaded($field_name)) { $correcto = false; $retorno = array("correcto" => false, "mensaje" => "No se subio ningún archivo o estaba vacío"); } if (!$upload->isValid($field_name)) { $texto = "</br>"; $mensajes = $upload->getMessages(); foreach ($mensajes as $key => $txt) { $texto .= $txt . "</br>"; } $correcto = false; $retorno = array("correcto" => false, "mensaje" => "<b>El archivo es inválido</b>." . $texto); } $this->_setFileConfig($file_data["name"]); $this->_mime = $file_data["type"]; $this->_hash = $this->_ci->string_core->rand_string(20); $this->_target = $this->_dir_temp . $this->_hash . "." . $this->_file_ext; $upload->addFilter('Rename', array('target' => $this->_target, 'overwrite' => true)); } if ($correcto) { fb($upload->receive()); $retorno = $this->_saveToCache(); } return $retorno; }
function addTableGroup($data) { $db = $this->getAdapter(); $upload = new Zend_File_Transfer(); $file = $upload->getFileInfo(); foreach ($file as $row) { $row_name = $row["name"]; $filenameitems = explode(".", $row_name); $extension = $filenameitems[count($filenameitems) - 1]; $photoname = str_replace(" ", "_", $data['group_code']) . '.' . $extension; } $upload->addFilter('Rename', array('target' => PUBLIC_PATH . '/image/' . $photoname, 'overwrite' => true), 'photo'); $receive = $upload->receive(); if ($receive) { $data['photo'] = $photoname; } else { // if($data['show_description'] == 1){ // $photo=$data['group_code']; // } // elseif ($data['show_description']==2){ // $photo=$data['description']; // } // elseif ($data['show_description']==3){ // $photo=$data['lang_1']; // } // elseif ($data['show_description']==4){ // $photo=$data['lang_2']; // } // else{ $photo="";} $data['photo'] = ""; } unset($data['MAX_FILE_SIZE']); $arr = array('code' => $data['group_code'], 'description' => $data['description'], 'lang1' => $data['lang_1'], 'lang2' => $data['lang_2'], 'img_name' => $data["photo"], 'display_by' => $data['show_description'], 'compid' => $data['apply_to_company'], 'note' => $data['note'], 'background_color' => $data['backgroun_color'], 'font_color' => $data['font_color'], 'font_size' => $data['font_size'], 'status' => $data['active']); $this->insert($arr); }
private function saveImagesToFilesystem($savePath) { if (!file_exists($savePath)) { mkdir($savePath); } $upload = new Zend_File_Transfer(); $upload->setDestination($savePath); $upload->receive(); $this->resizeImagesAndCreateThumbnails($savePath, $upload->getFileInfo()); }
public function uploadAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(true); $json = new ZendT_Json_Result(); try { $options = $this->getRequest()->getParam('options'); if ($options && !is_array($options)) { $options = unserialize($options); } /** * @var Zend_File_Transfer_Adapter_Http */ $uploads = new Zend_File_Transfer('Http', false, array('detectInfos' => false)); if ($options['extension'] == ZendT_Type_Blob::FILTER_EXECUTABLE) { $options['extension'] = array('text/php', 'text/x-php', 'text/asp', 'text/x-asp'); } if ($options['maxSize'] || $options['minSize']) { $uploads->addValidator('FilesSize', false, array('max' => $options['maxSize'], 'min' => $options['minSize'])); } if (is_array($options['validators'])) { array_merge($options['extension'], $options['validators']); } //$uploads->addValidator('ExcludeMimeType', false, $options['extension']); $uploads->receive(); if ($uploads->hasErrors()) { $message = $uploads->getMessages(); throw new ZendT_Exception_Information(current($message)); } else { } $infoFiles = $uploads->getFileInfo(); @($content = file_get_contents($infoFiles['file']['tmp_name'])); if ($content === false) { throw new ZendT_Exception_Error('Não foi possível armazenar o arquivo informado!'); } $_file = new ZendT_File($infoFiles['file']['name'], $content, $infoFiles['file']['type']); @unlink($infoFiles['file']['tmp_name']); $infoFile = $_file->toArrayJson(); $infoFile['size'] = $infoFiles['file']['size']; $json->setResult($infoFile); } catch (Exception $Ex) { $json->setException($Ex); } echo $json->render(); }
/** * Metodo para renderizar o formulario de cadastro/alteracao dos parametros do contribuinte. * * Retorna para a view a instancia do formulario Contribuinte_Form_ParametrosContribuinte */ public function contribuinteAction() { $oForm = new Contribuinte_Form_ParametrosContribuinte(); $oParametroContribuinte = $this->buscaParametroContribuinte($this->view->contribuinte->getIdUsuarioContribuinte()); $aDados = $this->getRequest()->getPost(); if ($this->getRequest()->isPost() && $oForm->isValid($aDados)) { try { $oDoctrine = Zend_Registry::get('em'); $oDoctrine->getConnection()->beginTransaction(); $oParametroContribuinte->setAvisofimEmissaoNota($aDados["avisofim_emissao_nota"]); $oParametroContribuinte->setCofins(DBSeller_Helper_Number_Format::toDataBase($aDados["cofins"])); $oParametroContribuinte->setCsll(DBSeller_Helper_Number_Format::toDataBase($aDados["csll"])); $oParametroContribuinte->setIdContribuinte($this->view->contribuinte->getIdUsuarioContribuinte()); $oParametroContribuinte->setInss(DBSeller_Helper_Number_Format::toDataBase($aDados["inss"])); $oParametroContribuinte->setIr(DBSeller_Helper_Number_Format::toDataBase($aDados["ir"])); $oParametroContribuinte->setMaxDeducao(DBSeller_Helper_Number_Format::toDataBase($aDados["max_deducao"])); $oParametroContribuinte->setPis(DBSeller_Helper_Number_Format::toDataBase($aDados["pis"])); $oParametroContribuinte->setValorIssFixo(DBSeller_Helper_Number_Format::toDataBase($aDados["valor_iss_fixo"])); $oParametroContribuinte->salvar(); $oDoctrine->getConnection()->commit(); $this->view->messages[] = array('success' => 'Parâmetros modificados com sucesso.'); $oArquivoUpload = new Zend_File_Transfer(); $oArquivoUpload->receive(); $iInscricaoMunicipal = $this->view->contribuinte->getInscricaoMunicipal(); Administrativo_Model_Empresa::setLogoByIm($iInscricaoMunicipal, $oArquivoUpload->getFileInfo()); } catch (Exception $oErro) { $oDoctrine->getConnection()->rollback(); $this->view->messages[] = array('error' => $oErro->getMessage()); } } $oDados->im = $this->view->contribuinte->getInscricaoMunicipal(); $oDados->nome_contribuinte = $this->view->contribuinte->getNome(); $oDados->avisofim_emissao_nota = $oParametroContribuinte->getAvisofimEmissaoNota(); $oDados->cofins = $oParametroContribuinte->getCofins(); $oDados->csll = $oParametroContribuinte->getCsll(); $oDados->inss = $oParametroContribuinte->getInss(); $oDados->ir = $oParametroContribuinte->getIr(); $oDados->max_deducao = $oParametroContribuinte->getMaxDeducao(); $oDados->pis = $oParametroContribuinte->getPis(); $oDados->valor_iss_fixo = $oParametroContribuinte->getValorIssFixo(); $oForm->preenche($oDados); $this->view->sLogoPrestador = Administrativo_Model_Empresa::getLogoByIm($oDados->im); $this->view->form = $oForm; }
public function importSeasons() { $option = JRequest::getCmd('option'); $controller = JRequest::getCmd('controller'); // Check for request forgeries JRequest::checkToken() or die('Invalid Token'); $path = JPATH_ROOT . "/tmp"; $upload = new Zend_File_Transfer(); $upload->setDestination($path); $upload->addValidator('Extension', false, array("csv")); $errors = array(); $file = "products_seasons"; $info = $upload->getFileInfo($file); if ($upload->isUploaded($file)) { if (!$upload->isValid($file)) { foreach ($upload->getMessages() as $k => $v) { $errors[$k] = true; } } } if ($upload->receive()) { $mProduct = new EcwidgatewayModelProducts(); $mProduct->processSeasonsCsv($path . "/" . $info[$file]["name"]); $msg = "Данные импортированы"; } else { $errorMessages = array("Ошибка при загрузке файла"); foreach ($errors as $k => $v) { if (isset($errors[Zend_Validate_File_Extension::FALSE_EXTENSION])) { $errorMessages[] = JText::_("Недопустимое расширение файла"); } } $msg = implode("<p>", $errorMessages); } $link = 'index.php?option=' . $option . '&controller=' . $controller; $this->setRedirect($link, $msg); }
public function saveAction() { $request = $this->getRequest(); $id = $this->getParam('id'); $auth = Zend_Auth::getInstance(); if ($auth->hasIdentity()) { $user_id = $auth->getIdentity()->id; } $form = $this->getSaveProductForm($id); if ($this->getRequest()->isPost()) { if ($form->isValid($request->getPost())) { $data = $this->getRequest()->getParams(); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); $isValid = true; foreach ($files as $field => $file) { if (!strlen($file["name"])) { continue; } $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $filename = pathinfo($file['name'], PATHINFO_FILENAME); if (!file_exists(UPLOADS_IMAGES)) { mkdir(UPLOADS_IMAGES, 0774, true); } if (!file_exists(UPLOADS_DATA)) { mkdir(UPLOADS_DATA, 0774, true); } // upload instructions for image if ($field == 'image') { $upload->addFilter('Rename', array('target' => UPLOADS_IMAGES . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('jpg', 'jpeg', 'png'), $field); $data['image'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } // upload instructions for file if ($field == 'file') { $upload->addFilter('Rename', array('target' => UPLOADS_DATA . '/' . $filename . "_" . $user_id . "_" . time() . "." . $extension, 'overwrite' => TRUE), $field)->addValidator('Extension', false, array('doc', 'docx', 'txt', 'pdf'), $field); $data['file'] = $filename . "_" . $user_id . "_" . time() . "." . $extension; } if ($upload->isValid($field)) { if (!$upload->receive($field)) { $isValid = false; foreach ($upload->getMessages() as $key => $val) { $this->_helper->getHelper('FlashMessenger')->addMessage($val, 'error'); } } } else { $isValid = false; $this->_helper->getHelper('FlashMessenger')->addMessage($file['name'] . " is not valid {$field}", 'error'); //return $this->_helper->redirector('save'); } } if ($upload->hasErrors()) { $errors = $upload->getMessages(); foreach ($errors as $error) { $this->_helper->getHelper('FlashMessenger')->addMessage("{$error}", 'error'); } return $this->_helper->redirector('save'); } if ($isValid) { $product = new Application_Model_Product(); $productMapper = new Application_Model_ProductMapper(); if ($id) { $product = $productMapper->getProductById($id); } if (isset($data['file']) && $product->file && $product->file != $data['file'] || !isset($data['file']) && $product->file) { $productMapper->delete_file($product->file); } if (isset($data['image']) && $product->image && $product->image != $data['image'] || !isset($data['image']) && $product->image) { $productMapper->delete_image($product->image); } $product = new Application_Model_Product($data); $productMapper->save($product); return $this->_helper->redirector('dashboard', 'users'); } } } $this->view->headScript()->appendFile(JS_DIR . '/' . self::DELETE_FIELD . '.js'); $this->view->form = $form; }
public function uploadAction() { $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $db = new Fotos(); $album_id = $this->_request->getPost('album_id'); $db->setAlbumId($album_id); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(APPLICATION_PATH . '/../data/temp'); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); if (!file_exists(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id)) { mkdir(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id, 0777, true); } foreach ($files as $file => $info) { if ($upload->isUploaded($file)) { $extension = substr($info['name'], strrpos($info['name'], '.') + 1); $filename = 'photo_' . time() . '.' . $extension; $adapter->addFilter('Rename', array('target' => APPLICATION_PATH . '/../data/temp/' . $filename, 'overwrite' => true)); $adapter->receive($info['name']); if (!$adapter->receive()) { $messages = $adapter->getMessages(); echo implode("\n", $messages); exit; } //setFileName::Url $db->setUrl($filename); //setCapa::false (0) $db->setCapa(0); $imanee = new Imanee\Imanee(APPLICATION_PATH . '/../data/temp/' . $filename); //resized $imanee->resize(870, 653)->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id . DS . 'r_' . $filename, 80); //full //$imanee->resize(1024, 768) // ->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id . DS . 'f_' . $filename, 80); //thumbnail $imanee->thumbnail(200, 200, true)->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id . DS . 't_' . $filename, 60); unlink(APPLICATION_PATH . '/../data/temp/' . $filename); $data = array('url' => $db->getUrl(), 'album_id' => $db->getAlbumId(), 'capa' => $db->getCapa()); $foto_id = $db->saveFoto($data); $data['foto_id'] = $foto_id; echo json_encode($data); } } }
public function rdfuploadAction() { $this->view->placeholder('main.window.title')->set('Upload RDF Dumps'); if ($this->_request->isPost()) { $postData = $this->_request->getPost(); $upload = new Zend_File_Transfer(); $filesArray = $upload->getFileInfo(); $message = ''; switch (true) { case empty($filesArray): $message = 'upload went wrong. check post_max_size in your php.ini.'; break; case $filesArray['source']['error'] == UPLOAD_ERR_INI_SIZE: $message = 'The uploaded files\'s size exceeds the upload_max_filesize directive in php.ini.'; break; case $filesArray['source']['error'] == UPLOAD_ERR_PARTIAL: $message = 'The file was only partially uploaded.'; break; case $filesArray['source']['error'] >= UPLOAD_ERR_NO_FILE: $message = 'Please select a file to upload'; break; } if ($message != '') { $this->_owApp->appendErrorMessage($message); return; } $file = $filesArray['source']['tmp_name']; // setting permissions to read the tempfile for everybody // (e.g. if db and webserver owned by different users) chmod($file, 0644); $locator = Erfurt_Syntax_RdfParser::LOCATOR_FILE; $filetype = 'auto'; // guess file mime type if ($postData['filetype-upload'] != 'auto') { $filetype = $postData['filetype-upload']; } else { // guess file type extension $extension = strtolower(strrchr($filesArray['source']['name'], '.')); if ($extension == '.rdf' || $extension == '.owl') { $filetype = 'rdfxml'; } else { if ($extension == '.n3') { $filetype = 'ttl'; } else { if ($extension == '.json') { $filetype = 'rdfjson'; } else { if ($extension == '.ttl') { $filetype = 'ttl'; } else { if ($extension == '.nt') { $filetype = 'ttl'; } } } } } } try { $this->_import($file, $filetype, $locator); } catch (Exception $e) { $message = $e->getMessage(); $this->_owApp->appendErrorMessage($message); return; } $this->_owApp->appendSuccessMessage('Data successfully imported.'); } }
/** * handle a archive upload (from browser) */ public function installarchiveuploadAction() { $ontoWiki = OntoWiki::getInstance(); $upload = new Zend_File_Transfer(); $filesArray = $upload->getFileInfo(); if ($filesArray['archive_file']['error'] == UPLOAD_ERR_OK) { // upload ok, $tmpName = $filesArray['archive_file']['tmp_name']; $cachedir = ini_get('upload_tmp_dir'); $name = $this->getParam('name', ""); if ($name == '') { $ontoWiki->appendMessage(new OntoWiki_Message('parameters url and name needed.', OntoWiki_Message::ERROR)); } else { $this->installArchive($cachedir . $tmpName, $name); } } else { $ontoWiki->appendMessage(new OntoWiki_Message('upload error.', OntoWiki_Message::ERROR)); } }
/** * Controller to handle file upload form * @throws Exception */ public function indexAction() { $response = new stdClass(); try { $upload = new Zend_File_Transfer(); } catch (Exception $e) { $response->error = $e->getMessage(); $this->_helper->json->sendJson($response); } $upload->addValidator('Count', false, array('min' => 1, 'max' => 100)); $upload->addValidator('IsImage', false); $upload->addValidator('Size', false, array('max' => '10MB', 'bytestring' => false)); $translate = Zend_Registry::get('Zend_Translate'); $updating = false; try { if (!$upload->receive()) { throw new Exception($translate->translate('error_uploading')); } else { $files = $upload->getFileInfo(); // Updating hash with new images if (!empty($_POST['hash']) && Unsee_Hash::isValid($_POST['hash'])) { $hashDoc = new Unsee_Hash($_POST['hash']); $updating = true; $response = array(); if (!Unsee_Session::isOwner($hashDoc) && !$hashDoc->allow_anonymous_images) { die('[]'); } } else { // Creating a new hash $hashDoc = new Unsee_Hash(); $this->setExpiration($hashDoc); $response->hash = $hashDoc->key; } $imageAdded = false; foreach ($files as $file => $info) { if ($upload->isUploaded($file)) { $imgDoc = new Unsee_Image($hashDoc); $res = $imgDoc->setFile($info['tmp_name']); $imgDoc->setSecureParams(); //hack to populate correct secureTtd if ($updating) { $ticket = new Unsee_Ticket(); $ticket->issue($imgDoc); $newImg = new stdClass(); $newImg->hashKey = $hashDoc->key; $newImg->key = $imgDoc->key; $newImg->src = '/image/' . $imgDoc->key . '/' . $imgDoc->secureMd5 . '/' . $imgDoc->secureTtd . '/'; $newImg->width = $imgDoc->width; $newImg->ticket = md5(Unsee_Session::getCurrent() . $hashDoc->key); $response[] = $newImg; } if ($res) { $imageAdded = true; } // Remove uploaded file from temporary dir if it wasn't removed if (file_exists($info['tmp_name'])) { @unlink($info['tmp_name']); } } } if (!$imageAdded) { throw new Exception('No images were added'); } } } catch (Exception $e) { $response->error = $e->getMessage(); } $this->_helper->json->sendJson($response); }
public function filesAction() { if (!$this->getRequest()->isPost()) { throw new AppEx\ForbiddenException("Files action must be a post request."); } $front = Zend_Controller_Front::getInstance(); $front->registerPlugin(new \Tid_Zend_Controller_Plugin_UploadMax()); try { $upload = new Zend_File_Transfer('App_File_Transfer_Adapter_HttpMultipartMixed', false, array('ignoreNoFile' => true)); } catch (Zend_File_Transfer_Exception $e) { throw new AppEx\InvalidArgumentException($e->getMessage()); } $upload->addValidator('Count', true, array('min' => 1, 'max' => 1))->addValidator('Extension', true, array('xml', 'csv', 'txt'))->addValidator('MimeType', true, array('application/xml', 'text/plain', 'headerCheck' => true)); if ($upload->isValid()) { if ($upload->receive()) { try { $fileinfo = current($upload->getFileInfo()); $filename = $fileinfo['tmp_name']; // Attempt to parse data from file $parseResult = $this->_stockSrv->getData($filename, $upload->getMimeType()); $data = $parseResult['data']; $errors = $parseResult['errors']; if (!empty($errors) && is_array($errors)) { foreach ($errors as $errMess) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $method = 'create' . ucfirst($data['_type']); if (!empty($data['_type']) && is_callable(array($this->_stockSrv, $method))) { // Check permissions according to the data type $dumbSim = new Application\Model\SimModel(); $this->_helper->allowed($data['_perm'], $dumbSim); try { $watcher = $this->_stockSrv->{$method}($parseResult); } catch (AppEx\GlobalServiceException $ex) { $ex->addErrorMessages($errors); throw $ex; } $txId = uniqid('parser'); WatcherService::getInstance()->pushEntityId($watcher, $txId); $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->eventData = $errors; $event->created = time(); $event->forceFinish = true; WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors_ex = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors_ex)) { $errors = Zend_Json::encode($errors_ex); App::log()->warn("Error on file upload in stock:\n" . $errors); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors_ex)); } } else { throw new AppEx\UnexpectedException('Unknown data type (' . $data['_type'] . ')'); } } catch (PermissionException $e) { throw $e; } catch (StockParserException $e) { throw $e; } catch (GlobalServiceException $e) { $txId = uniqid('parser'); if (!isset($watcher)) { $watcher = $this->_stockSrv->createFileWatcher(); $watcher->entityIds = array($txId); $watcher->params->type = 'sim'; $watcher->params->action = 'stockUpload'; $watcher->save(); } else { WatcherService::getInstance()->pushEntityId($watcher, $txId); } $event = new EventModel(); $event->entityId = $txId; $event->entityType = 'transaction'; $event->namespace = 'connectivity'; $event->created = time(); $event->modified = time(); $event->pushEventData = true; $eventData = array(); $errors = $e->getErrorMessages(); $eventData['hasFailures'] = true; if (!empty($errors) && is_array($errors)) { require_once APPLICATION_PATH . '/modules/default/controllers/ErrorController.php'; foreach ($errors as $errMess) { if ($errMess instanceof ErrorModel) { $errMess->code = ErrorController::finishErrorCode($errMess->code); } } $eventData['message'] = array('failed' => $errors); } $event->eventData = $eventData; $event->forceFinish = true; $compressor = new ErrorModelCompressEvent(); $compressor->compress($event); WatcherService::getInstance()->publishEvent($event); // WatcherService::getInstance()->setStatus($watcher->id, WatcherModel::STATUS_FINISHED); $errors = $this->_loadErrorsFromWatcher($watcher); if (!empty($errors)) { App::log()->warn("Error on file upload in stock:\n" . Zend_Json::encode($errors)); throw new AppEx\StockParserException("Some errors uploading file to stock.", array('errorMessages' => $errors)); } } } else { throw new AppEx\InvalidArgumentException('Could not receive file'); } } else { throw new AppEx\InvalidArgumentException('Invalid file: ' . implode(', ', $upload->getMessages())); } }
public function applyAction() { $this->view->pageTitle = 'Careers'; if ($this->getRequest()->isPost()) { // Handle the cv file and form data $filters = array('name' => 'StringTrim', 'tel' => 'StringTrim', 'email' => 'StringTrim', 'enquiry' => 'StringTrim'); $validators = array('name' => array('NotEmpty', 'messages' => 'Please enter your name'), 'tel' => array('NotEmpty', 'messages' => 'Please enter your telephone number'), 'email' => array('NotEmpty', 'messages' => 'Please enter your email address'), 'enquiry' => array('NotEmpty', 'messages' => 'Please tell us why this position interests you')); $input = new Zend_Filter_Input($filters, $validators, $_POST); if ($input->isValid()) { $upload = new Zend_File_Transfer(); // Make sure the file is actually a document $upload->clearValidators(); $upload->setOptions(array('ignoreNoFile' => true)); //$upload->addValidator('MimeType', false, array('application/msword', 'application/pdf', 'application/rtf', 'text/plain')); if ($upload->isValid()) { $params = Zend_Registry::get('params'); $uploadPath = $params->cms->fileUploadPath; $upload->setDestination($uploadPath); $upload->receive(); $fileInfo = $upload->getFileInfo(); $emailer = new Application_Core_Mail(); $emailer->setTo($params->email->careers, 'HomeLet'); $emailer->setFrom($input->email, $input->name); $emailer->setSubject('HomeLet - Job Application (' . $input->position . ')'); $bodyHtml = 'Position : ' . $input->position . '<br />'; $bodyHtml .= 'Name : ' . $input->name . '<br />'; $bodyHtml .= 'Email : ' . $input->email . '<br />'; $bodyHtml .= 'Tel : ' . $input->tel . '<br />'; $bodyHtml .= 'Enquiry : <pre>' . $input->enquiry . '</pre><br />'; if ($fileInfo['cv_file']['type'] !== null) { $emailer->addAttachment($fileInfo['cv_file']['destination'] . '/' . $fileInfo['cv_file']['name'], $fileInfo['cv_file']['name']); } $emailer->setBodyHtml($bodyHtml); if ($emailer->send()) { $this->_helper->redirector('thanks', 'careers'); } else { } } else { // Invalid file type $this->view->errors = array('cv_file' => 'Invalid file type'); $this->view->name = $input->name; $this->view->tel = $input->tel; $this->view->email = $input->email; $this->view->enquiry = $input->enquiry; } } else { // Invalid form data $this->view->errors = $input->getMessages(); $this->view->name = $input->name; $this->view->tel = $input->tel; $this->view->email = $input->email; $this->view->enquiry = $input->enquiry; } } $careerUrl = $this->getRequest()->getParam('careerID'); $careerID = substr($careerUrl, 0, strpos($careerUrl, '-')); $careers = new Datasource_Cms_Careers(); $career = $careers->getById($careerID); $this->view->title = $career['title']; $this->view->id = $career['id']; }
public function processpictureAction() { // disable rendering of the view and layout so that we can just echo the AJAX output $this->_helper->layout->disableLayout(); $this->_helper->viewRenderer->setNoRender(TRUE); $session = SessionWrapper::getInstance(); $config = Zend_Registry::get("config"); $this->_translate = Zend_Registry::get("translate"); $formvalues = $this->_getAllParams(); //debugMessage($this->_getAllParams()); $user = new UserAccount(); $user->populate(decode($this->_getParam('id'))); // only upload a file if the attachment field is specified $upload = new Zend_File_Transfer(); // set the file size in bytes $upload->setOptions(array('useByteString' => false)); // Limit the extensions to the specified file extensions $upload->addValidator('Extension', false, $config->uploads->photoallowedformats); $upload->addValidator('Size', false, $config->uploads->photomaximumfilesize); // base path for profile pictures $destination_path = BASE_PATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . "users" . DIRECTORY_SEPARATOR . "user_"; // determine if user has destination avatar folder. Else user is editing there picture if (!is_dir($destination_path . $user->getID())) { // no folder exits. Create the folder mkdir($destination_path . $user->getID(), 0777); } // set the destination path for the image $profilefolder = $user->getID(); $destination_path = $destination_path . $profilefolder . DIRECTORY_SEPARATOR . "avatar"; if (!is_dir($destination_path)) { mkdir($destination_path, 0777); } // create archive folder for each user $archivefolder = $destination_path . DIRECTORY_SEPARATOR . "archive"; if (!is_dir($archivefolder)) { mkdir($archivefolder, 0777); } $oldfilename = $user->getProfilePhoto(); //debugMessage($destination_path); $upload->setDestination($destination_path); // the profile image info before upload $file = $upload->getFileInfo('profileimage'); $uploadedext = findExtension($file['profileimage']['name']); $currenttime = time(); $currenttime_file = $currenttime . '.' . $uploadedext; $thefilename = $destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime_file; $thelargefilename = $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime_file; $updateablefile = $destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime; $updateablelarge = $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime; //debugMessage($thefilename); // rename the base image file $upload->addFilter('Rename', array('target' => $thefilename, 'overwrite' => true)); // exit(); // process the file upload if ($upload->receive()) { // debugMessage('Completed'); $file = $upload->getFileInfo('profileimage'); // debugMessage($file); $basefile = $thefilename; // convert png to jpg if (in_array(strtolower($uploadedext), array('png', 'PNG', 'gif', 'GIF'))) { ak_img_convert_to_jpg($thefilename, $updateablefile . '.jpg', $uploadedext); unlink($thefilename); } $basefile = $updateablefile . '.jpg'; // new profilenames $newlargefilename = "large_" . $currenttime_file; // generate and save thumbnails for sizes 250, 125 and 50 pixels resizeImage($basefile, $destination_path . DIRECTORY_SEPARATOR . 'large_' . $currenttime . '.jpg', 400); resizeImage($basefile, $destination_path . DIRECTORY_SEPARATOR . 'medium_' . $currenttime . '.jpg', 165); // unlink($thefilename); unlink($destination_path . DIRECTORY_SEPARATOR . 'base_' . $currenttime . '.jpg'); // exit(); // update the user with the new profile images try { $user->setProfilePhoto($currenttime . '.jpg'); $user->save(); // check if user already has profile picture and archive it $ftimestamp = current(explode('.', $user->getProfilePhoto())); $allfiles = glob($destination_path . DIRECTORY_SEPARATOR . '*.*'); $currentfiles = glob($destination_path . DIRECTORY_SEPARATOR . '*' . $ftimestamp . '*.*'); // debugMessage($currentfiles); $deletearray = array(); foreach ($allfiles as $value) { if (!in_array($value, $currentfiles)) { $deletearray[] = $value; } } // debugMessage($deletearray); if (count($deletearray) > 0) { foreach ($deletearray as $afile) { $afile_filename = basename($afile); rename($afile, $archivefolder . DIRECTORY_SEPARATOR . $afile_filename); } } $session->setVar(SUCCESS_MESSAGE, $this->_translate->translate("global_update_success")); $this->_helper->redirector->gotoUrl($this->view->baseUrl("profile/picture/id/" . encode($user->getID()) . '/crop/1')); } catch (Exception $e) { $session->setVar(ERROR_MESSAGE, $e->getMessage()); $session->setVar(FORM_VALUES, $this->_getAllParams()); $this->_helper->redirector->gotoUrl($this->view->baseUrl('profile/picture/id/' . encode($user->getID()))); } } else { // debugMessage($upload->getMessages()); $uploaderrors = $upload->getMessages(); $customerrors = array(); if (!isArrayKeyAnEmptyString('fileUploadErrorNoFile', $uploaderrors)) { $customerrors['fileUploadErrorNoFile'] = "Please browse for image on computer"; } if (!isArrayKeyAnEmptyString('fileExtensionFalse', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_ext_error'), $config->uploads->photoallowedformats); $customerrors['fileExtensionFalse'] = $custom_exterr; } if (!isArrayKeyAnEmptyString('fileUploadErrorIniSize', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_size_error'), formatBytes($config->uploads->photomaximumfilesize, 0)); $customerrors['fileUploadErrorIniSize'] = $custom_exterr; } if (!isArrayKeyAnEmptyString('fileSizeTooBig', $uploaderrors)) { $custom_exterr = sprintf($this->_translate->translate('global_invalid_size_error'), formatBytes($config->uploads->photomaximumfilesize, 0)); $customerrors['fileSizeTooBig'] = $custom_exterr; } $session->setVar(ERROR_MESSAGE, 'The following errors occured <ul><li>' . implode('</li><li>', $customerrors) . '</li></ul>'); $session->setVar(FORM_VALUES, $this->_getAllParams()); $this->_helper->redirector->gotoUrl($this->view->baseUrl('profile/picture/id/' . encode($user->getID()))); } // exit(); }
public function editarAction() { $eq = new Equipe(); $request = $this->getRequest(); $id = $request->getParam('id'); $equipe = $eq->getById($id); if (!$equipe) { $this->_helper->redirector('listar', 'equipe'); } $erro = false; if ($request->isPost()) { $erro = false; $msg = ''; $eq->setNome($request->getPost('Nome')); $eq->setCargo($request->getPost('Cargo')); $eq->setDescricao($request->getPost('Descricao')); $data = array('nome' => $eq->getNome(), 'cargo' => $eq->getCargo(), 'descricao' => $eq->getDescricao()); $eq->save($data, $id); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(APPLICATION_PATH . '/../data/temp'); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); if ($files['Avatar']['tmp_name']) { if (!file_exists(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'equipe' . DS . $id)) { mkdir(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'equipe' . DS . $id, 0777, true); } foreach ($files as $file => $info) { if ($upload->isUploaded($file)) { //$extension = substr($info['name'], strrpos($info['name'], '.') + 1); $filename = 'avatar.jpg'; $adapter->addFilter('Rename', array('target' => APPLICATION_PATH . '/../data/temp/' . $filename, 'overwrite' => true)); $adapter->receive($info['name']); if (!$adapter->receive()) { $messages = $adapter->getMessages(); echo implode("\n", $messages); exit; } //setFileName::Url $eq->setAvatar($filename); $imanee = new Imanee\Imanee(APPLICATION_PATH . '/../data/temp/' . $filename); //resized $imanee->resize(300, 300)->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'equipe' . DS . $id . DS . $filename, 80); //full //$imanee->resize(1024, 768) // ->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id . DS . 'f_' . $filename, 80); unlink(APPLICATION_PATH . '/../data/temp/' . $filename); } } } if ($erro) { $msg = 'Ocorreu um erro, tente novamente'; $this->view->msg = $msg; } else { $this->_helper->redirector('listar', 'equipe'); } } $this->view->equipe = $equipe; $this->render(); }
/** * @param $id * @param Zend_File_Transfer $upload * @param string $uploadName * @return mixed */ protected function _uploadFiles($id, Zend_File_Transfer $upload, $uploadName = 'fileLoad') { $destinationPath = UPLOAD_DIR . '/products/' . $id; if (!file_exists($destinationPath)) { mkdir($destinationPath, 0755, true); } $upload->setDestination($destinationPath)->addValidator('Size', false, 1024000)->addValidator('Extension', false, 'jpg,png,gif,svg'); $upload->receive($uploadName); $uploadFile = $upload->getFileInfo($uploadName); return $uploadFile; }
/** * @param $id * @param Zend_File_Transfer $upload * @param string $inputName * @return mixed */ protected function _uploadFiles($id, Zend_File_Transfer $upload, $inputName = 'fileLoad') { $moduleFolder = UPLOAD_DIR . '/categories'; if (!file_exists($moduleFolder)) { mkdir($moduleFolder, 0755); } $destinationPath = $moduleFolder . '/' . $id; if (!file_exists($destinationPath)) { mkdir($destinationPath, 0755); } $upload->setDestination($destinationPath)->addValidator('Size', false, 1024000)->addValidator('Extension', false, 'jpg,png,gif,svg'); $upload->receive(); $uploadFile = $upload->getFileInfo($inputName); return $uploadFile; }
public function editarAction() { $tp = new LoginTipo(); $ut = new Util(); $us = new Usuarios(); $tiposLogin = $tp->getAllLoginTipo(); $request = $this->getRequest(); $id = $request->getParam('id'); $usuario = $us->getUserByLoginId($id); if (!$usuario) { $this->_helper->redirector('listar', 'usuarios'); } if ($request->isPost()) { $erro = false; $msg = ''; $nascimento = empty($request->getPost('Nascimento')) ? NULL : $ut->dateToSql($request->getPost('Nascimento')); $now = $ut->nowDateSql(); $rg = $ut->limpaDados($request->getPost('Rg')); $cpf = $ut->limpaDados($request->getPost('Cpf')); $telefone = $ut->limpaDados($request->getPost('Telefone')); $celular = $ut->limpaDados($request->getPost('Celular')); $us->setNome($request->getPost('Nome')); $us->setSobrenome($request->getPost('Sobrenome')); $us->setEmail($request->getPost('Email')); $us->setLoginId($id); $us->setRg($rg); $us->setCpf($cpf); $us->setNascimento($nascimento); $us->setTelefone($telefone); $us->setCelular($celular); $us->setSexo($request->getPost('Sexo')); $us->setCadastradoEm($now); $data = array('nome' => $us->getNome(), 'sobrenome' => $us->getSobrenome(), 'email' => $us->getEmail(), 'login_id' => $us->getLoginId(), 'rg' => $us->getRg(), 'cpf' => $us->getCpf(), 'nascimento' => $us->getNascimento(), 'telefone' => $us->getTelefone(), 'celular' => $us->getCelular(), 'sexo' => $us->getSexo()); $us->saveUser($data, $id); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(APPLICATION_PATH . '/../data/temp'); $upload = new Zend_File_Transfer(); $files = $upload->getFileInfo(); if ($files['Avatar']['tmp_name']) { if (!file_exists(ROOT_DIR . DS . 'painel' . DS . 'images' . DS . 'usuario' . DS . $id)) { mkdir(ROOT_DIR . DS . 'painel' . DS . 'images' . DS . 'usuario' . DS . $id, 0777, true); } foreach ($files as $file => $info) { if ($upload->isUploaded($file)) { //$extension = substr($info['name'], strrpos($info['name'], '.') + 1); $filename = 'avatar.jpg'; $adapter->addFilter('Rename', array('target' => APPLICATION_PATH . '/../data/temp/' . $filename, 'overwrite' => true)); $adapter->receive($info['name']); if (!$adapter->receive()) { $messages = $adapter->getMessages(); echo implode("\n", $messages); exit; } //setFileName::Url2 $us->setAvatar($filename); $imanee = new Imanee\Imanee(APPLICATION_PATH . '/../data/temp/' . $filename); //resized $imanee->resize(300, 300, false)->write(ROOT_DIR . DS . 'painel' . DS . 'images' . DS . 'usuario' . DS . $id . DS . $filename, 80); //full //$imanee->resize(1024, 768) // ->write(ROOT_DIR . DS . 'site' . DS . 'images' . DS . 'galeria' . DS . $album_id . DS . 'f_' . $filename, 80); unlink(APPLICATION_PATH . '/../data/temp/' . $filename); } } } if ($erro) { $msg = 'Ocorreu um erro, tente novamente'; $this->view->msg = $msg; } else { $this->_helper->redirector('listar', 'usuarios'); } } $this->view->usuario = $usuario; $this->view->tipos = $tiposLogin; $this->view->util = $ut; $this->render(); }
public function imageuploadAction() { $ArticleMapper = new Application_Model_ImageinfoMapper(); $method = $this->_request->getParam("method"); if ($method == "post") { $deptid = $this->_request->getParam("deptid"); //实例化文件上传类 $upload = new Zend_File_Transfer(); $upload->addValidator('Size', false, 5 * 1024 * 1024); $upload->addValidator('Extension', false, 'jpg,gif,png'); if (!$upload->isValid()) { echo "<script>alert('格式不符或文件过大,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } //获取上传的文件表单,可以有多项 $fileInfo = $upload->getFileInfo(); $parseImg = new Application_Model_Admin_Admin(); $filetmp = $parseImg->resize_image($fileInfo['imageFile']['name'], $fileInfo['imageFile']['tmp_name'], '480', '280'); imagedestroy($fileInfo['imageFile']['tmp_name']); //获取后缀名,这里imageFile为上传表单file控件的name $ext = explode(".", $fileInfo['imageFile']['name']); $ext = $ext[1]; //定义生成目录 $dir = './upload' . date('/Y/m/'); //文件重新命名 do { $filename = date('His') . rand(100000, 999999) . '.' . $ext; } while (file_exists($dir . $filename)); //如果目录不存在则创建目录 if (!file_exists($dir)) { mkdir($dir, 0777, true); } //将图片正式写入 $pass = imagejpeg($filetmp, $dir . '/' . $filename, 100); if (!$pass) { imagedestroy($filetmp); echo "<script>alert('图片资源上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } imagedestroy($filetmp); //将图片信息插入数据库 $i = $ArticleMapper->uploadImageInfo($filename, $_SESSION['user']['RealName'], $deptid); if (!isset($i)) { echo "<script>alert('图片信息上传失败,请重新尝试');location.href = '/admin/imageupload';</script>"; exit; } echo "<script>alert('上传成功!');location.href = '/admin/imageupload';</script>"; } else { //加载列表 $DeptMapper = new Application_Model_DepartmentMapper(); $arr = $DeptMapper->findAllDept(); $this->view->arrDept = $arr; $this->view->imageArr = $ArticleMapper->selectImageInfo($_SESSION['user']['RealName']); } }