public function applyAction() { $form = new ApplicationForm(); $form->get('submit')->setValue('Apply Now!'); $request = $this->getRequest(); if ($request->isPost()) { $application = new Application(); $form->setInputFilter($application->getInputFilter()); $post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray()); $form->setData($post); if ($form->isValid()) { $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()); $application->exchangeArray($data); $size = new Size(['min' => 20, 'max' => 200000]); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators([$size], $application->getProfilePic()); $adapter->setValidators([$size], $application->getBasePic()); if (!$adapter->isValid()) { $errors = $adapter->getMessages(); return ['form' => $form, 'errors' => $errors]; } $path = '/applications/' . $application->getTag() . '/'; $prefix = getcwd() . '/public'; if (!file_exists($prefix . '/applications/')) { mkdir($prefix . '/applications/'); } if (!file_exists($prefix . $path)) { mkdir($prefix . $path); } $basePic = $application->getBasePic(); $ending = pathinfo($basePic['name'], PATHINFO_EXTENSION); $application->setBasePic($path . 'basepic.' . $ending); $basePicFile = file_get_contents($basePic['tmp_name']); file_put_contents($prefix . $application->getBasePic(), $basePicFile); $profilePic = $application->getProfilePic(); $ending = pathinfo($profilePic['name'], PATHINFO_EXTENSION); $application->setProfilePic($path . 'profilepic.' . $ending); $profilePicFile = file_get_contents($profilePic['tmp_name']); file_put_contents($prefix . $application->getProfilePic(), $profilePicFile); try { $this->getApplicationTable()->saveApplication($application); } catch (\Exception $e) { return $this->redirect()->toRoute('applynow', ['action' => 'applyfailed']); } $id = $this->getApplicationTable()->getLastInsertedId(); return $this->redirect()->toRoute('applynow', ['action' => 'applysuccess', 'id' => $id]); } else { $errors = $form->getMessages(); return ['form' => $form, 'errors' => $errors]; } } return ['form' => $form]; }
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())); } }
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)); }
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)); }
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' => ''); } } } }
/** * 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; }
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 }
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)); }
public function processjqueryAction() { $form = new \Users\Form\UploadJqueryForm(); // $form->setInputFilter(new \Users\Form\Filter\UploadJqueryFilter()); $request = $this->getRequest(); $response = $this->getResponse(); $jsonModel = new \Zend\View\Model\JsonModel(); try { if ($request->isPost()) { $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()); // throw new \Exception(json_encode("data " . serialize($data))); $form->setData($data); if ($form->isValid()) { $datas = []; $datas['files'] = []; $uploadPath = $this->getFileUploadLocation(); // $uploadFiles = $this->params()->fromFiles('files'); // throw new \Exception(json_encode("FILES " . serialize($_FILES))); // Сохранение выгруженного файла $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setDestination($uploadPath); $adapter->setValidators(array(new \Zend\Validator\File\Extension(array('extension' => array('jpg', 'jpeg', 'png', 'rtf'))))); // $adapter->setFilters(array( // new \Zend\Filter\File\RenameUpload(array( // 'target' => $uploadPath . '../tmpuploads/tmp', // 'randomize' => true, // ) // ) // )); if (!$adapter->isValid()) { throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages()))); } $files = $adapter->getFileInfo(); // throw new \Exception(json_encode($files)); foreach ($files as $file => $info) { // throw new \Exception(json_encode($info)); $name = $adapter->getFileName($file); // file uploaded & is valid if (!$adapter->isUploaded($file)) { throw new \Exception(json_encode("!isUploaded") . implode(" ", $adapter->getMessages())); continue; } if (!$adapter->isValid($file)) { throw new \Exception(json_encode("!isValid " . implode(" ", $adapter->getMessages()))); continue; } // receive the files into the user directory $check = $adapter->receive($file); // this has to be on top if (!$check) { throw new \Exception(json_encode("! receive" . implode(" ", $adapter->getMessages()))); } /** * "name": "picture1.jpg", "size": 902604, "url": "http:\/\/example.org\/files\/picture1.jpg", "thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/picture1.jpg", "deleteUrl": "http:\/\/example.org\/files\/picture1.jpg", "deleteType": "DELETE" */ $fileclass = new stdClass(); // we stripped out the image thumbnail for our purpose, primarily for security reasons // you could add it back in here. $fileclass->name = $name; $fileclass->size = $adapter->getFileSize($name); $fileclass->type = $adapter->getMimeType($name); $fileclass->deleteUrl = '/uploads/delete'; $fileclass->deleteType = 'DELETE'; //$fileclass->error = 'null'; $fileclass->url = '/'; $datas['files'][] = $fileclass; } $response->getHeaders()->addHeaders(array('Pragma' => 'no-cache', 'Cache-Control' => 'private, no-cache', "Content-Type" => 'application/json')); // return $response->setContent(json_encode(array('files' => $files))); return $response->setContent(json_encode($datas)); } else { throw new \Exception(json_encode("!isValid form" . serialize($form->getMessages()))); } } } catch (\Exception $e) { return $response->setContent(json_encode($e->getMessage())); } return $jsonModel; // if ($request->isPost()) { // // Получение конфигурации из конфигурационных данных модуля // $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); // // $upload = new \Users\Model\Upload(); // // // Успешная выгрузка файла // $exchange_data = array(); // $exchange_data['label'] = $request->getPost()->get('label'); // $exchange_data['filename'] = $uploadFile['name']; // $exchange_data['user_id'] = $user->getId(); // $upload->exchangeArray($exchange_data); // // $uploadTable = $this->getServiceLocator()->get('UploadTable'); // $uploadTable->save($upload); // $upload->setId($uploadTable->getLastInsertValue()); // // //добавить в Lucene // $searchIndexLocation = $this->getIndexLocation(); // $index = Lucene\Lucene::create($searchIndexLocation); // // // создание полей lucene // $fileUploadId = Document\Field::unIndexed( // 'upload_id', $upload->getId()); // $label = Document\Field::Text('label', $upload->getLabel()); // $owner = Document\Field::Text('owner', $user->getName()); // // $uploadPath = $this->getFileUploadLocation(); // $fileName = $upload->getFilename(); // $filePath = $uploadPath . DIRECTORY_SEPARATOR . $fileName; // // if (substr_compare($fileName, ".xlsx", strlen($fileName) - // strlen(".xlsx"), strlen(".xlsx")) === 0) { // // Индексирование таблицы excel // $indexDoc = Lucene\Document\Xlsx::loadXlsxFile($filePath); // } else if (substr_compare($fileName, ".docx", strlen($fileName) - // strlen(".docx"), strlen(".docx")) === 0) { // // Индексирование документа Word // $indexDoc = Lucene\Document\Docx::loadDocxFile($filePath); // } else { // $indexDoc = new Lucene\Document(); // } // // // создание нового документа и добавление всех полей // $indexDoc = new Lucene\Document(); // $indexDoc->addField($label); // $indexDoc->addField($owner); // $indexDoc->addField($fileUploadId); // $index->addDocument($indexDoc); // // $index->commit(); // } // } // return $response->setContent(""); }
public function editAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('admin/certifications', array('action' => 'add')); } $certification = $this->getUserCertificationsTable()->getCertification($id); if ($certification == false) { $this->flashMessenger()->addErrorMessage('Certification not found..!!'); return $this->redirect()->toRoute('admin/certifications'); } $form = new UserCertificationForm($this->getServiceLocator()->get('Admin\\Model\\UsersTable'), $this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_logo = $certification->logo; $form->bind($certification); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('logo'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('logo' => $File['name'])); $form->setInputFilter($certification->getInputFilter()); $form->setData($post); if ($form->isValid()) { $formData = $form->getData(); $size = new Size(array('min' => 200, 'max' => 2000000)); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); if (!$dataError['fileUploadErrorNoFile']) { $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $form->setMessages(array('logo' => $error)); return array('id' => $id, 'form' => $form); } } else { if (isset($old_logo) && !empty($old_logo)) { $AllImages = array(); $S3 = new ImageS3(); $S3Path = "https://ovessence.s3.amazonaws.com/Logo/Original/"; $AllImages[] = str_replace($S3Path, 'Logo/Small/', $old_logo); $AllImages[] = str_replace($S3Path, 'Logo/Medium/', $old_logo); $AllImages[] = str_replace($S3Path, 'Logo/Large/', $old_logo); $AllImages[] = str_replace($S3Path, 'Logo/Original/', $old_logo); if (count($AllImages) > 0) { foreach ($AllImages as $image) { $S3->deleteFile($image); } } } $S3 = new ImageS3(); $data = $S3->uploadFiles($_FILES['logo'], "Logo", array('Small' => 25, 'Medium' => 50, 'Large' => 75, 'Original' => 100)); if (is_array($data) && count($data) > 0) { $formData->logo = $data['Original']; } } $this->getUserCertificationsTable()->saveCertification($form->getData()); $this->flashMessenger()->addSuccessMessage('User certification updated successfully..!!'); // Redirect to list of consumers return $this->redirect()->toRoute('admin/certifications'); } } return array('id' => $id, 'form' => $form); }
/** * 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(); } } }
/** * * @return Ambigous <\Zend\View\Model\ViewModel, \Zend\View\Model\ViewModel> */ public function uploadcreativeAction() { $initialized = $this->initialize(); if ($initialized !== true) { return $initialized; } $creatives_dir = 'public/creatives/' . $this->auth->getUserID() . '/'; if (!file_exists($creatives_dir)) { mkdir($creatives_dir, 0755, true); } $site_url = $this->config_handle['delivery']['site_url']; if (substr($site_url, -1) == '/') { $site_url = substr($site_url, 0, -1); } $files = $this->request->getFiles()->toArray(); $httpadapter = new \Zend\File\Transfer\Adapter\Http(); $filesize = new \Zend\Validator\File\Size(array('max' => 2000000)); //2MB $extension = new \Zend\Validator\File\Extension(array('extension' => array('jpg', 'jpeg', 'png', 'gif', 'swf'))); $httpadapter->setValidators(array($filesize, $extension), $files['file']['name']); $ext = pathinfo($files['file']['name'], PATHINFO_EXTENSION); $newName = md5(rand() . $files['file']['name']) . '.' . $ext; $httpadapter->addFilter('File\\Rename', array('target' => $creatives_dir . $newName, 'overwrite' => true)); if ($httpadapter->isValid()) { if ($httpadapter->receive($files['file']['name'])) { $httpadapter->getFilter('File\\Rename')->getFile(); $newfile = $httpadapter->getFileName(); header("Content-type: text/plain"); echo $site_url . substr($newfile, strlen('public')); exit; } } $error = array(); $dataError = $httpadapter->getMessages(); foreach ($dataError as $key => $row) { $error[] = $row; } http_response_code(400); header("Content-type: text/plain"); echo implode(',', $error); exit; }
public function editAction() { $booking_id = (int) $this->params()->fromRoute('booking_id', 0); $id = (int) $this->params()->fromRoute('id', 0); if (!$id && !$booking_id) { return $this->redirect()->toRoute('admin/bannerbookings'); } $bu = $this->getBannerUploadTable()->getBannerUpload($id); $bannerDetails = $this->getServiceLocator()->get('Admin\\Model\\AdvertisementPlanTable')->getBannerDetails($booking_id); $form = new BannerUploadForm($this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_image = $bu->banner_content; $form->bind($bu); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('banner_content'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('banner_content' => $File['name'])); $form->setInputFilter($bu->getInputFilter()); $form->setData($post); if ($form->isValid()) { $S3 = new ImageS3(); $formData = $form->getData(); if ($post['banner_type'] == '1') { if ($File['name'] != "") { $validator = new IsImage(); if ($validator->isValid($File['tmp_name'])) { /* Image uploading code starts */ $size = new Size(array('min' => 200, 'max' => 20000000)); $imageSize = new ImageSize(array('minWidth' => $bannerDetails->banner_width, 'minHeight' => $bannerDetails->banner_height, 'maxWidth' => $bannerDetails->banner_width + 10, 'maxHeight' => $bannerDetails->banner_height + 10)); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size, $imageSize), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); return array('form' => $form, 'file_errors' => $dataError, 'booking_id' => $booking_id, 'details' => $bannerDetails); } else { $data = $S3->uploadFiles($_FILES['banner_content'], "Banners", array()); if (is_array($data) && count($data) > 0) { $formData->banner_content = $data['Original']; // deleting old image $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', $old_image)); } } /* Image uploading code ends */ } else { return array('form' => $form, 'file_errors' => $validator->getMessages(), 'booking_id' => $booking_id, 'details' => $bannerDetails); } } else { $formData->banner_content = $old_image; } } else { if ($post['banner_type'] == '2') { } else { // deleting old image $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', $old_image)); $formData->banner_content = $request->getPost('banner_content'); } } $this->getBannerUploadTable()->saveBannerUpload($form->getData()); $this->flashMessenger()->addSuccessMessage('Banner updated successfully..!!'); // Redirect to list of banners return $this->redirect()->toRoute('admin/banneruploads', array('booking_id' => $booking_id)); } } return array('id' => $id, 'bannerUpload' => $bu, 'errors' => $this->errors, 'booking_id' => $booking_id, 'form' => $form, 'details' => $bannerDetails); }
/** * Valida se o arquivo é um arquivo válido para upload. * * @param array $fileArgs * @return boolean * @throws Exception */ private function validateFile(array $fileArgs) { $size = new \Zend\Validator\File\Size(array('max' => 2000000, 'min' => 2000)); $return = true; $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size), $fileArgs['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $errors = ""; foreach ($dataError as $key => $row) { $errors .= $row . "<br>"; } $return = false; throw new \Exception($errors); } return $return; }
public function editAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('admin/partners', array('action' => 'add')); } $partner = $this->getPartnersTable()->getPartner($id); if ($partner == false) { $this->flashMessenger()->addErrorMessage('Partner not found..!!'); return $this->redirect()->toRoute('admin/partners'); } $form = new PartnersForm($this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_logo = $partner->logo; $form->bind($partner); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('logo'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('logo' => $File['name'])); $form->setInputFilter($partner->getInputFilter()); $form->setData($post); if ($form->isValid()) { $formData = $form->getData(); $size = new Size(array('min' => 200, 'max' => 2000000)); $imageSize = new ImageSize(array('minWidth' => '205', 'minHeight' => '235', 'maxWidth' => '1000', 'maxHeight' => '1000')); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size, $imageSize), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); if (!$dataError['fileUploadErrorNoFile']) { $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $form->setMessages(array('logo' => $error)); return array('id' => $id, 'form' => $form); } } else { if (isset($old_logo) && !empty($old_logo)) { $S3 = new ImageS3(); $S3->deleteFile($old_logo); } $S3 = new ImageS3(); $adapter->setDestination('./public/uploads'); if ($adapter->receive($File['name'])) { $fileName = "./public/uploads/" . $File['name']; $data = $S3->uploadFile($fileName, array('PartnersLogo' => '205x235\\!')); } if (is_array($data) && count($data) > 0) { $formData->logo = $data['PartnersLogo']; } } $this->getPartnersTable()->savePartner($form->getData()); $this->flashMessenger()->addSuccessMessage('Partner updated successfully..!!'); // Redirect to list of consumers return $this->redirect()->toRoute('admin/partners'); } } return array('id' => $id, 'form' => $form); }
public function editAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('admin/media'); } $media = $this->getMediaTable()->getMedia($id); if ($media == false) { $this->flashMessenger()->addErrorMessage('Media not found..!!'); return $this->redirect()->toRoute('admin/media'); } $form = new MediaForm($this->getServiceLocator()->get('Admin\\Model\\UsersTable'), $this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_media = $media->media_url; $form->bind($media); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('media_url'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('media_url' => $File['name'])); $form->setInputFilter($media->getInputFilter()); $form->setData($post); $adapter = new \Zend\File\Transfer\Adapter\Http(); if ($form->isValid()) { $S3 = new ImageS3(); $formData = $form->getData(); if ($post['media_type'] == '1') { if ($File['name'] != "") { $validator = new IsImage(); if ($validator->isValid($File['tmp_name'])) { /* Image uploading code starts */ $size = new Size(array('min' => 200, 'max' => 20000000)); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); return array('form' => $form, 'file_errors' => $dataError); } else { $data = $S3->uploadFiles($_FILES['media_url'], "Media", array(), array('Media' => 100, 'Media_thumb' => 20)); if (is_array($data) && count($data) > 0) { $formData->media_url = $data['Media']; // deleting old image $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', $old_image)); $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', str_replace('Media', 'Media_thumb', $old_image))); } } /* Image uploading code ends */ } else { return array('form' => $form, 'file_errors' => $validator->getMessages()); } } else { $formData->media_url = $old_media; } } else { if ($post['media_type'] == '2') { if ($File['name'] != "") { $renameUpload = new \Zend\Filter\File\RenameUpload(array('target' => "./public/uploads/", 'randomize' => true, 'use_upload_name' => true)); if ($fileDetails = $renameUpload->filter($_FILES['media_url'])) { $filePath = $fileDetails['tmp_name']; // check video orientation and rotate if needed /*exec("mediainfo " . $fileDetails['tmp_name'] . " | grep Rotation", $mediaInfo); if (is_array($mediaInfo) && count($mediaInfo) > 0) { $tempPath = explode("/", $fileDetails['tmp_name']); $filePath = "./public/uploads/new_" . end($tempPath); exec('ffmpeg -i ' . $fileDetails['tmp_name'] . ' -vf "transpose=1" -strict -2 ' . $filePath, $output, $response); ($response == '0') ? @unlink($fileDetails['tmp_name']) : ''; }*/ $session = new Container('vimeo'); $formData->media_url = $session->file = $filePath; $session->mode = 'write'; $session->returnUrl = $this->url()->fromRoute('admin/media'); $session->old_video = $old_media; $session->media_id = $this->getMediaTable()->saveMedia($form->getData()); if ($formData->status_id == 9) { return $this->redirect()->toRoute('admin/media', array('action' => 'vimeologin')); } } else { return array('form' => $form, 'file_errors' => $adaptor->getMessages()); } } else { $formData->media_url = $old_media; } } } $this->getMediaTable()->saveMedia($form->getData()); $this->flashMessenger()->addSuccessMessage('Media updated successfully..!!'); // Redirect to list of banners return $this->redirect()->toRoute('admin/media'); } } return array('id' => $id, 'media' => $media, 'errors' => $this->errors, 'form' => $form); }
public function ajaxUploadFileAction() { //load the form $form = $this->getFrontProfileFileManagerModel()->getFileUploadForm(); $request = $this->getRequest(); if ($request->isPost()) { //get file $files = $request->getFiles()->toArray(); $form->remove("tmp_file"); $form->remove("mode"); $form->remove("filename"); $arr_post_data = $request->getPost(); $arr_post_data["mode"] = "image"; $arr_post_data["additional_path"] = ""; $form->setData($arr_post_data); if ($form->isValid($request->getPost())) { //extract form data $arr_data = $form->getData(); //clear file name, it is derived from the uploaded data $arr_data["filename"] = ""; if ($files) { $httpadapter = new \Zend\File\Transfer\Adapter\Http(); $filesize = new \Zend\Validator\File\Size(array('min' => 1, 'max' => 1000000)); $extension = new \Zend\Validator\File\Extension(array('extension' => array('jpg', 'png', 'gif', 'jpeg', 'pdf', 'csv', 'xls', 'xlsx', 'csv', 'docx', 'txt', 'js', 'css', 'html'), "options" => array("messages" => array(\Zend\Validator\File\Extension::FALSE_EXTENSION => "File is not valid", \Zend\Validator\File\Extension::NOT_FOUND => "File could not be found")))); $httpadapter->setValidators(array($filesize, $extension), $files['file']['name']); if ($httpadapter->isValid()) { //set uploads path $uploads_path = "./data/tmp/uploads"; if (!is_dir($uploads_path)) { mkdir($uploads_path, 0755, TRUE); } //end if $httpadapter->setDestination($uploads_path); if ($httpadapter->receive($files['file']['name'])) { $newfile = $httpadapter->getFileName(); //set form data $arr_t = explode("/", $newfile); if (!isset($arr_data["filename"]) || $arr_data["filename"] == "") { $f = array_pop($arr_t); $f = preg_replace('/[^a-zA-Z0-9_.]/', '', $f); if ($f == "") { $f = time(); } //end if $arr_data["filename"] = $f; } //end if $arr_data["url"] = ""; $arr_data["data"] = base64_encode(file_get_contents($newfile)); //determine mode from file uploaded if (is_array(getimagesize($newfile))) { $arr_data["mode"] = "image"; } else { $arr_data["mode"] = "document"; } //end if //remove local file unlink($newfile); } //end if } else { //file validation failed echo json_encode(array("error" => 1, "response" => "File validation failed. File could not be uploaded: " . implode(",", $httpadapter->getMessages())), JSON_FORCE_OBJECT); exit; } //end if } //end if try { $this->getFrontProfileFileManagerModel()->uploadFile($arr_data["mode"], $arr_data); //set message echo json_encode(array("error" => 0, "response" => "File uploaded"), JSON_FORCE_OBJECT); exit; } catch (\Exception $e) { $arr_t = explode("||", $e->getMessage()); $obj = json_decode(array_pop($arr_t)); $arr_t = explode(":", $obj->HTTP_RESPONSE_MESSAGE); echo json_encode(array("error" => 1, "response" => array_pop($arr_t)), JSON_FORCE_OBJECT); exit; } //end catch } else { //form validation failed $r = "Form validation failed"; echo json_encode(array("error" => 1, "response" => $r), JSON_FORCE_OBJECT); exit; } //end if } //end if echo json_encode(array("error" => 1, "response" => "AJAX request needs to be POST"), JSON_FORCE_OBJECT); exit; exit; }
/** * This function returns a form for editing an Contact * @return type */ public function editAction() { $this->checkIdentity($this->id); //Get the artist id from the route $contact_id = (int) $this->params()->fromRoute('id'); $File = $this->params()->fromFiles('photo'); //Go to the artist table and Get the current artist $contact = $this->getContactTable()->getContact($contact_id); //create an instance of the form $form = new \Ekontact\Form\EditContactForm(); //Attach the artist model to the form $form->bind($contact); //Get the request $request = $this->getRequest(); //Check if the request is posted if ($request->isPost()) { $old_info = $contact->getArrayCopy(); $data = $request->getPost()->toArray(); unset($data['submit']); try { if (!$File['name'] == null) { $extension = explode(".", $File['name']); //combine the menu name with the extension $image_name = $data['first_name'] . $data['last_name'] . date('ymd') . "." . $extension[1]; $databasepath = "/eKontact/public/uploads"; // $databasepath = dirname(dirname(dirname(dirname(dirname(__DIR__)))))."/public/uploads"; //file path for the directory $filepath = dirname(dirname(dirname(dirname(dirname(__DIR__))))) . '/public/uploads'; //path to the images folder to be saved in the database //$dbfilepath = 'Ekontact/module/Ekontact/src/Ekontact/uploads'; //file path for the directory //$filepath = dirname(__DIR__) . '/uploads'; //make the directory for storing the images with full permission on the directory mkdir($databasepath, 0777); unlink($databasepath . "/" . $image_name); //create an instance of the size class and specify the minimum file size $size = new Size(array('min' => 2000, 'max' => 2000000)); //get an instance of the file transfer adapter http $adapter = new \Zend\File\Transfer\Adapter\Http(); //set validators for the file size $adapter->setValidators(array($size), $File['name']); //check if the size is valid if (!$adapter->isValid()) { //throw errors if the size is not valid $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } $form->setMessages(array('photo' => $error)); } else { /** If the file is uploaded to the directory change the name of the file to the artist name + extension */ $adapter->setDestination($filepath); // If the file is uploaded to the directory change the name of the file to the merchant short name + extension if (move_uploaded_file($_FILES['photo']['tmp_name'], $filepath . "/" . $image_name)) { $array = array_merge($data, array('photo' => $databasepath . "/" . $image_name)); // \Zend\Debug\Debug::dump($array);die(); $this->getContactTable()->updateContact($array, $contact_id); $this->ContactLogger("user updated 1 record from " . json_encode($old_info) . " to " . json_encode($array)); $this->flashMessenger()->addMessage(sprintf(" %s contact Updated Successfully %s", '<div class="alert alert-success">', '</div>')); return $this->redirect()->toRoute('contacts', array('action' => 'index')); } } } } catch (Excetion $e) { return false; } //If the form is not valid display the form again return array('id' => $contact_id, 'form' => $form); } //If the request is not posted display the artist form again return new ViewModel(array('id' => $contact_id, 'form' => $form)); }
public function addAction() { $form = new FileForm(); $request = $this->getRequest(); if ($request->isPost()) { $file = new File(); // On vérifie la validité des champs $form->setInputFilter($file->getInputFilter()); $nonFile = $request->getPost()->toArray(); $params = $this->params()->fromFiles('link'); // On récupère l'extension du fichier $ext = new \Zend\File\PhpClassFile($params['name']); $ext = $ext->getExtension(); // recherche de la catégorie $musique = array('mp3', 'flac', 'aac', 'wav'); $video = array('mp4', 'avi', 'wmv', 'mov'); $document = array('pdf', 'txt', 'ppt', 'pptx', 'xls', 'xlsx', 'doc', 'docx'); $image = array('jpg', 'jpeg', 'gif', 'png'); $cat = ''; if (in_array($ext, $musique)) { $cat = 'musique'; } else { if (in_array($ext, $video)) { $cat = 'video'; } else { if (in_array($ext, $document)) { $cat = 'document'; } else { if (in_array($ext, $image)) { $cat = 'image'; } } } } $date = date('Y-m-d H:i:s'); if ($params['size'] < 100000) { $size = round($params['size'] / 1000, 2) . ' Ko'; } else { $size = round($params['size'] / 1000000, 2) . ' Mo'; } // renommage du fichier $newName = 'file' . time() . '.' . $ext; // if you're using ZF >= 2.1.1 $data = array_merge_recursive($this->getRequest()->getPost()->toArray(), array('link' => $newName, 'size' => $size, 'extension' => $ext, 'category' => $cat, 'uploaded' => $date, 'updated' => $date)); $form->setData($data); $adapter = new \Zend\File\Transfer\Adapter\Http(); // Liste d'extensions valides $listExt = array(); $types = array_merge_recursive($musique, $video, $document, $image); $extensionvalidator = new \Zend\Validator\File\Extension(array('extension' => $listExt)); $adapter->setValidators(array($extensionvalidator), $params['name']); // Taille maximum du fichier $maxSize = new Size(array('max' => 300000000)); //maximum bytes filesize $adapter->setValidators(array($maxSize), $params['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } //set formElementErrors $form->setMessages(array('link' => $error)); } else { if ($form->isValid()) { $adapter->addFilter('Rename', dirname(__DIR__) . '/upload/' . $newName); //$adapter->setDestination(dirname(__DIR__).'/upload'); if ($adapter->receive($params['name'])) { $file->exchangeArray($form->getData()); } $file->exchangeArray($form->getData()); $this->getFileTable()->saveFile($file); return $this->redirect()->toRoute('media'); } } } return new ViewModel(array('form' => $form)); }
/** * upload a ProfileImage * @param \Profile\Form\UploadForm $form * @param httpRequest $request * @param file $file file to upload * @return boolean */ public function upload($form, $request, $file) { $filter = new UploadFilter(); $form->setInputFilter($filter->getInputFilter()); $nonFile = $request->getPost()->toArray(); $data = array_merge($nonFile, array('fileupload' => $file['name'])); $form->setData($data); if ($form->isValid()) { $options = $this->getOptions(); $size = new Size(array('min' => '5kB', 'max' => '1.5MB')); $type = new Extension($options['profileImage']); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size, $type), $file['name']); if (!$adapter->isValid() || file_exists('public/images/profile_uploads/' . $file['name'])) { return false; } else { $adapter->setDestination('public/images/profile_uploads'); if ($adapter->receive($file['name'])) { $filter->exchangeArray($form->getData()); $user = $this->getUserById($this->getIdentity()->getUserId()); $entity = $this->getUserMapper()->findUserDataById($user->getUserid()); if ($entity == null) { $entity = new UserData(); $entity->setUser($user); } $entity->setPicture('/images/profile_uploads/' . $file['name']); $this->getUserMapper()->saveData($entity); return true; } } } }
public function editAction() { $id = (int) $this->params()->fromRoute('id', 0); if (!$id) { return $this->redirect()->toRoute('admin/sitebanner', array('action' => 'add')); } $banner = $this->getBannerTable()->getBanner($id); if ($banner == false) { $this->flashMessenger()->addErrorMessage('Banner not found..!!'); return $this->redirect()->toRoute('admin/sitebanner'); } $form = new SiteBannerForm($this->getServiceLocator()->get('Admin\\Model\\AdvertisementPageTable'), $this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_image = $banner->banner_url; $form->bind($banner); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('banner_url'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('banner_url' => $File['name'])); $old_image != '' ? $banner->getInputFilter()->get('banner_url')->setRequired(false) : ''; $form->setInputFilter($banner->getInputFilter()); $form->setData($post); if ($form->isValid()) { $S3 = new ImageS3(); $formData = $form->getData(); if ($File['name'] != "") { $validator = new IsImage(); if ($validator->isValid($File['tmp_name'])) { /* Image uploading code starts */ $size = new Size(array('min' => 200, 'max' => 20000000)); $adapter = new \Zend\File\Transfer\Adapter\Http(); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); return array('form' => $form, 'file_errors' => $dataError); } else { $data = $S3->uploadFiles($_FILES['banner_url'], "Banners", array()); if (is_array($data) && count($data) > 0) { $formData->banner_url = $data['Original']; // deleting old image $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', $old_image)); } } /* Image uploading code ends */ } else { return array('form' => $form, 'file_errors' => $validator->getMessages()); } } else { $formData->banner_url = $old_image; } $this->getBannerTable()->saveBanner($formData); $this->flashMessenger()->addSuccessMessage('Banner updated successfully..!!'); // Redirect to list of pages return $this->redirect()->toRoute('admin/sitebanner'); } else { $this->errors = $form->getMessages(); } } return array('id' => $id, 'form' => $form, 'errors' => $this->errors, 'siteBanner' => $banner); }
public function editAction() { $id = (int) $this->params()->fromRoute('id', 0); $user_id = (int) $this->params()->fromRoute('user_id', 0); $user = $this->getServiceLocator()->get('Admin\\Model\\UsersTable')->getUser($user_id); if ($user == false) { $this->flashMessenger()->addErrorMessage('User not found..!!'); return $this->redirect()->toRoute('admin/users'); } if (!$id) { return $this->redirect()->toRoute('admin/usersmedia', array('user_id' => $user_id)); } $usersMedia = $this->getUserMediaTable()->getMedia($id); if ($usersMedia == false) { $this->flashMessenger()->addErrorMessage('User media not found..!!'); return $this->redirect()->toRoute('admin/usersmedia', array('user_id' => $user_id)); } $form = new UsersMediaForm($this->getServiceLocator()->get('Admin\\Model\\StatusTable')); $old_image = $usersMedia->media_url; $form->bind($usersMedia); $form->get('submit')->setAttribute('value', 'Edit'); $request = $this->getRequest(); if ($request->isPost()) { $File = $this->params()->fromFiles('media_url'); // Make certain to merge the files info! $post = array_merge_recursive($request->getPost()->toArray(), array('media_url' => $File['name'])); $form->setInputFilter($usersMedia->getInputFilter()); $form->setData($post); $adapter = new \Zend\File\Transfer\Adapter\Http(); if ($form->isValid()) { $S3 = new ImageS3(); $formData = $form->getData(); if ($File['name'] != "") { $validator = new IsImage(); if ($validator->isValid($File['tmp_name'])) { /* Image uploading code starts */ $size = new Size(array('min' => 200, 'max' => 20000000)); $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); return array('form' => $form, 'file_errors' => $dataError, 'user_id' => $user_id); } else { $data = $S3->uploadFiles($_FILES['media_url'], "Media", array(), array('Media' => 100, 'Media_thumb' => 20)); if (is_array($data) && count($data) > 0) { $formData->media_url = $data['Media']; // deleting old image $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', $old_image)); $S3->deleteFile(str_replace('https://ovessence.s3.amazonaws.com/', '', str_replace('Media', 'Media_thumb', $old_image))); } } /* Image uploading code ends */ } else { return array('form' => $form, 'file_errors' => $validator->getMessages(), 'user_id' => $user_id); } } else { $formData->media_url = $old_image; } $this->getUserMediaTable()->saveUserMedia($form->getData()); $this->flashMessenger()->addSuccessMessage('User media updated successfully..!!'); // Redirect to list of media return $this->redirect()->toRoute('admin/usersmedia', array('user_id' => $user_id)); } } return array('id' => $id, 'usermedia' => $usersMedia, 'user_id' => $user_id, 'errors' => $this->errors, 'form' => $form); }
public function editLessonAction() { $auth = new AuthenticationService(); $user = $auth->getIdentity(); $lessonId = $this->params()->fromRoute('id'); $lesson = $this->getLessonTable()->getLesson($lessonId); $lessonFiles = $this->getLessonFilesTable()->getLessonFilesByLessonId($lessonId); $subsubject = $this->getSubsubjectTable()->getSubsubject($lesson->subsubject_id); $form = new LessonForm(); $form->bind($lesson); $form->get('submit')->setAttribute('value', 'Muuda'); $form->get('id')->setValue($lessonId); $form->get('user_id')->setValue($user->id); $form->get('subsubject_id')->setValue($subsubject->id); $form->get('type')->setValueOptions(array('text' => array('value' => 'text', 'label' => 'Tekst', 'selected' => $lesson->type == 'text' ? true : false), 'video' => array('value' => 'video', 'label' => 'Video', 'selected' => $lesson->type == 'video' ? true : false), 'presentation' => array('value' => 'presentation', 'label' => 'Esitlus', 'selected' => $lesson->type == 'presentation' ? true : false), 'audio' => array('value' => 'audio', 'label' => 'Audio', 'selected' => $lesson->type == 'audio' ? true : false), 'images' => array('value' => 'images', 'label' => 'Pildid', 'selected' => $lesson->type == 'images' ? true : false))); if ($lesson->type == 'video') { $form->get('url')->setValue($lessonFiles->current()->url); } $request = $this->getRequest(); if ($request->isPost()) { $form->setInputFilter(new LessonFilter($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(); $files = $adapter->getFileInfo(); $filesUrls = array(); $error = array(); if ($post['type'] == 'images' || $post['type'] == 'audio' || $post['type'] == 'presentation') { foreach ($files as $key => $file) { if ($post['type'] == 'images') { $extension = new \Zend\Validator\File\Extension(array('extension' => array('jpg', 'jpeg', 'png'))); } else { if ($post['type'] == 'audio') { $extension = new \Zend\Validator\File\Extension(array('extension' => array('mp3', 'wav'))); $size = new \Zend\Validator\File\Size(array(array('max' => 104857600))); $adapter->setValidators(array($size), $file['name']); } else { if ($post['type'] == 'presentation') { $extension = new \Zend\Validator\File\Extension(array('extension' => array('pdf'))); } else { $extension = new \Zend\Validator\File\Extension(array('extension' => array())); } } } $adapter->setValidators(array($extension), $file['name']); } if (!$adapter->isValid()) { foreach ($adapter->getMessages() as $key => $row) { $error[] = $row; } $form->setMessages(array('fileupload' => $error)); } else { $adapter->setDestination($this->getServiceLocator()->get('Config')['upload_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(); if (is_array($adapterFileName)) { foreach ($adapterFileName as $name) { $fileName = preg_replace('/\\.\\/public\\/uploads/', '', $name); $filesUrls[] = $baseUrl . '/uploads/' . substr($fileName, 1); } } else { $fileName = preg_replace('/\\.\\/public\\/uploads/', '', $adapterFileName); $filesUrls[] = $baseUrl . '/uploads/' . substr($fileName, 1); } } } } else { if ($post['type'] == 'video') { $filesUrls[] = $post['url']; } else { if ($post['type'] == 'text') { $lesson->exchangeArray($post); $this->getLessonTable()->saveLesson($lesson); $this->getLessonFilesTable()->deleteLessonFilesByLessonId($lessonId); return $this->redirect()->toRoute('teacher/my-course'); } } } if (empty($error)) { if ($lesson->type != $post['type'] || $post['type'] == 'presentation' || $post['type'] == 'audio') { $this->getLessonFilesTable()->deleteLessonFilesByLessonId($lessonId); } $lesson->exchangeArray($post); $this->getLessonTable()->saveLesson($lesson); $post['lesson_id'] = $post['id']; $post['id'] = 0; foreach ($filesUrls as $fileUrl) { $lessonFiles = new LessonFiles(); $post['url'] = $fileUrl; $lessonFiles->exchangeArray($post); $this->getLessonFilesTable()->saveLessonFiles($lessonFiles); } return $this->redirect()->toRoute('teacher/my-course'); } } } return array('id' => $lessonId, 'form' => $form, 'lessonFiles' => $lessonFiles, 'lessonType' => $lesson->type); }
/** * @param $file */ static function uploadFile($file) { $adapter = new \Zend\File\Transfer\Adapter\Http(); $size = new Size(array('max' => 2000000)); //minimum bytes filesize $adapter->setValidators(array($size), $file['avatar']['name']); $data = array(); if ($adapter->isValid()) { $adapter->setDestination($_SERVER['DOCUMENT_ROOT'] . '/img/upload'); if ($adapter->receive($file['avatar']['name'])) { $data['avatar'] = 'http://' . $_SERVER['HTTP_HOST'] . '/img/upload/' . $file['avatar']['name']; $data['status'] = true; $data['error'] = null; } } else { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } //set formElementErrors $data['avatar'] = ''; $data['status'] = false; $data['error'] = $error; } return $data; }
/** * 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; }
public function addAction() { //echo getcwd()."/public/_gallery"; //echo $this->getEvent()->getRouteMatch()->getParam('type'); if ($this->getEvent()->getRouteMatch()->getParam('type') == "gallery") { $form = new GalleryForm(); $form->add(array('name' => 'id_section', 'attributes' => array('type' => 'hidden', 'value' => $this->getEvent()->getRouteMatch()->getParam('id')))); } elseif ($this->getEvent()->getRouteMatch()->getParam('type') == "item") { $form = new ItemForm(); $form->add(array('name' => 'id_gallery', 'attributes' => array('type' => 'hidden', 'value' => $this->getEvent()->getRouteMatch()->getParam('id')))); //echo $this->getEvent()->getRouteMatch()->getParam('id'); } else { $form = new SectionForm(); } //return array('form' => $form); $viewModel = new ViewModel(); $viewModel->setVariables(array('form' => $form)); $request = $this->getRequest(); if ($request->isPost()) { //echo $form->getName(); if ($form->getName() == "Item") { /******/ $nonFile = $request->getPost()->toArray(); $File = $this->params()->fromFiles('fileupload'); $data = array_merge($nonFile, array('fileupload' => $File['name'])); //set data post and file ... $form->setData($data); $size = new Size(array('max' => 2000000)); $adapter = new \Zend\File\Transfer\Adapter\Http(); //validator can be more than one... $adapter->setValidators(array($size), $File['name']); if (!$adapter->isValid()) { $dataError = $adapter->getMessages(); $error = array(); foreach ($dataError as $key => $row) { $error[] = $row; } //set formElementErrors $form->setMessages(array('fileupload' => $error)); } else { $g = $this->getEntityManager()->getRepository('Backend\\Entity\\Gallery')->findOneBy(array('id' => $this->getEvent()->getRouteMatch()->getParam('id'))); echo getcwd() . $g->getPath() . " * " . getcwd() . $g->getPath() . "/thumbs" . "<br/>"; $adapter->setDestination(getcwd() . $g->getPath()); @chmod(getcwd() . $g->getPath() . $File['name'], 0777); /*if (!copy(getcwd() . $g->getPath()."/".$File['name'], getcwd() . $g->getPath()."/thumbs"."/".$File['name'])) { echo "Error al copiar ".getcwd() . $g->getPath()."/".$File['name']."...\n"; }*/ $path = substr($g->getPath(), 7) . "/" . $File['name']; $path_thumb = substr($g->getPath(), 7) . "/thumbs/" . $File['name']; $i = new Item(); $i->setDescripcion($request->getPost("description")); $i->setComment($request->getPost("comentario")); $i->setId_gallery($this->getEvent()->getRouteMatch()->getParam('id')); $i->setPath($path); $i->setPath_thumb($path_thumb); $i->setDeleted(0); $i->setVisible(1); $this->getEntityManager()->persist($i); $this->getEntityManager()->flush(); echo "<pre>"; //echo $this->getEvent()->getRouteMatch()->getParam('type'); //echo $this->getEvent()->getRouteMatch()->getParam('id'); echo $File['name']; var_dump($request->getPost("description")); var_dump($request->getPost("comentario")); echo "</pre>"; if ($adapter->receive($File['name'])) { // $profile->exchangeArray($form->getData()); // echo 'Profile Name '.$profile->profilename.' upload '.$profile->fileupload; } $this->createThumbs(getcwd() . $g->getPath(), getcwd() . $g->getPath() . "/thumbs", 100); } /******/ } elseif ($form->getName() == "Gallery") { //echo $File['name']; $gal = $this->getEntityManager()->getRepository('Backend\\Entity\\Gallery')->findOneBy(array('slug' => $request->getPost("slug"), 'id_section' => $this->getEvent()->getRouteMatch()->getParam('id'))); //var_dump($gal); if (!empty($gal)) { echo "<pre>"; print "Identificador repetido"; echo "</pre>"; } else { $s = $this->getEntityManager()->getRepository('Backend\\Entity\\Section')->findOneBy(array('id' => $this->getEvent()->getRouteMatch()->getParam('id'))); //echo $s->getUrl(); $new_url = $s->getUrl() . "/" . $request->getPost("slug"); $new_path = $s->getPath() . "/" . $request->getPost("slug"); //echo getcwd()."$new_path"; $g = new Gallery(); $g->setDescripcion($request->getPost("description")); $g->setComment($request->getPost("comentario")); $g->setSlug($request->getPost("slug")); $g->setId_section($this->getEvent()->getRouteMatch()->getParam('id')); $g->setPath($new_path); $g->setUrl($new_url); $g->setDeleted(0); $g->setVisible(1); $this->getEntityManager()->persist($g); $this->getEntityManager()->flush(); mkdir(getcwd() . "{$new_path}", 0777, true); mkdir(getcwd() . "{$new_path}" . "/thumbs", 0777, true); echo "<pre>"; print 'Se creo nueva galeria "' . $request->getPost("description") . '" en la seccion "' . $s->getDescripcion() . '"'; echo "</pre>"; /*echo "<pre>"; var_dump ($this->getEvent()->getRouteMatch()->getParam('type')); var_dump ($this->getEvent()->getRouteMatch()->getParam('id')); // var_dump($request->getPost("description")); var_dump($request->getPost("slug")); var_dump($request->getPost("comentario")); echo "</pre>"; */ } } //good return $this->redirect()->toRoute('backend'); } //$viewModel->setTemplate ( "backend/index/index" ); return $viewModel; }