Example #1
0
 public function uploadAction()
 {
     $renderer = $this->getServiceLocator()->get('Zend\\View\\Renderer\\RendererInterface');
     $fileDirectory = new DirectoryIterator(self::PATH_IMAGES);
     $adapter = new Http();
     $adapter->setDestination(implode(DIRECTORY_SEPARATOR, [self::PATH_IMAGES, FileProperties::DIR_RAW]));
     $result = ['media' => [], 'length' => $this->requestContentLength($this->getRequest())];
     foreach ($adapter->getFileInfo() as $info) {
         $originalFileName = $info['name'];
         $uploadedFileObject = new SplFileInfo(implode(DIRECTORY_SEPARATOR, [$info['destination'], $info['name']]));
         $newFileName = $this->cleanFileName($uploadedFileObject->getFilename());
         $fileObject = new SplFileInfo(implode(DIRECTORY_SEPARATOR, [$uploadedFileObject->getPath(), $newFileName]));
         $type = null;
         if ($adapter->receive($originalFileName)) {
             rename($uploadedFileObject->getPathname(), implode(DIRECTORY_SEPARATOR, [$uploadedFileObject->getPath(), $newFileName]));
             if (preg_match('/^image\\/jpe?g|png|gif$/', $info['type'])) {
                 $type = 'image';
                 $generator = new ImageGenerator($fileObject, $fileDirectory);
             } else {
                 $type = 'file';
                 $generator = new FileGenerator($fileObject, $fileDirectory);
             }
             $actionResponse = $generator->execute();
             $actionResponse->setRenderer($renderer);
             $result['media'][] = ['code' => 200, 'message' => 'Success', 'file' => $actionResponse, 'type' => $type];
         } else {
             $errorArray = $adapter->getErrors();
             $result['media'][] = ['code' => 501, 'message' => array_pop($errorArray), 'file' => null, 'type' => $type];
         }
     }
     return new JsonModel($result);
 }
 public function moveFile($file)
 {
     $adapter = new Http();
     $adapter->setDestination(dirname(__DIR__) . './../../../../public/useruploads/files');
     $bool = $adapter->receive($file['name']);
     return $bool;
 }
Example #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 uploadImage($file)
 {
     $filename = $file['file']['name'];
     $adapter = new Http();
     $path = BASE_PATH . '/img/position';
     $fileRenameFilter = new Rename(array('target' => $path . '/usr.jpg', 'randomize' => true));
     $adapter->addFilters(array($fileRenameFilter));
     if ($adapter->receive($filename)) {
         $fileFullPath = explode('/', $adapter->getFileName());
         $newFileName = array_pop($fileFullPath);
         return $newFileName;
     } else {
         return 'no-image.png';
     }
 }
Example #5
0
 public function move($postdata)
 {
     if (!$postdata && !isset($postdata['filepath']) && !isset($postdata['destination'])) {
         throw new Exception("invalid input", '500');
     }
     $adapter = new Http();
     $adapter->addFilter('File\\Rename', array('target' => $postdata['destination'], 'use_upload_extension' => true, 'overwrite' => true));
     try {
         if ($adapter->receive()) {
             $file = $adapter->getFilter('File\\Rename')->getFile();
             echo $file[0]['target'];
         } else {
             throw new \Exception('Unable to upload file', '500');
         }
     } catch (\Exception $ex) {
         throw new \Exception($ex->getMessage(), '500');
     }
 }
 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);
 }
Example #7
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");
     }
 }
