Beispiel #1
0
 public function __invoke($destinationDir, $fileFieldName = 'file', $replace = false, $status = 0)
 {
     if (!$this->getController()->getRequest()->isPost()) {
         return;
     }
     if (!($data = $this->getController()->getRequest()->getFiles()->toArray())) {
         return;
     }
     if (empty($data[$fileFieldName])) {
         return;
     }
     $datafile = $data[$fileFieldName];
     if (!empty($datafile['error'])) {
         return;
     }
     $md5Dir = $this->fileService->getMd5Dir($datafile['name']);
     $destinationDir = $this->fileService->checkDirectory($destinationDir . $md5Dir);
     if (!$destinationDir) {
         return;
     }
     $fileadapter = new \Zend\File\Transfer\Adapter\Http();
     $realDEstinationDir = $this->fileService->getUploadDir() . $destinationDir;
     $fileadapter->setDestination($realDEstinationDir);
     $fileTable = $this->getController()->getServiceLocator()->get('File\\Table\\File');
     $filedata = array();
     $destinationPath = $this->fileService->createFilename($destinationDir, $datafile['name'], $filedata, $replace);
     if (!$replace) {
         $fileadapter->addFilter('Rename', array('target' => $filedata['basename']));
     }
     //Upload
     if ($fileadapter->receive($datafile['name'])) {
         $datafile = array('name' => $datafile['name'], 'path' => $destinationPath, 'mime' => $datafile['type'], 'size' => $datafile['size'], 'created' => date('Y-m-d H:i:s'), 'status' => $status);
         return $fileTable->insert($datafile);
     }
 }
 function uploadFile($form, $file, $image = null)
 {
     $options = $this->_options;
     $size = new Size(array('min' => $options['min'], 'max' => $options['max']));
     $type = new Extension($options['allowedExtensions']);
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     $adapter->setValidators(array($size, $type), $file['name']);
     if (!$adapter->isValid() || file_exists($options['galleryDir'] . $file['name'])) {
         $dataError = $adapter->getMessages();
         $error = array();
         foreach ($dataError as $key => $row) {
             $error[] = $row;
         }
         if (file_exists($options['galleryDir'] . $file['name'])) {
             $error[] = 'Die Datei ' . $file['name'] . ' existiert bereits. Bitte umbenennen';
         }
         return $error;
     } else {
         $adapter->setDestination($options['galleryDir']);
         if ($adapter->receive($file['name'])) {
             if ($image != null) {
                 $image->exchangeArray($form->getData());
                 return array('error' => '');
             }
         }
     }
 }
 public function processUploadAction()
 {
     $userTable = $this->getServiceLocator()->get('UserTable');
     $user_email = $this->getAuthService()->getStorage()->read();
     $user = $userTable->getUserByEmail($user_email);
     $form = $this->getServiceLocator()->get('UploadForm');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $upload = new Upload();
         $uploadFile = $this->params()->fromFiles('fileupload');
         $form->setData($request->getPost());
         if ($form->isValid()) {
             // Fetch Configuration from Module Config
             $uploadPath = $this->getFileUploadLocation();
             // Save Uploaded file
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             $adapter->setDestination($uploadPath);
             if ($adapter->receive($uploadFile['name'])) {
                 $exchange_data = array();
                 $exchange_data['label'] = $request->getPost()->get('label');
                 $exchange_data['filename'] = $uploadFile['name'];
                 $exchange_data['user_id'] = $user->id;
                 $upload->exchangeArray($exchange_data);
                 $uploadTable = $this->getServiceLocator()->get('UploadTable');
                 $uploadTable->saveUpload($upload);
                 return $this->redirect()->toRoute('users/upload-manager', array('action' => 'index'));
             }
         }
     }
     return array('form' => $form);
 }
 public function processAction()
 {
     $request = $this->getRequest();
     if ($request->isPost()) {
         // Make certain to merge the files info!
         $File = $this->params()->fromFiles('image-file');
         $post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
         $form = $this->getServiceLocator()->get('UploadForm');
         $form->setData($post);
         if ($form->isValid()) {
             // $data = $form->getData();
             // $size = new Size(array('min'=>2000000)); //minimum bytes filesize
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             //validator can be more than one...
             //$adapter->setValidators($File['name']);
             $adapter->setDestination($this->getFileUploadLocation());
             if ($adapter->receive($File['name'])) {
                 $uploadTable = $this->getServiceLocator()->get('UploadTable');
                 $userTable = $this->getServiceLocator()->get('UserTable');
                 $authService = $this->getServiceLocator()->get('AuthService');
                 $userEmail = $authService->getStorage()->read();
                 $user_info = $userTable->getUserByEmail($userEmail);
                 $upload_data = array('user_id' => $user_info["users_id"], 'label' => 'prazno ne unosim iz forme', 'filename' => $post["image-file"]["name"]);
                 $upload = new Upload();
                 $upload->exchangeArray($upload_data);
                 $uploadTable->saveUpload($upload);
             }
             // Form is valid, save the form!
             //return $this->redirect()->toRoute('upload-form/success');
         }
         return $this->redirect()->toRoute('uploads', array('action' => 'prva'));
     }
 }
