Пример #1
0
 public function testAdapterHasValidators()
 {
     $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]);
     $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true);
     $this->adapter->setValidators([$size, new IsImage(), $extension]);
     $testExtension = $this->adapter->getValidator('Extension');
     $testIsImage = $this->adapter->getValidator('IsImage');
     $testSize = $this->adapter->getValidator('Size');
     $this->assertInstanceOf('Zend\\Validator\\File\\Extension', $testExtension);
     $this->assertInstanceOf('Zend\\Validator\\File\\IsImage', $testIsImage);
     $this->assertInstanceOf('Zend\\Validator\\File\\Size', $testSize);
 }
Пример #2
0
 /**
  * @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");
     }
 }
Пример #3
0
 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);
 }
Пример #5
0
 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;
 }
Пример #6
0
 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;
 }
Пример #7
0
 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;
 }
Пример #8
0
 /**
  * Upload all images async.
  *
  * @return array
  */
 private function prepareImages()
 {
     $adapter = new Http();
     $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]);
     $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true);
     if (extension_loaded('fileinfo')) {
         $adapter->setValidators([new IsImage()]);
     }
     $adapter->setValidators([$size, $extension]);
     $adapter->setDestination('public/userfiles/images/');
     return $this->uploadFiles($adapter);
 }
Пример #9
0
 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;
 }
Пример #10
0
 /**
  * Upload all images async.
  *
  * @return JsonModel
  */
 public function prepareImages()
 {
     $adapter = new Http();
     $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]);
     $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true);
     $adapter->setValidators([$size, new IsImage(), $extension]);
     $this->makeDir('public/');
     $adapter->setDestination('public/userfiles/' . date('Y_M') . '/images/');
     $data = $this->uploadFiles($adapter);
     return new JsonModel($data);
 }
 /**
  * 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];
 }
Пример #12
0
 /**
  * @param int $userId - used to create a folder for the current user and rename the image
  *
  * @return void
  */
 private function uploadImage($userId = 0)
 {
     $userId = (int) $userId;
     $messages = [];
     $dir = 'public/userfiles/images/user-' . $userId . '/';
     $adapter = new Http();
     $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]);
     $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true);
     if (!is_dir($dir)) {
         mkdir($dir, 0750, true);
     }
     foreach ($adapter->getFileInfo() as $file) {
         $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
         $newName = $userId . '.' . $ext;
         $adapter->setValidators([$size, new IsImage(), $extension]);
         $adapter->addFilter('File\\Rename', ['target' => $dir . $newName, 'overwrite' => true]);
         $adapter->receive($file['name']);
         if (!$adapter->isReceived($file['name']) && $adapter->isUploaded($file['name'])) {
             $messages[] = $file['name'] . ' was not uploaded';
         }
     }
     $this->setLayoutMessages($messages, 'info');
 }