Example #8
0
 public function uploadImage($fileData)
 {
     $upload = new Http();
     $upload->setDestination(self::UPLOAD_PATH);
     try {
         // upload received file(s)
         $upload->receive();
     } catch (\Exception $e) {
         // return $uploadResult;
     }
     //This method will return the real file name of a transferred file.
     $name = $upload->getFileName($fileData['upload']['name']);
     //This method will return extension of the transferred file
     $extention = pathinfo($name, PATHINFO_EXTENSION);
     //get random new name
     $newName = $this->random->getRandomUniqueName();
     $newFullName = self::UPLOAD_PATH . $newName . '.' . $extention;
     // rename
     rename($name, $newFullName);
     $uploadResult = $newFullName;
     return $uploadResult;
 }
 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');
 }
 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;
 }
 private function uploadAttachment($filename, $attachmentPath)
 {
     $uploadResult = null;
     $upload = new Http();
     $upload->setDestination($attachmentPath);
     try {
         // upload received file(s)
         $upload->receive($filename);
     } catch (\Exception $e) {
         return $uploadResult;
     }
     //This method will return the real file name of a transferred file.
     $name = $upload->getFileName($filename);
     //This method will return extension of the transferred file
     $extention = pathinfo($name, PATHINFO_EXTENSION);
     //get random new name
     $newName = $this->random->getRandomUniqueName() . '_' . date('Y.m.d_h:i:sa');
     $newFullName = $attachmentPath . $newName . '.' . $extention;
     // rename
     rename($name, $newFullName);
     $uploadResult = $newFullName;
     return $uploadResult;
 }
 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;
 }
Example #16
0
 public function isValidParent($files = null)
 {
     return parent::isValid($files);
 }
 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;
 }
Example #18
0
 /**
  * image upload
  */
 public function uploadAction()
 {
     if ($this->getRequest()->isPost()) {
         if (!is_dir($this->path . $this->locador->getId())) {
             mkdir($this->path . $this->locador->getId());
         }
         $fileTransfer = new FileTransfer();
         $arquivo = $fileTransfer->getFileInfo('fachada');
         //unlink($this->path.$this->locador->getId().'/original.' . strtolower(substr($arquivo['fachada']['name'], -3, 3)));
         $fileTransfer->setDestination($this->path . $this->locador->getId());
         $fileTransfer->addFilter('Rename', array('target' => 'original.' . strtolower(substr($arquivo['fachada']['name'], -3, 3)), 'overwrite' => true));
         $fileTransfer->receive();
         $this->redirect()->toRoute('Locador/imovel/novo', array('etapa' => 3));
     }
 }
 public function editAction()
 {
     try {
         $id = $this->params('id', false);
         $em = $this->getEntityManager();
         if ($id) {
             $form = new RecruitmentForm($em);
             $recruitment = $em->find('Recruitment\\Entity\\Recruitment', $id);
             $currentDate = new \DateTime();
             $beginDate = \DateTime::createFromFormat('d/m/Y', $recruitment->getRecruitmentBeginDate());
             if ($beginDate <= $currentDate) {
                 return new ViewModel(array('message' => 'Não é possível editar processos seletivos concluídos ou em andamento. Por favor, consulte o administrador do sistema.', 'form' => null));
             }
             $form->bind($recruitment);
             $request = $this->getRequest();
             if ($request->isPost()) {
                 $publicNotice = $recruitment->getRecruitmentPublicNotice();
                 $fileContainer = $request->getFiles()->toArray();
                 $file = $fileContainer['recruitment']['recruitmentPublicNotice'];
                 $data = $request->getPost();
                 $form->setData($data);
                 if ($form->isValid() && !$file['error'] && $file['size']) {
                     try {
                         $filename = $data['recruitment']['recruitmentYear'] . $data['recruitment']['recruitmentNumber'] . $data['recruitment']['recruitmentType'] . '.pdf';
                         $recruitment->setRecruitmentPublicNotice($filename);
                         $em->persist($recruitment);
                         $em->flush();
                         $targetDir = self::PUBLIC_NOTICE_DIR;
                         $targetFile = $targetDir . $filename;
                         if (file_exists($targetFile)) {
                             unlink(self::PUBLIC_NOTICE_DIR . $publicNotice);
                         }
                         $uploadAdapter = new HttpAdapter();
                         $uploadAdapter->addFilter('File\\Rename', array('target' => $targetFile, 'overwrite' => true));
                         $uploadAdapter->setDestination($targetDir);
                         if (!$uploadAdapter->receive($fileContainer['name'])) {
                             $messages = implode('\\n', $uploadAdapter->getMessages());
                             throw new \RuntimeException($messages);
                         }
                         return $this->redirect()->toRoute('recruitment/recruitment', array('action' => 'index'));
                     } catch (\Thrownable $ex) {
                         if ($ex instanceof UniqueConstraintViolationException) {
                             return new ViewModel(array('message' => 'Este processo seletivo já foi cadastrado.', 'form' => null));
                         }
                         return new ViewModel(array('message' => 'Erro inesperado: ' . $ex->getMessage(), 'form' => null));
                     }
                 }
                 return new ViewModel(array('message' => $file['error'] || !$file['size'] ? 'O upload do edital não pode ser feito. Por favor tente novamente.' : null, 'form' => $form));
             }
             return new ViewModel(array('form' => $form, 'message' => null));
         }
         return new ViewModel(array('form' => null, 'message' => 'Nenhum Processo Seletivo foi escolhido'));
     } catch (\Exception $ex) {
         return new ViewModel(array('form' => null, 'message' => $ex->getMessage()));
     }
 }