Beispiel #5
0
 public function processAction()
 {
     if (!$this->request->isPost()) {
         return $this->redirect()->toRoute(NULL, array('controller' => 'upload', 'action' => 'index'));
     }
     //$post = $this->request->getPost();
     //$request = $this->getRequest();
     //Création du formulaire
     $form = new UploadForm();
     //récupération de l'objet de travail
     //$uploadFile = new File();
     $uploadFile = $this->params()->fromFiles('fileupload');
     $form->setData($this->{$request}->getPost());
     if ($form->isValid()) {
         // Fetch Configuration from Module Config
         $uploadPath = $this->getFileUploadLocation();
         // Save Uploaded file
         $adapter = new \Zend\File\Transfer\Adapter\Http();
         $adapter->setDestination($uploadPath);
         if ($adapter->receive($uploadFile['name'])) {
             // File upload sucessfull
             $exchange_data = array();
             $exchange_data['label'] = $request->getPost()->get('label');
             $exchange_data['filename'] = $uploadFile['name'];
             $exchange_data['user_id'] = $user->id;
             $upload->exchangeArray($exchange_data);
             $uploadTable = $this->getServiceLocator()->get('UploadTable');
             $uploadTable->saveUpload($upload);
             return $this->redirect()->toRoute('users/upload-manager', array('action' => 'index'));
         }
         /*
                     $post = $this->request->getPost();
                     $form = new UploadForm();
                     // to get Login Form
                   // $form = $this->getServiceLocator()->get('LoginForm');
         
                     
                     $inputFilter = new UploadFilter();
                     $form->setInputFilter($inputFilter);
                     $form->setData($post);
                         if (!$form->isValid()) {
           $model = new ViewModel(array(
             'error' => true,
              'form' => $form,
                    ));
         
                      $model->setTemplate('users/upload/index');
                  return $model;
          }
          
          // Créer l'utisateur avant la page de  confirmation  
           $this->createUpload($form->getData());
         
            return $this->redirect()->toRoute(NULL , array(
            'controller' => 'upload',
                'action' => 'confirm'
                          ));
         */
     }
 }
 /**
  * Add new comment attachment into database and uploads
  *
  * @author Coeus
  * @param $data
  * @return JsonModel
  */
 public function create($data = array())
 {
     //$attachmentPath = 'public' . DIRECTORY_SEPARATOR . 'attachments'.DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
     $attachmentPath = 'public/attachments/comments/';
     $attachmentName = md5(uniqid(null, true));
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     if (!$adapter->isValid()) {
         $dataError = $adapter->getMessages();
         $error = array();
         foreach ($dataError as $key => $row) {
             $error[] = $row;
         }
     } else {
         if (!is_dir($attachmentPath)) {
             mkdir($attachmentPath, 0766);
         }
         $adapter->setDestination($attachmentPath);
         $name = $adapter->getFileName(null, false);
         $extension = end(explode(".", $name));
         $newFilePath = $attachmentPath . $attachmentName . "." . $extension;
         $newName = $attachmentName . "." . $extension;
         $adapter->addFilter('Rename', array('target' => $newFilePath, 'overwrite' => true));
         $adapter->receive();
         if (isset($data['post_id'])) {
             $data['info'] = $data['post_id'] . '||' . $data['user_id'] . '||' . $data['post_owner_id'] . '||' . $data['resource_type'] . '||' . $data['resource_id'];
             $comment = $this->getCommentService()->addTimelineComment($data);
         } else {
             $data['info'] = $data['resource_id'] . '||' . $data['user_id'];
             //$data['content'] = $data['content'].'<a ng-click="openInBrowserTab('.$newName.');" href="javascript:void(0);"><i>'.$name.'</a></i>';
             $comment = $this->getCommentService()->addResourceComment($data, $data['resource_type']);
         }
         $attachmentId = $this->getService()->addCommentAttachment(array('comment_id' => $comment['comment_id'], 'file' => $name . ',' . $newName));
     }
     return new JsonModel(array('original_name' => $name, 'altered_name' => $newName, 'comment_id' => $comment['comment_id']));
 }
 public function addAction()
 {
     $auth = $this->getServiceLocator()->get('Zend\\Authentication\\AuthenticationService');
     if (!$auth->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $form = new CategoryForm();
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter(new CategoryFilter());
         $form->setData($request->getPost());
         $files = $request->getFiles()->toArray();
         $httpadapter = new \Zend\File\Transfer\Adapter\Http();
         $filesize = new \Zend\Validator\File\Size(array('min' => 2000));
         //1KB
         $extension = new \Zend\Validator\File\Extension(array('extension' => array('png', 'jpg')));
         $httpadapter->setValidators(array($filesize, $extension), $files['ctgr_image_filename']['name']);
         if ($httpadapter->isValid()) {
             $route = $httpadapter->setDestination('public/uploads/');
             if ($httpadapter->receive($files['ctgr_image_filename']['name'])) {
                 $newfile = $httpadapter->getFileName();
             }
         }
         if ($form->isValid()) {
             $data = $form->getData();
             $data['ctgr_image_filename'] = $data['ctgr_image_filename']['name'];
             unset($data['submit']);
             $this->getCategoriesTable()->insert($data);
             return $this->redirect()->toRoute('cms/default', array('controller' => 'category', 'action' => 'index'));
         }
     }
     return new ViewModel(array('form' => $form));
 }
 public function uploadAction()
 {
     $this->_loginedInUser();
     $this->uploadTable = $this->getServiceLocator()->get('UploadTable');
     $form = $this->getServiceLocator()->get('UploadForm');
     if ($this->request->isPost()) {
         $form->setData($this->request->getPost());
         $uploadFile = $this->params()->fromfiles('filename');
         if ($form->isValid()) {
             $uploadPath = $this->getFileUploadLocation();
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             $adapter->setDestination($uploadPath);
             if ($adapter->receive($uploadFile['name'])) {
                 // File upload sucessfully
                 $exchange_data = array();
                 $exchange_data['label'] = $this->request->getPost('label');
                 $exchange_data['filename'] = $uploadFile['name'];
                 $exchange_data['user_id'] = $this->user->id;
                 $upload = new Upload();
                 $upload->exchangeArray($exchange_data);
                 $this->uploadTable->saveUpload($upload);
                 $this->redirect()->toRoute(null, array('controller' => 'upload-manager', 'action' => 'index'));
             }
         }
     }
     $viewModel = new ViewModel(array('form' => $form));
     return $viewModel;
 }
 public function pdfAction()
 {
     try {
         $path_start = PUBLIC_PATH . self::PDF_UPLOAD_DIR;
         $url_start = self::PDF_UPLOAD_DIR;
         $request = $this->getRequest();
         if ($request->isPost()) {
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             $adapter->setDestination($path_start);
             $filesize = new \Zend\Validator\File\Size(array('max' => 10000000));
             // 10MB
             $extension = new \Zend\Validator\File\Extension(array('extension' => array('pdf')));
             foreach ($adapter->getFileInfo() as $file => $info) {
                 $name = $adapter->getFileName($file);
                 $ext = "." . pathinfo($name, PATHINFO_EXTENSION);
                 $adapter->setValidators(array($filesize, $extension), $info['name']);
                 $name_without_ext = time() . '_' . strtolower(HashGenerator::generate(6));
                 $pdfDefault = array("PATH" => $path_start . $name_without_ext . $ext, "URL" => $url_start . $name_without_ext . $ext);
                 $adapter->addFilter(new \Zend\Filter\File\Rename(array('target' => $pdfDefault['PATH'], 'overwrite' => true)), null, $file);
                 if ($adapter->isValid()) {
                     $adapter->receive($info['name']);
                 } else {
                     return new JsonModel(array('returnCode' => 201, 'msg' => "Allowed only pdf files (max 10MB)."));
                 }
             }
         }
         return new JsonModel(array('returnCode' => 101, 'result' => array('url' => $pdfDefault['URL']), 'msg' => 'Image has been uploaded.'));
     } catch (\Exception $e) {
         return new JsonModel(array('returnCode' => 201, 'msg' => $e->getMessage()));
     }
 }
