示例#1
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 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;
 }