Example #20
0
 /**
  * @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;
 }
 public function addAction()
 {
     if ($this->getLoginTable()->validarSessao()) {
         $this->redirect()->toRoute('login');
     }
     $adapter = new Http();
     $destino = dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '/public/img/fotos/';
     $adapter->setDestination($destino);
     $request = $this->getRequest();
     $titulo = $id_update = $pasta = $hidden = $saida = null;
     if ($request->isPost()) {
         $titulo = $request->getPost('titulo');
         $titulo = str_replace("/", "-", $titulo);
         $id_update = $request->getPost('id');
         date_default_timezone_set('America/Sao_Paulo');
         $pasta = date("dmYHis");
         $files = $adapter->getFileInfo();
         if (!empty($files)) {
             mkdir($destino . $pasta . '/', 0777);
             $qtd = 0;
             foreach ($files as $file => $info) {
                 //$adapter->addFilter('Rename', $destino . $pasta . '/' . $info['name']);
                 $adapter->addFilter('Rename', $destino . $pasta . '/' . $qtd . '.jpg');
                 $adapter->receive($file);
                 $this->lista[$qtd] = '/nortes/public/img/fotos/' . $pasta . '/' . $qtd . '.jpg';
                 $qtd++;
             }
             $saida = $this->getPortfolioTable()->printFormulario($this->lista, $titulo, $pasta, null, null);
             $hidden = 'hidden = "true" ';
         } else {
             if (!is_null($id_update)) {
                 $fotos_update = $this->getFotosTable()->changeFotos($id_update);
                 $qtd = 0;
                 $id_fotos = array();
                 foreach ($fotos_update as $ft) {
                     $this->lista[$qtd] = '/nortes/public/img/fotos/' . $id_update . '/' . $ft['id'] . '.jpg';
                     $id_fotos[$qtd] = $ft;
                     $qtd++;
                 }
                 $hidden = 'hidden = "true" ';
                 $saida = $this->getPortfolioTable()->printFormulario($this->lista, $titulo, null, $id_update, $id_fotos);
             }
         }
         return array('titulo' => $titulo, 'saida' => $saida, 'hidden' => $hidden);
     }
 }
Example #22
0
 public function testUploadProgressAdapter()
 {
     if (!Adapter\Http::isApcAvailable() && !Adapter\Http::isUploadProgressAvailable()) {
         $this->markTestSkipped('Whether APC nor UploadExtension available');
     }
     $_GET['progress_key'] = 'mykey';
     $adapter = new AdapterProgressBar\Console();
     $status = array('progress' => $adapter, 'session' => 'upload');
     $status = HttpTestMockAdapter::getProgress($status);
     $this->assertTrue(array_key_exists('total', $status));
     $this->assertTrue(array_key_exists('current', $status));
     $this->assertTrue(array_key_exists('rate', $status));
     $this->assertTrue(array_key_exists('id', $status));
     $this->assertTrue(array_key_exists('message', $status));
     $this->assertTrue(array_key_exists('progress', $status));
     $this->assertTrue($status['progress'] instanceof ProgressBar\ProgressBar);
     $this->adapter->switchApcToUP();
     $status = HttpTestMockAdapter::getProgress($status);
     $this->assertTrue(array_key_exists('total', $status));
     $this->assertTrue(array_key_exists('current', $status));
     $this->assertTrue(array_key_exists('rate', $status));
     $this->assertTrue(array_key_exists('id', $status));
     $this->assertTrue(array_key_exists('message', $status));
     $this->assertTrue(array_key_exists('progress', $status));
     $this->assertTrue($status['progress'] instanceof ProgressBar\ProgressBar);
 }
Example #23
0
    /**
     * Render a form file
     *
     * @param  string $content
     * @return string
     */
    public function render($content)
    {
        $element = $this->getElement();
        if (!$element instanceof Element) {
            return $content;
        }

        $view = $element->getView();
        if (!$view instanceof View) {
            return $content;
        }

        $name      = $element->getName();
        $attribs   = $this->getAttribs();
        if (!array_key_exists('id', $attribs)) {
            $attribs['id'] = $name;
        }

        $separator = $this->getSeparator();
        $placement = $this->getPlacement();
        $markup    = array();
        $size      = $element->getMaxFileSize();
        if ($size > 0) {
            $element->setMaxFileSize(0);
            $markup[] = $view->formHidden('MAX_FILE_SIZE', $size);
        }

        if (Adapter\Http::isApcAvailable()) {
            $markup[] = $view->formHidden(ini_get('apc.rfc1867_name'), uniqid(), array('id' => 'progress_key'));
        } else if (Adapter\Http::isUploadProgressAvailable()) {
            $markup[] = $view->formHidden('UPLOAD_IDENTIFIER', uniqid(), array('id' => 'progress_key'));
        }

        if ($element->isArray()) {
            $name .= "[]";
            $count = $element->getMultiFile();
            for ($i = 0; $i < $count; ++$i) {
                $htmlAttribs        = $attribs;
                $htmlAttribs['id'] .= '-' . $i;
                $markup[] = $view->formFile($name, $htmlAttribs);
            }
        } else {
            $markup[] = $view->formFile($name, $attribs);
        }

        $markup = implode($separator, $markup);

        switch ($placement) {
            case self::PREPEND:
                return $markup . $separator . $content;
            case self::APPEND:
            default:
                return $content . $separator . $markup;
        }
    }