Beispiel #10
0
 public function addAction()
 {
     $formJob = new JobForm($this->categoryTable);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $job = new Job();
         $formJob->setInputFilter($job->getInputFilter());
         $nonFiles = $this->getRequest()->getPost()->toArray();
         $files = $this->getRequest()->getFiles()->toArray();
         $data = array_merge_recursive($nonFiles, $files);
         $formJob->setData($data);
         if ($formJob->isValid()) {
             $size = new Size(array('max' => 716800));
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             $adapter->setValidators(array($size), $files['logo']);
             if (!$adapter->isValid()) {
                 $dataError = $adapter->getMessages();
                 $error = array();
                 foreach ($dataError as $key => $row) {
                     $error[] = $row;
                 }
                 $formJob->setMessages(array('logo' => $error));
             } else {
                 $adapter->setDestination('./public/resources');
                 if ($adapter->receive($files['logo']['name'])) {
                     $job->exchangeArray($formJob->getData());
                     $job->logo = $files['logo']['name'];
                     $this->jobTable->saveJob($job);
                     return $this->redirect()->toRoute('home');
                 }
             }
         }
     }
     return new ViewModel(array('form' => $formJob));
 }
Beispiel #11
0
 public function index02Action()
 {
     if ($this->request->isPost()) {
         $upload = new \Zend\File\Transfer\Adapter\Http();
         $upload->addValidator("Extension", false, array("png", "jpg"), "image");
         $upload->addValidator("Size", true, array("min" => "100KB", "max" => "1MB"), "zip");
         if ($upload->isValid()) {
             $upload->setDestination(FILES_PATH . "images", "image");
             $upload->setDestination(FILES_PATH . "zip", "zip");
             $upload->receive();
         } else {
             $message = $upload->getMessages();
             echo "<pre style='font-weight:bold'>";
             print_r($message);
             echo "</pre>";
         }
     }
 }
 /**
  * Signup if not logged in
  *
  * @return void
  */
 public function indexAction()
 {
     $this->layout('layout/signup');
     $viewData = array();
     $signupForm = new SignupForm();
     $signupForm->setAttribute('action', $this->url()->fromRoute('users-signup'));
     $request = $this->getRequest();
     if ($request->isPost()) {
         $data = $request->getPost()->toArray();
         $signupForm->setInputFilter(User::getInputFilter());
         $signupForm->setData($data);
         if ($signupForm->isValid()) {
             $files = $request->getFiles()->toArray();
             $data = $signupForm->getData();
             $data['avatar'] = $files['avatar']['name'] != '' ? $files['avatar']['name'] : null;
             if ($data['avatar'] !== null) {
                 $size = new Size(array('max' => 2048000));
                 $isImage = new IsImage();
                 $filename = $data['avatar'];
                 $adapter = new \Zend\File\Transfer\Adapter\Http();
                 $adapter->setValidators(array($size, $isImage), $filename);
                 if (!$adapter->isValid($filename)) {
                     $errors = array();
                     foreach ($adapter->getMessages() as $key => $row) {
                         $errors[] = $row;
                     }
                     $signupForm->setMessages(array('avatar' => $errors));
                 }
                 $destPath = 'data/tmp/';
                 $adapter->setDestination($destPath);
                 $fileinfo = $adapter->getFileInfo();
                 preg_match('/.+\\/(.+)/', $fileinfo['avatar']['type'], $matches);
                 $newFilename = sprintf('%s.%s', sha1(uniqid(time(), true)), $matches[1]);
                 $adapter->addFilter('File\\Rename', array('target' => $destPath . $newFilename, 'overwrite' => true));
                 if ($adapter->receive($filename)) {
                     $data['avatar'] = base64_encode(file_get_contents($destPath . $newFilename));
                     if (file_exists($destPath . $newFilename)) {
                         unlink($destPath . $newFilename);
                     }
                 }
             }
             unset($data['repeat_password']);
             unset($data['csrf']);
             unset($data['register']);
             $response = ApiClient::registerUser($data);
             if ($response['result'] == true) {
                 $this->flashMessenger()->addMessage('Account created!');
                 return $this->redirect()->toRoute('wall', array('username' => $data['username']));
             }
         }
     }
     $viewData['signupForm'] = $signupForm;
     return $viewData;
 }
 public function addAction()
 {
     $view = new ViewModel();
     $view->setVariable("id", "");
     $form = new FlickForm();
     $form->get('submit')->setValue('Ajouter');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $flick = new Flick();
         $form->setInputFilter($flick->getInputFilter(true));
         $File = $this->params()->fromFiles('fileupload');
         $nonFile = $request->getPost()->toArray();
         $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
         $form->setData($data);
         if ($form->isValid()) {
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             if (empty($File["name"])) {
                 $view->setVariable("form", $form);
                 return $view;
             }
             $path = pathinfo($File['name']);
             $ext = $path['extension'];
             $filename = md5($File['name']) . "-" . time() . "." . $ext;
             $adapter->addFilter('Rename', $filename);
             if (!$adapter->isValid()) {
                 echo 77;
                 exit;
                 $dataError = $adapter->getMessages();
                 $error = array();
                 foreach ($dataError as $key => $row) {
                     $error[] = $row;
                 }
                 $form->setMessages(array('fileupload' => $error));
             } else {
                 $adapter->setDestination(dirname(__DIR__) . '/../../../../public/assets');
                 // $adapter->setDestination('.');
                 if ($adapter->receive($File['name'])) {
                     $d = $form->getData();
                     $d["fileupload"] = $filename;
                     // var_dump($d);
                     // exit;
                     $flick->exchangeArray($d);
                     $this->getFlickTable()->saveFlick($flick);
                 }
             }
             // $flick->exchangeArray($form->getData());
             // Redirect to list of flicks
             return $this->redirect()->toRoute('me');
         }
     }
     $view->setVariable("form", $form);
     return $view;
 }
 /**
  * Add new company logo
  * 
  * @author Stoyan Rangelov
  * @param array $data the data from REST Client
  * @return \Zend\View\Model\JsonModel 
  */
 public function create($data = array())
 {
     $tmpPath = 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'logos' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
     $attachmentPath = 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'logos' . DIRECTORY_SEPARATOR;
     $attachmentName = md5(uniqid(null, true));
     $companyStatus = $data['company_status'];
     if ($companyStatus == 'new') {
         $adapter = new \Zend\File\Transfer\Adapter\Http();
         if (!$adapter->isValid()) {
             $dataError = $adapter->getMessages();
             $error = array();
             foreach ($dataError as $key => $row) {
                 $error[] = $row;
             }
         } else {
             $adapter->setDestination($tmpPath);
             $name = $adapter->getFileName(null, false);
             $extension = end(explode(".", $name));
             $newFilePath = $tmpPath . $attachmentName . "." . $extension;
             $newName = $attachmentName . "." . $extension;
             $adapter->addFilter('Rename', array('target' => $newFilePath, 'overwrite' => true));
             $adapter->receive();
         }
         return new JsonModel(array('original_name' => $name, 'altered_name' => $newName, 'status_code' => 200));
     } else {
         $adapter = new \Zend\File\Transfer\Adapter\Http();
         if (!$adapter->isValid()) {
             $dataError = $adapter->getMessages();
             $error = array();
             foreach ($dataError as $key => $row) {
                 $error[] = $row;
             }
         } else {
             $adapter->setDestination($attachmentPath);
             $name = $adapter->getFileName(null, false);
             $extension = end(explode(".", $name));
             $newFilePath = $attachmentPath . $attachmentName . "." . $extension;
             $newName = $attachmentName . "." . $extension;
             $adapter->addFilter('Rename', array('target' => $newFilePath, 'overwrite' => true));
             $adapter->receive();
         }
         $result = $this->getService()->addCompanyLogo($data, $newName);
         return new JsonModel($result);
     }
 }
 public function uploadCsvFile2Db($uploadCsvFile, $database)
 {
     // move file to target dir
     $targetDir = $this->moduleOptions->getContactUploadedCsvDir();
     $uploadCsvFileArray = $uploadCsvFile->toArray();
     $uploadElementName = key($uploadCsvFileArray);
     $csvFileName = $uploadCsvFileArray[$uploadElementName]['name'];
     $csvFileInfo = pathinfo($csvFileName);
     $now = new \DateTime();
     $receiver = new \Zend\File\Transfer\Adapter\Http();
     $receiver->setDestination($targetDir)->setFilters([new \Zend\Filter\File\Rename(["target" => $targetDir . '/uploaded_csv_' . $now->format('Y_m_d-H:i') . '_' . '.' . $csvFileInfo['extension'], "randomize" => true])]);
     $receiver->receive($uploadElementName);
     $newCsvFilePath = $receiver->getFileName($uploadElementName);
     // transform CSV file to array
     $contactsArray = $this->csvFile2Array($newCsvFilePath);
     // save array to databse
     $this->runProcessSave2Database($database, $contactsArray);
 }
