/** * @param $file * @param $accountId * @throws \Exception */ public function addPictureFromRequest($file, $accountId) { $picture = $file->get('file'); $adapter = new Http(); $size = new Size(array('max' => $this::MAXIMUM_PICTURE_SIZE)); //$extension = new Extension(array('extension' => array('jpeg', 'jpg', 'gif', 'tiff', 'png', 'bmp'))); $adapter->setValidators(array($size), $picture['name']); if (!$adapter->isValid()) { $errors = $adapter->getMessages(); $message = ''; foreach ($errors as $error) { $message .= $error; break; } throw new \Exception($message); } $tmpFileUrl = $accountId . '_logo.jpg'; $destinationFolder = dirname(__DIR__) . $this::UPLOAD_FOLDER; $destinationFile = $destinationFolder . "/" . $tmpFileUrl; if (!file_exists($destinationFolder)) { mkdir($destinationFolder); } $adapter->addFilter('Rename', array('target' => $destinationFile, 'overwrite' => true)); if (!$adapter->receive($picture['name'])) { throw new \Exception("An error was found while uploading the picture"); } }
public function addAction() { if (!$this->zfcUserAuthentication()->hasIdentity()) { return $this->redirect()->toRoute('zfcuser'); } $form = new UploadForm(); $optionSubject = $this->getSubjectTable()->getSubjectsForSelect(); $form->get('subject')->setAttribute('options', $optionSubject); $optionCategory = $this->getCategoryTable()->getCategoriesForSelect(); $form->get('category')->setAttribute('options', $optionCategory); $request = $this->getRequest(); if ($request->isPost()) { $file = new File(); $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()); $form->setData($data); $uploadPath = $this->getOptions()->getUploadFolderPath(); // Validatoren $size = new Size(array('max' => $this->getOptions()->getMaxFileSizeInByte())); $extension = new Extension($this->getOptions()->getAllowedFileExtensions()); // Filter für Zufallsnamen if ($this->options->getRandomizeFileName()) { $rename = new Rename(array('target' => $uploadPath . '/file', 'randomize' => true)); } else { $rename = null; } //TODO Add to factory $adapter = new Http(); $adapter->setValidators(array($size, $extension)); $adapter->setFilters(array($rename)); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); array_merge($dataError, $adapter->getErrors()); foreach ($dataError as $key => $row) { echo $row; } header('HTTP/1.1 500 Internal Server Error'); exit; } else { $adapter->setDestination($uploadPath); if ($adapter->receive()) { $subjectID = $data['subject']; $categoryID = $data['category']; $dbdata = array(); $dbdata['fileName'] = $data['file']['name']; $filename = $adapter->getFileName(); if (is_array($filename)) { $dbdata['url'] = basename(current($filename)); } else { $dbdata['url'] = basename($filename); } $file->exchangeArray($dbdata); $this->getFileTable()->saveFile($file, $subjectID, $categoryID); header('HTTP/1.1 200 OK'); exit; } } } return array('form' => $form); }
public function uploadAction() { $id_slab = (int) $this->getEvent()->getRouteMatch()->getParam('id_slab'); $aReturn = array(); $aDataInsert = array(); $sDestination = ROOT_DIR . '/upload/slab/' . $id_slab . '/'; (int) ($id_user = $this->getAuthService()->getStorage()->read()->id); $aDataInsert['id_slab'] = $id_slab; $aDataInsert['cr_date'] = new \Zend\Db\Sql\Expression("getdate()"); $aDataInsert['cr_user'] = $id_user; if (!is_dir($sDestination)) { if (!@mkdir($sDestination, 0777, true)) { throw new \Exception("Unable to create destination: " . $sDestination); } } $size = new Size(array('min' => 10, "max" => 10000000)); //minimum bytes filesize $count = new Count(array("min" => 0, "max" => 1)); $extension = new Extension(array("extension" => array("jpg", "png", "swf"))); $adapter = new \Zend\File\Transfer\Adapter\Http(); $file = $adapter->getFileInfo(); $adapter->setValidators(array($size, $count, $extension), $file['file']['name']); $adapter->setDestination($sDestination); if ($adapter->isValid()) { if ($adapter->isUploaded()) { if ($adapter->receive()) { $file = $adapter->getFileInfo(); $aDataInsert['photo'] = $file['file']['name']; $aDataInsert['name'] = $file['file']['name']; $this->getContainerDrawingTable()->save($aDataInsert); $aReturn['state'] = true; } } else { $aReturn['state'] = false; } } else { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $aReturn['state'] = false; } return new JsonModel($aReturn); }
public function postAction() { $request = $this->getRequest(); if ($request->isPost()) { $product = new Product(); $product->name = $request->getPost('name'); $product->price = $request->getPost('price'); $product->manufacture = $request->getPost('manufacture'); $product->inventory_number = $request->getPost('inventory_number'); $product->date = $request->getPost('date'); $product->show = $request->getPost('show'); // Get images $temp = array(); $imgTotal = intval($request->getPost('imgTotal')); $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000)); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg')); for ($i = 0; $i < $imgTotal; $i++) { $fileName = 'image_' . $i; $image = $request->getFiles($fileName); $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/products/' . $product->name . '-' . $image['name'], 'randomize' => true)); if ($httpadapter->isValid()) { if ($httpadapter->receive($image['name'])) { $temp[] = $httpadapter->getFileInfo()[$fileName]['name']; } } } $product->images = implode(';', $temp); $product->display = $request->getPost('display'); $product->os = $request->getPost('os'); $product->cpu = $request->getPost('cpu'); $product->camera = $request->getPost('camera'); $product->internal_memory = $request->getPost('internal_memory'); $product->ram = $request->getPost('ram'); $product->battery = $request->getPost('battery'); $product->more = $request->getPost('more'); // Insert product if ($this->getProductTable()->insertProduct($product)) { echo json_encode('successful'); } else { echo json_encode('Insert error'); } exit; } }
public function importAction() { $request = $this->getRequest(); $this->form->get('type')->setValue($this->params('type')); if ($request->isPost()) { $nonFile = $request->getPost()->toArray(); $file = $this->params()->fromFiles('fileupload'); $data = array_merge($nonFile, ['fileupload' => $file['name']]); //set data post and file ... $this->form->setData($data); if ($this->form->isValid()) { //$size = new Size(array('max' => '204800B')); //minimum bytes filesize $adapter = new Http(); //$adapter->setValidators(array($size), $file['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $this->form->setMessages(['fileupload' => $error]); } else { $pathUploadFiles = $this->importer->getDriverFactory()->getConfig()['file_upload_path']; if (!is_dir($pathUploadFiles)) { mkdir($pathUploadFiles, 0775, true); } $adapter->setDestination($pathUploadFiles); //\Zend\Debug\Debug::dump([$adapter->getFileName($file['name'])]); die(__METHOD__); /*\Zend\Debug\Debug::dump([ $file['name'], $adapter->receive($adapter->getFileName('fileupload', false)), $adapter->isFiltered($file['name']), $adapter->getMessages() ]); die(__METHOD__.__LINE__);*/ //$fileName = $adapter->getFileName('fileupload', false); if ($adapter->receive($adapter->getFileName('fileupload', false))) { $this->importer->import($this->params('type'), $adapter->getFileName('fileupload')); $this->prepareMessages(); } } } } //\Zend\Debug\Debug::dump([$form->getName(), get_class($form)]); die(__METHOD__); return ['form' => $this->form]; }
public function updateAction() { $id = $this->params()->fromRoute('id'); $request = $this->getRequest(); $message = null; if ($request->isPost()) { // Get file upload $files = $request->getFiles()->toArray(); $filePostName = 'image'; $file = $files[$filePostName]; // Check validate $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000), $filePostName); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg'), $filePostName); // Rename file upload $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/ads/' . $file['name'], 'randomize' => true), $filePostName); // Save file upload $newFileName = null; if ($httpadapter->isValid()) { if ($httpadapter->receive($file['name'])) { $fileInfo = $httpadapter->getFileInfo(); $newFileName = $fileInfo[$filePostName]['name']; } } $adsPost = new Advertise(); $adsPost->id = $id; $adsPost->image = $newFileName; $adsPost->link = $request->getPost('link'); $adsPost->date_start = $request->getPost('date_start'); $adsPost->date_end = $request->getPost('date_end'); $adsPost->location = $request->getPost('location'); $adsPost->show = $request->getPost('show'); $adsPost->view_count = $request->getPost('view_count'); $adsPost->click_count = $request->getPost('click_count'); $result = $this->getAdvertiseTable()->updateAdvertise($adsPost); if ($result) { $message = 'Successful!'; } else { $message = 'Error!! Please try again.'; } } $ads = $this->getAdvertiseTable()->getAdvertiseById($id); return new ViewModel(array('ads' => $ads, 'message' => $message)); }
public function updateAction() { $request = $this->getRequest(); if ($request->isPost()) { // Get file upload $files = $request->getFiles()->toArray(); $logo = $files['logo']; // Check validate $httpadapter = new Http(); $httpadapter->addValidator('Size', true, array('min' => 1000)); $httpadapter->addValidator('Extension', true, array('png', 'jpg', 'jpeg')); // Rename file upload $httpadapter->addFilter('Rename', array('target' => __UPLOAD__ . '/page/' . $logo['name'], 'randomize' => true)); // Save file upload $newFileName = null; if ($httpadapter->isValid()) { if ($httpadapter->receive($logo['name'])) { $fileInfo = $httpadapter->getFileInfo(); $newFileName = $fileInfo['logo']['name']; } } $data = new Info(); $data->name = $request->getPost('name'); if (isset($newFileName)) { $data->logo = '/upload/page/' . $newFileName; } else { $data->logo = null; } $data->address = $request->getPost('address'); $data->tel = $request->getPost('tel'); $data->introduce = $request->getPost('introduce'); $data->image = $request->getPost('image'); $this->getInfoTable()->updateInfo($data); } $this->redirect()->toRoute('shopinfo'); }
public function execute() { $file = new Http(); $fileInfo = $file->getFileInfo(); // armazena os caminhos dos arquivos que fizeram upload para remover em caso de erros $tempDirUpload = array(); // retorno com o nome do arquivo enviados $return = array(); foreach ($fileInfo as $id => $item) { // se for um array renomeia separadamente os arquivos if (is_array($this->rename)) { if (array_key_exists($id, $this->rename)) { $newName = $this->rename[$id] . "." . substr(strrchr($item['name'], '.'), 1); $file->setFilters(array('Rename' => $newName), $id); } } elseif ($this->rename) { $newName = md5(microtime()) . "." . substr(strrchr($item['name'], '.'), 1); $file->setFilters(array('Rename' => $newName)); // se for null fica a imagem com o nome normal } else { $newName = $item['name']; } // destino do arquivo $destination = is_array($this->destination) ? $this->path . $this->destination[$id] : $this->path . $this->destination; if (!is_dir($destination)) { mkdir($destination); } chmod($destination, "0775"); $file->setDestination($destination, $id); // validações $arrValidators = array(); // verifica se tem validação de tamanho se tiver aplica if ($this->sizeValidation !== null) { $size = isset($this->sizeValidation[$id]) ? $this->sizeValidation[$id] : $this->sizeValidation; $sizeValidation = new Size(array('min' => $size[0], 'max' => $size[1])); $arrValidators[] = $sizeValidation; } // verifica se tem validação de extensão se tiver aplica if ($this->extValidation !== null) { $ext = isset($this->extValidation[$id]) ? $this->extValidation[$id] : $this->extValidation; $extValidation = new Extension($ext); $arrValidators[] = $extValidation; } // setando as validações caso existam if (count($arrValidators)) { $file->setValidators($arrValidators, $id); } // valida o arquivo if ($file->isValid($id)) { // envia o arquivo if ($file->receive($id)) { // seta o destino do arquivo $tempDirUpload[] = $destination . "/" . $newName; // seta o nome do arquivo $return['files'][$id] = $newName; // verifica se tem destino thumb se tiver gera a thumb if (count($this->thumbOpt)) { // setando os opções obrigatórias $arrThumbOptRequire = array('destination' => 'destination', 'width' => 'width', 'height' => 'height', 'cropimage' => 'cropimage'); // Validando se todos os parâmetros foram passados foreach ($this->thumbOpt as $thumbIndex => $thumbValue) { unset($arrThumbOptRequire[$thumbIndex]); } if (count($arrThumbOptRequire)) { throw new \Exception('Configure corretamente o setThumb("destination", "width", "height", "cropimage")'); } /* * Criando a thumb usando o modulo JVEasyPhpThumbnail */ $destinationThumb = $this->path . $this->thumbOpt['destination'] . "/"; if (!is_dir($destinationThumb)) { mkdir($destinationThumb); } chmod($destinationThumb, "0775"); $phpThumb = new PHPThumb(); $phpThumb->Thumblocation = $destinationThumb; $phpThumb->Chmodlevel = '0755'; $phpThumb->Thumbsaveas = substr(strrchr($item['name'], '.'), 1); $phpThumb->Thumbwidth = $this->thumbOpt['width']; $phpThumb->Thumbheight = $this->thumbOpt['height']; $phpThumb->Cropimage = $this->thumbOpt['cropimage']; $destination = $destination . "/" . $newName; $phpThumb->Createthumb($destination, 'file'); } } } else { $keyError = $file->getErrors(); // verifica se fez algum upload se tiver exclui os arquivos, mas caso o required esteja setado como true if (count($tempDirUpload) && ($this->required && in_array('fileUploadErrorNoFile', $keyError)) || !in_array('fileUploadErrorNoFile', $keyError)) { foreach ($tempDirUpload as $filename) { unlink($filename); } } if ($this->required && in_array('fileUploadErrorNoFile', $keyError) || !in_array('fileUploadErrorNoFile', $keyError)) { return array('error' => array($id => $file->getMessages())); } } } return $return; }
protected function validateImportFile($file) { $size = new Size(array('min' => 1024, 'max' => 2048000)); // min/max bytes filesize $adapter = new FileHttp(); $ext = new FileExt(array('extension' => array('csv'))); $adapter->setValidators(array($size, $ext), $file['name']); $isValid = $adapter->isValid(); if (!$isValid) { $dataError = $adapter->getMessages(); $this->errorResponse->addMessage($dataError, "error"); } else { $adapter->setDestination($this->getUploadPath()); if ($adapter->receive($file['name'])) { $isValid = $file['name']; } } return $isValid; }
public function isValidParent($files = null) { return parent::isValid($files); }
public function editarAction() { $id = $this->params('id'); $filme = $this->getFilmesTable()->getFilmes($id); $form = new FilmesForm(); $form->setBindOnValidate(false); $form->get('submit')->setLabel('Alterar'); $categories = $this->getCategoryTable()->getAllFormArray(); $form->get('categoria_id')->setValueOptions($categories); $form->bind($filme); $request = $this->getRequest(); if ($request->isPost()) { $nonFile = $request->getPost()->toArray(); $File = $this->params()->fromFiles('filmes_foto'); if ($File['name'] == "") { $name_file = $filme->filmes_foto; } else { $name_file = $File['name']; } $data = array_merge($nonFile, array('filmes_foto' => $name_file)); $form->setData($data); if ($form->isValid()) { $form->bindValues(); if ($File['name'] != "") { $size = new Size(array('max' => 2000000)); $adapter = new Http(); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $erro = array(); foreach ($dataError as $row) { $erro[] = $row; } $form->setMessages(array('filmes_foto' => $erro)); } else { $diretorio = $request->getServer()->DOCUMENT_ROOT . '/conteudo/filmes'; $adapter->setDestination($diretorio); if ($adapter->receive($File['name'])) { $this->flashMessenger()->addMessage(array('success' => 'A foto foi enviada com sucesso!')); } else { $this->flashMessenger()->addMessage(array('danger' => 'A foto não foi enviada!')); } } } $this->getFilmesTable()->saveFilmes($filme); $this->flashMessenger()->addMessage(array('success' => 'Registro alterado com sucesso!')); $this->redirect()->toUrl("/filmes"); } } $view = new ViewModel(array('form' => $form)); $view->setTemplate('application/filmes/form.phtml'); return $view; }
/** * @param Http $adapter * * @return array */ private function uploadFiles(Http $adapter) { $uploadStatus = []; foreach ($adapter->getFileInfo() as $key => $file) { if (!$adapter->isValid($file['name'])) { foreach ($adapter->getMessages() as $key => $msg) { $uploadStatus['errorFiles'][] = $file['name'] . ' ' . strtolower($msg); } } // @codeCoverageIgnoreStart if (!$adapter->receive($file['name'])) { $uploadStatus['errorFiles'][] = $file['name'] . ' was not uploaded'; } else { $uploadStatus['successFiles'][] = $file['name'] . ' was successfully uploaded'; } // @codeCoverageIgnoreEnd } return $uploadStatus; }
protected function validateImportFile($file) { $size = new Size(array('min' => 128, 'max' => 20480000)); // min/max bytes filesize $ext = new FileExt(array('extension' => array('xls', 'xlsx', 'csv'))); $mime = new MimeType(array('application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'text/plain', 'text/csv')); $adapter = new FileHttp(); $adapter->setValidators(array($size, $ext, $mime), $file['name']); $isValid = $adapter->isValid(); if (!$isValid) { $dataError = $adapter->getMessages(); $this->flashMessenger()->addErrorMessage($this->errorImportTypeMessage . '<br>' . implode(' <br>', $dataError)); } else { $adapter->setDestination($this->getUploadPath()); if ($adapter->receive()) { $isValid = $adapter->getFileName(null, false); } else { $dataError = $adapter->getMessages(); $this->flashMessenger()->addErrorMessage($this->errorImportTypeMessage . '<br>' . implode(' <br>', $dataError)); $isValid = false; } } return $isValid; }
/** * See if file name is valid and it not return alll messages. * * @param Http $adapter * @param string $fileName * * @return array */ private function validateUploadedFileName(Http $adapter, $fileName) { $uploadStatus = []; if (!$adapter->isValid($fileName)) { foreach ($adapter->getMessages() as $msg) { $uploadStatus['errorFiles'][] = $fileName . ' ' . strtolower($msg); } } return $uploadStatus; }
/** * Handles a given form for the add and edit action * @return array Array for the view, containing the form and maybe id and errors */ private function handleForm(Request &$request, NewsCategoryForm &$form, NewsCategory &$nc, $id = 0) { $form->setInputFilter($nc->getInputFilter()); $post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray()); $form->setData($post); if ($form->isValid()) { $nc->exchangeArray($post); $old = $this->getNewsCategoryTable()->getNewsCategoryBy(['id' => $id]); if ($this->getNewsCategoryTable()->getNewsCategoryBy(['name' => $nc->getName()]) && ($id === 0 || $nc->getName() !== $old->getName())) { $errors['name'] = ['exists' => 'A category with this name already exists']; $form->get('name')->setMessages($errors); if (!$id) { return ['form' => $form, 'errors' => $errors]; } return ['form' => $form, 'errors' => $errors, 'id' => $id]; } $size = new Size(['min' => 20, 'max' => 20000]); $adapter = new Http(); $adapter->setValidators([$size], $post['path']); //Only throw error if a new category is created. New Categories need an image if (!$adapter->isValid() && $id === 0) { $errors = $adapter->getMessages(); return ['form' => $form, 'errors' => $errors]; } $dir = getcwd() . '/public/news_cat/'; //A file was given, so it will be saved on the server if ($adapter->isValid()) { if (!file_exists($dir)) { mkdir($dir); } $pic = $post['path']; $file = file_get_contents($pic['tmp_name']); file_put_contents($dir . $nc->getName() . '.png', $file); } else { //No new file was given, so update the filename to the new name rename($dir . $old->getName() . '.png', $dir . $nc->getName() . '.png'); } $this->getNewsCategoryTable()->saveNewsCategory($nc); return $this->redirect()->toRoute('newscategory'); } $errors = $form->getMessages(); if ($id) { return ['form' => $form, 'errors' => $errors, 'id' => $id]; } return ['form' => $form, 'errors' => $errors]; }