Example #24
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;
 }
Example #25
0
use Zend\File\Transfer\Adapter\Http;
use Zend\Form\Form;
use Zend\Form\Element;
use Zend\Form\View\Helper;
use Zend\Loader\StandardAutoloader;
use Zend\ProgressBar\Adapter\JsPull;
/**
 * This sample file demonstrates an advanced use case of Zend_ProgressBar with
 * Zend_Form and Zend_File_Transfer.
 */
require_once dirname(dirname(dirname(__DIR__))) . '/library/Zend/Loader/StandardAutoloader.php';
$loader = new StandardAutoloader(array('autoregister_zf' => true));
$loader->register();
if (isset($_GET['progress_key'])) {
    $adapter = new JsPull();
    Http::getProgress(array('progress' => $adapter));
    die;
}
?>
<html>
<head>
    <title>Zend_ProgressBar Upload Demo</title>
    <style type="text/css">
        iframe {
            position: absolute;
            left: -100px;
            top: -100px;

            width: 10px;
            height: 10px;
            overflow: hidden;
 /**
  * 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;
 }
Example #27
0
 /**
  * {@inheritDoc}
  *
  * @FIXME Array (or cURL upload) is handled differently in PHP 5.3/5.4
  */
 protected function getFiles($files, $names = false, $noexception = false)
 {
     $files = $files ?: null;
     $check = parent::getFiles($files, $names, $noexception);
     return $check;
 }
 public function testAdapterContainsFileWithName()
 {
     $this->dispatch('/learn-zf2-ajax-image-gallery/index/upload');
     $this->assertContains('test1.jpg', $this->adapter->getFileName());
 }