Beispiel #16
0
 public function uploadContractFile($contractId)
 {
     if (!$contractId) {
         return array('code' => 0, 'messages' => 'Dữ liệu không hợp lệ');
     }
     $contract = new \Crm\Model\Contract();
     $contract->setId($contractId);
     $contractMapper = $this->getServiceLocator()->get('\\Crm\\Model\\ContractMapper');
     if (!$contractMapper->get($contract)) {
         return array('code' => 0, 'messages' => 'Không tìm thấy hợp đồng');
     }
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     $targetFolder = BASE_PATH . '/public/media/contract/' . $contract->getId();
     if (!file_exists($targetFolder)) {
         $oldmask = umask(0);
         mkdir($targetFolder, 0777, true);
         umask($oldmask);
     }
     $adapter->setDestination($targetFolder);
 }
Beispiel #17
0
 public function addAction()
 {
     $albumId = (int) $this->params()->fromRoute('id', 0);
     if (empty($albumId)) {
         $albumList = $this->getAlbumList();
     } else {
         $albumList = [];
     }
     $form = new PhotoForm($albumList);
     $form->get('submit')->setValue('Add');
     $request = $this->getRequest();
     if ($request->isPost()) {
         $photo = new Photo();
         $form->setInputFilter($photo->getInputFilter());
         $fileArray = $request->getFiles()->toArray();
         $post = array_merge_recursive($request->getPost()->toArray(), $fileArray);
         if (!$post['album_id'] && $albumId) {
             $post['album_id'] = $albumId;
         }
         $form->setData($post);
         if ($form->isValid()) {
             $photo->exchangeArray($form->getData());
             $uploadFile = $fileArray['file_upload'];
             $uploadPath = $this->getFileLocation();
             $fileAdapter = new \Zend\File\Transfer\Adapter\Http();
             $fileAdapter->setDestination($uploadPath);
             $fileAdapter->receive($uploadFile['name']);
             $pathParts = pathinfo($uploadFile['name']);
             $fileExtension = $pathParts['extension'];
             $photo->extension = $fileExtension;
             $newId = $this->getPhotoTable()->savePhoto($photo);
             $uploadFileName = $this->renameFile($uploadFile['name'], $newId);
             $this->imgResize($uploadFileName);
             return $this->redirect()->toRoute('album', array('action' => 'show', 'id' => $albumId));
         }
     }
     return array('form' => $form, 'album_id' => $albumId);
 }
 private function uploadFile($arr_file)
 {
     //set validators
     $arr_validators = array("filesize" => array("max" => 350000), "filemimetype" => array("mimetype" => "image/png,image/x-png,image/svg,image/svg+xml,image/jpg,image/gif"));
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     $adapter->setValidators($arr_validators, $arr_file["name"]);
     if (!$adapter->isValid()) {
         $arr_form_errors = $adapter->getMessages();
         $arr_errors = array();
         foreach ($arr_form_errors as $key => $row) {
             $arr_errors[] = $row;
         }
         //end foreach
         return array("result" => false, "errors" => $arr_errors);
     } else {
         $adapter->setDestination($this->getProfileSettingsModel()->getFilesPath());
         if ($adapter->receive($arr_file['name'])) {
             return array("result" => TRUE, "file_location" => $this->getProfileSettingsModel()->getFilesPath() . "/" . $arr_file["name"]);
         }
         //end if
     }
     //end if
 }
 /**
  * Add new task into database
  *
  * @author Hrayr Shahbazyan
  * @param null $data
  * @return JsonModel
  */
 public function create($data = array())
 {
     $attachmentPath = 'public' . DIRECTORY_SEPARATOR . 'attachments' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR;
     $attachmentName = md5(uniqid(null, true));
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     if (!$adapter->isValid()) {
         $dataError = $adapter->getMessages();
         $error = array();
         foreach ($dataError as $key => $row) {
             $error[] = $row;
         }
     } else {
         $adapter->setDestination($attachmentPath);
         $name = $adapter->getFileName(null, false);
         $extension = end(explode(".", $name));
         $newFilePath = $attachmentPath . $attachmentName . "." . $extension;
         $newName = $attachmentName . "." . $extension;
         $adapter->addFilter('Rename', array('target' => $newFilePath, 'overwrite' => true));
         $adapter->receive();
         //$attachmentId = $this->getService()->addTaskAttachment(array('task_id'=>$data['task_id'],'file'=>$name));
     }
     return new JsonModel(array('original_name' => $name, 'altered_name' => $newName));
 }
 public function addAction()
 {
     $entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
     $article = new Article();
     $form = $this->getForm($article, $entityManager, 'Add');
     $form->bind($article);
     $form->get('language')->setAttribute('class', 'browser-default');
     $form->get('resource')->setAttribute('class', 'browser-default');
     $form->get('categories')->setAttributes(array('class' => 'browser-default', 'style' => 'height:100px'));
     $form->get('tags')->setAttributes(array('class' => 'browser-default', 'style' => 'height:100px'));
     $request = $this->getRequest();
     if ($request->isPost()) {
         $files = $request->getFiles()->toArray();
         $httpadapter = new \Zend\File\Transfer\Adapter\Http();
         $filesize = new \Zend\Validator\File\Size(array('min' => 1000));
         //1KB
         $extension = new \Zend\Validator\File\Extension(array('extension' => array('png')));
         $httpadapter->setValidators(array($filesize, $extension), $files['art_image_filename']['name']);
         if ($httpadapter->isValid()) {
             $route = $httpadapter->setDestination('public/article/');
             if ($httpadapter->receive($files['art_image_filename']['name'])) {
                 $newfile = $httpadapter->getFileName();
             }
         }
         $post = $request->getPost();
         $form->setData($post);
         if ($form->isValid()) {
             $data = $form->getData();
             $article->setArtcImageFilename($files['art_image_filename']['name']);
             $this->prepareData($article);
             $entityManager->persist($article);
             $entityManager->flush();
             return $this->redirect()->toRoute('cms/default', array('controller' => 'index', 'action' => 'index'));
         }
     }
     return new ViewModel(array('form' => $form));
 }
 public function addAction()
 {
     $formPost = new PostForm($this->categoryTable);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $post = new Post();
         $formPost->setInputFilter($post->getInputFilter());
         $nonFiles = $this->getRequest()->getPost()->toArray();
         $files = $this->getRequest()->getFiles()->toArray();
         // Pour ZF 2.2.x uniquement
         $data = array_merge_recursive($nonFiles, $files);
         $formPost->setData($data);
         if ($formPost->isValid()) {
             $size = new Size(array('max' => 716800));
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             $adapter->setValidators(array($size), $files['image']);
             if (!$adapter->isValid()) {
                 $dataError = $adapter->getMessages();
                 $error = array();
                 foreach ($dataError as $key => $row) {
                     $error[] = $row;
                 }
                 $formPost->setMessages(array('image' => $error));
             } else {
                 $adapter->setDestination('./public/img/');
                 if ($adapter->receive($files['image']['name'])) {
                     $post->exchangeArray($formPost->getData());
                     $post->image = $files['image']['name'];
                     $this->postTable->savePost($post);
                     return $this->redirect()->toRoute('home');
                 }
             }
         }
     }
     return new ViewModel(array('form' => $formPost));
 }
 /**
  * Add new user avatar
  * 
  * @author Stoyan Rangelov
  * @param array $data the data from REST Client
  * @return \Zend\View\Model\JsonModel 
  */
 public function create($data = array())
 {
     $attachmentPath = 'public' . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR . 'avatars' . DIRECTORY_SEPARATOR;
     $attachmentName = md5(uniqid(null, true));
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     if (!$adapter->isValid()) {
         $dataError = $adapter->getMessages();
         $error = array();
         foreach ($dataError as $key => $row) {
             $error[] = $row;
         }
     } else {
         $adapter->setDestination($attachmentPath);
         $name = $adapter->getFileName(null, false);
         $extension = end(explode(".", $name));
         $newFilePath = $attachmentPath . $attachmentName . "." . $extension;
         $newName = $attachmentName . "." . $extension;
         $adapter->addFilter('Rename', array('target' => $newFilePath, 'overwrite' => true));
         $adapter->receive();
     }
     $userId = $data['user_id'];
     $result = $this->getService()->addUserAvatar($userId, $newName);
     return new JsonModel($result);
 }
Beispiel #23
0
 public function egresotrabajadorfileAction()
 {
     //Obtenemos id bbdd
     $sid = new Container('base');
     $id_db = $sid->offsetGet('id_db');
     //Guardamos Registro en Servidor
     $File = $this->params()->fromFiles('nombrefile');
     $adapterFile = new \Zend\File\Transfer\Adapter\Http();
     $nombre = $adapterFile->getFileName($File, false);
     $ruta = $_SERVER['DOCUMENT_ROOT'] . '/files/db/' . $id_db . '/admin/finanzas/egreso';
     //Validamos si existe el archivo
     if (file_exists($ruta . "/" . $nombre)) {
         $status = "nok";
         $desc = "Nombre de Archivo ya existe en el servidor, use otro nombre";
     } else {
         $status = "ok";
         $adapterFile->setDestination($ruta);
         $adapterFile->receive($File['name']);
         $nombre = $adapterFile->getFileName($File, false);
         $desc = "Archivo cargado Exitosamente";
     }
     //Retornamos a la vista
     $result = new JsonModel(array('status' => $status, 'desc' => $desc, 'name' => $nombre));
     return $result;
 }
 /**
  * Upload a new image
  *
  * @param Zend\Form\Form $form 
  * @param Users\Entity\User $user 
  * @param array $data
  */
 protected function createImage($form, $user, $data)
 {
     if ($data['image']['error'] != 0) {
         $data['image'] = NULL;
     }
     $form->setData($data);
     $size = new Size(array('max' => 2048000));
     $isImage = new IsImage();
     $filename = $data['image']['name'];
     $adapter = new \Zend\File\Transfer\Adapter\Http();
     $adapter->setValidators(array($size, $isImage), $filename);
     if (!$adapter->isValid($filename)) {
         $errors = array();
         foreach ($adapter->getMessages() as $key => $row) {
             $errors[] = $row;
         }
         $form->setMessages(array('image' => $errors));
     }
     if ($form->isValid()) {
         $destPath = 'data/tmp/';
         $adapter->setDestination($destPath);
         $fileinfo = $adapter->getFileInfo();
         preg_match('/.+\\/(.+)/', $fileinfo['image']['type'], $matches);
         $extension = $matches[1];
         $newFilename = sprintf('%s.%s', sha1(uniqid(time(), true)), $extension);
         $adapter->addFilter('File\\Rename', array('target' => $destPath . $newFilename, 'overwrite' => true));
         if ($adapter->receive($filename)) {
             $data = array();
             $data['image'] = base64_encode(file_get_contents($destPath . $newFilename));
             $data['user_id'] = $user->getId();
             if (file_exists($destPath . $newFilename)) {
                 unlink($destPath . $newFilename);
             }
             $response = ApiClient::postWallContent($user->getUsername(), $data);
             return $response['result'];
         }
     }
     return $form;
 }
 /**
  * edit a a post by id
  * @return
  */
 public function editAction()
 {
     if (!$this->zfcUserAuthentication()->hasIdentity()) {
         return $this->redirect()->toRoute('home');
     }
     $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
     $id = $this->params('id');
     $post = $em->getRepository('Blog\\Entity\\Post')->find($id);
     if (!$post) {
         return $this->redirect()->toRoute('admin_list_post');
     }
     $formManager = $this->serviceLocator->get('FormElementManager');
     $form = $formManager->get('Admin\\Form\\Form\\CreatePostForm');
     $request = $this->getRequest();
     $form->bind($post);
     if ($request->isPost()) {
         $postData = array_merge_recursive((array) $request->getPost(), (array) $request->getFiles());
         $file = (array) $request->getFiles();
         // fichier incorect
         if (!$file) {
             $this->flashMessenger()->setNamespace('error')->addMessage('Le fichier envoyé est incorrect');
             return $this->redirect()->toRoute('admin_edit_post', array("id" => $post->getId()));
         }
         $form->setData($postData);
         if ($form->isValid()) {
             $post = $form->getData();
             // tableau contenant le nom dufichier['name'] uploader,[type], [tmp_name],[error],[size]
             $filesDetails = $post->getFile();
             // on a un fichier a upload
             if ($filesDetails['tmp_name'] != "") {
                 if ($post->getPhoto() != null && file_exists($post->getAbsoluteWebPath())) {
                     unlink($post->getAbsoluteWebPath());
                 }
                 $httpadapter = new \Zend\File\Transfer\Adapter\Http();
                 $httpadapter->setDestination($post->getAbsoluteUploadDir());
                 $path_parts = pathinfo($filesDetails['name']);
                 $photo = sha1(uniqid(mt_rand(), true)) . "." . $path_parts['extension'];
                 $newFilePath = "./public/" . $post->getUploadDir() . '/' . $photo;
                 // modification du fichier uploader
                 $httpadapter->addFilter('\\Zend\\Filter\\File\\Rename', array('target' => $newFilePath, 'overwrite' => false));
                 // move uploaded file
                 $httpadapter->receive();
                 $post->setPhoto($photo);
                 $post->setPhotoRealName($filesDetails['name']);
                 $post->setPhotoExtension($path_parts['extension']);
             }
             $submit = $request->getPost('submit');
             $post = $form->getData();
             $em->flush();
             $this->flashMessenger()->setNamespace('success')->addMessage('Modification réussi');
             // Le user a cliqué sur Enregistrer et retourner à la liste
             if ($submit) {
                 return $this->redirect()->toRoute('admin_list_post');
             } else {
                 return $this->redirect()->toRoute('admin_edit_post', array("id" => $post->getId()));
             }
         }
     }
     return new ViewModel(array('form' => $form, 'flashMessages' => $this->flashMessenger()->getMessages(), 'post' => $post));
 }
 public function editHomeworkAction()
 {
     $auth = new AuthenticationService();
     $user = $auth->getIdentity();
     $id = $this->params()->fromRoute('id');
     $homework = $this->getHomeworkTable()->getHomework($id);
     $form = new HomeworkForm();
     $form->bind($homework);
     $form->get('submit')->setAttribute('value', 'Muuda');
     $form->get('id')->setValue($id);
     $form->get('user_id')->setValue($user->id);
     $form->get('subsubject_id')->setValue($homework->subsubject_id);
     $request = $this->getRequest();
     if ($request->isPost()) {
         $form->setInputFilter(new HomeworkFilter($this->getServiceLocator()));
         $post = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray());
         $form->setData($post);
         if ($form->isValid()) {
             $adapter = new \Zend\File\Transfer\Adapter\Http();
             if (!$adapter->isValid()) {
                 $error = array();
                 foreach ($adapter->getMessages() as $key => $row) {
                     $error[] = $row;
                 }
                 $form->setMessages(array('fileupload' => $error));
             } else {
                 $adapter->setDestination($this->getServiceLocator()->get('Config')['homework_dir']);
                 if ($adapter->receive()) {
                     $event = $this->getEvent();
                     $request = $event->getRequest();
                     $router = $event->getRouter();
                     $uri = $router->getRequestUri();
                     $baseUrl = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), $request->getBaseUrl());
                     $adapterFileName = $adapter->getFileName();
                     $filesName = $baseUrl . '/uploads/homework/' . substr(preg_replace('/\\.\\/public\\/uploads\\/homework/', '', $adapter->getFileName()), 1);
                     $post['url'] = $filesName;
                     $homework->exchangeArray($post);
                     $this->getHomeworkTable()->saveHomework($homework);
                     return $this->redirect()->toRoute('teacher/my-course');
                 }
             }
         }
     }
     return array('form' => $form, 'id' => $id, 'homework' => $homework);
 }
 public function nuevocircularAction()
 {
     $sid = new Container('base');
     $id_usuario = $sid->offsetGet('id_usuario');
     $id_db = $sid->offsetGet('id_db');
     $status = "";
     $mensaje = "";
     $id = "0";
     if (isset($id_usuario)) {
         $db_name = $sid->offsetGet('dbNombre');
         $this->dbAdapter = $this->getServiceLocator()->get($db_name);
         $circular = new CircularTable($this->dbAdapter);
         $File = $this->params()->fromFiles('fileData');
         $adapterFile = new \Zend\File\Transfer\Adapter\Http();
         $adapterFile->setDestination($_SERVER['DOCUMENT_ROOT'] . '/files/db/' . $id_db . '/circulares');
         $adapterFile->receive($File['name']);
         $nombreArchivoCircular = isset($File['name']) ? $File['name'] : "";
         $tamanioArchivoCircular = isset($File['size']) ? round((int) $File['size'] / 1024) : "0 KB";
         //validamos si existe un fichero ya registrado
         $vfile = $circular->getCircularByName($this->dbAdapter, $nombreArchivoCircular);
         if (count($vfile) > 0) {
             $status = "nok";
             $mensaje = "El fichero ya existe en la base de datos, con fecha y hora: " . $vfile[0]['date_start'] . ". Favor de elegir otro Archivo ";
         } else {
             $datos = array('descripcion_file' => '', 'nombre_file' => $nombreArchivoCircular, 'tamanio_file' => $tamanioArchivoCircular . " KB", 'destino' => 'Comunidad', 'estado' => 'Proceso', 'activo' => '1', 'user_create' => $id_usuario);
             $id = $circular->nuevoCircular($datos);
             $status = "ok";
             $mensaje = "Se ha registrado y enviado satisfactoriamente la actividad. Nro peticion: " . $id;
         }
         //Enviar Correo
     } else {
         $status = "nok";
         $mensaje = "usuario del sistema no encontrado, sesion time-out";
     }
     return new JsonModel(array('status' => $status, 'mensaje' => $mensaje, 'id' => $id));
 }
Beispiel #28
0
 /**
  * Function created to validate form
  * @return TRUE
  * @param int    $id         contains tour id
  * @param string $tourForm   contains form name
  * @param array  $data       contains form values
  * @param array  $tourHelper contains tourhelper object
  * @param Object $tour       contains tour object
  * @param array  $tourImage  contains tour image detail
  * */
 function validateForm($id, $productsForm, $data, $products, $productsTable)
 {
     $productsForm->setData($data);
     $imgUpload = new \Zend\File\Transfer\Adapter\Http();
     $extension = new \Zend\Validator\File\Extension(array('extension' => array('png', 'jpg', 'jpeg')));
     $imgUpload->setValidators(array($extension), $data['image']['name']);
     if (!$imgUpload->isValid() && $data['image']['name'] != '') {
         $this->setErrorMessage("Only png, jpeg and jpg files are allowed");
     } else {
         try {
             $this->beginDbTransaction();
             $imgUpload->setDestination(APPLICATION_PUBLIC_PATH . '/upload/Products');
             $imgUpload->receive($data['image']['name']);
             $products->setProductName($data['name']);
             $products->setProductStock($data['stock']);
             $products->setProductRent($data['rent']);
             $products->setProductSecurity($data['security']);
             $products->setProductCategory($data['category']);
             $products->setProductGender($data['gender']);
             $products->setProductSize($data['size']);
             $products->setProductDescription($data['description']);
             $products->setProductActualcost($data['actualcost']);
             $products->setProductBrand($data['brand']);
             $products->setProductOccassion($data['occassion']);
             $products->setProductDesigner($data['designer']);
             $products->setProductColor($data['color']);
             $products->setProductFromdate($data['fromdate']);
             $products->setProductTodate($data['todate']);
             $products->setProductSeotags($data['seotags']);
             $products->setProductSubcategory($data['subcategory']);
             if ($data['image']['name'] != '') {
                 $products->setProductImage($data['image']['name']);
             }
             $products = $productsTable->save($products);
             $this->setSuccessMessage("Products added successsfully");
             $this->commitDbTransaction();
             return $this->redirect()->toRoute('admin_view_products');
         } catch (Exception $ex) {
             $this->rollbackDbTransaction();
         }
     }
 }
 public function importCsvFile($filePath, $database)
 {
     // get dir for uploaded csv
     $targetDir = $this->moduleOptions->getContactUploadedCsvDir();
     // transfer uploded file
     $now = new \DateTime();
     $fileInfo = pathinfo($filePath);
     $receiver = new \Zend\File\Transfer\Adapter\Http();
     $receiver->setDestination($targetDir)->setFilters([new \Zend\Filter\File\Rename(["target" => $targetDir . '/uploaded_csv_' . $now->format('Y_m_d-H:i') . '_' . '.' . $fileInfo['extension'], "randomize" => true])]);
     // file upload element in form class should have name 'csv-file' !! TODO: fix this dependency
     $receiver->receive('csv-file');
     $uploadedCsvFilePath = $receiver->getFileName('csv-file');
     // detect delimiter for csv
     $delimiter = self::detectCsvFileDelimiter($uploadedCsvFilePath);
     // convert file to array
     $contactsArray = file($uploadedCsvFilePath);
     // get titles of columns and transform
     $columnNames = str_getcsv($contactsArray[0], $delimiter);
     array_walk($columnNames, function (&$item) {
         $item = str_replace(" ", "-", $item);
         $item = strtolower($item);
     });
     foreach ($contactsArray as $key => $contact) {
         // get CSV line by line
         $contact = str_getcsv($contact, $delimiter);
         // change keys in array to column names
         $contact = array_combine($columnNames, $contact);
         // detect Windows-1251 ecoding and change to UTF-8
         array_walk($contact, function (&$item) {
             $encoding = mb_detect_encoding($item, array('UTF-8', 'Windows-1251', 'KOI8-R'));
             // if(mb_check_encoding($item, 'CP1251')){
             //     $item = iconv('CP1251', 'UTF-8', $item);
             // }
             if ($encoding !== 'UTF-8') {
                 $item = iconv('CP1251', 'UTF-8', $item);
             }
             $item = \VisoftBaseModule\Service\ForceUTF8\Encoding::toUTF8($item);
             // if(mb_check_encoding($item, 'CP1251')){
             //     $item = iconv('CP1251', 'UTF-8', $item);
             // }
         });
         // rewrite current element to new one
         $contactsArray[$key] = $contact;
     }
     // remove column header
     array_shift($contactsArray);
     // debug array
     // var_dump($contactsArray);
     // die('11122');
     // save contacts to database
     $this->contactService->enter($database, $contactsArray);
 }
 public function processAction()
 {
     $userEmail = $this->getAuthService()->getStorage()->read();
     if (!$userEmail) {
         $this->flashMessenger()->addErrorMessage("not authorized");
         return $this->redirect()->toRoute('media', array('action' => 'index'));
     }
     $request = $this->getRequest();
     $form = new UploadForm();
     $uploadFile = $this->params()->fromFiles('fileupload');
     $form->setData($request->getPost());
     if ($form->isValid()) {
         // Получение конфигурации из конфигурационных данных модуля
         $uploadPath = $this->getFileUploadLocation();
         // Сохранение выгруженного файла
         $adapter = new \Zend\File\Transfer\Adapter\Http();
         $adapter->setDestination($uploadPath);
         if ($adapter->receive($uploadFile['name'])) {
             $userTable = $this->getServiceLocator()->get('UserTable');
             $user = $userTable->getUserByEmail($userEmail);
             //                // Успешная выгрузка файла
             $exchange_data = array();
             $exchange_data['label'] = $request->getPost()->get('label');
             $exchange_data['filename'] = $uploadFile['name'];
             $exchange_data['user_id'] = $user->getId();
             $imageUpload = new \Users\Model\ImageUpload();
             $thumbnailFileName = $this->generateThumbnail($uploadFile['name']);
             $thumbnail_data = $exchange_data;
             $thumbnail_data['thumbnail'] = $thumbnailFileName;
             $imageUpload->exchangeArray($thumbnail_data);
             $imageUploadTable = $this->getServiceLocator()->get('ImageUploadTable');
             $imageUploadTable->save($imageUpload);
         }
     }
     return $this->redirect()->toRoute('media', array('action' => 'index'));
 }