예제 #1
0
 /**
  * Use the Zend_File_Transfer adapter to upload the file.  
  * 
  * @internal The resulting filename is retrieved via the adapter's 
  * getFileName() method.
  * 
  * @param array $fileInfo
  * @param string $originalFilename
  * @return string Path to the file in Omeka.
  */
 protected function _transferFile($fileInfo, $originalFilename)
 {
     // Upload a single file at a time.
     if (!$this->_adapter->receive($fileInfo['form_index'])) {
         throw new Omeka_File_Ingest_InvalidException(join("\n\n", $this->_adapter->getMessages()));
     }
     // Return the path to the file as it is listed in Omeka.
     return $this->_adapter->getFileName($fileInfo['form_index']);
 }
예제 #2
0
 public function upload($params = array())
 {
     if (!is_dir($params['destination_folder'])) {
         mkdir($params['destination_folder'], 0777, true);
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($params['destination_folder']);
     $adapter->setValidators($params['validators']);
     if ($adapter->getValidator('ImageSize')) {
         $adapter->getValidator('ImageSize')->setMessages(array('fileImageSizeWidthTooBig' => $this->_('Image too large, %spx maximum allowed.', '%maxwidth%'), 'fileImageSizeWidthTooSmall' => $this->_('Image not large enough, %spx minimum allowed.', '%minwidth%'), 'fileImageSizeHeightTooBig' => $this->_('Image too high, %spx maximum allowed.', '%maxheight%'), 'fileImageSizeHeightTooSmall' => $this->_('Image not high enough, %spx minimum allowed.', '%minheight%'), 'fileImageSizeNotDetected' => $this->_("The image size '%s' could not be detected.", '%value%'), 'fileImageSizeNotReadable' => $this->_("The image '%s' does not exist", '%value%')));
     }
     if ($adapter->getValidator('Size')) {
         $adapter->getValidator('Size')->setMessages(array('fileSizeTooBig' => $this->_("Image too large, '%s' allowed.", '%max%'), 'fileSizeTooSmall' => $this->_("Image not large enough, '%s' allowed.", '%min%'), 'fileSizeNotFound' => $this->_("The image '%s' does not exist", '%value%')));
     }
     if ($adapter->getValidator('Extension')) {
         $adapter->getValidator('Extension')->setMessages(array('fileExtensionFalse' => $this->_("Extension not allowed, '%s' only", '%extension%'), 'fileExtensionNotFound' => $this->_("The file '%s' does not exist", '%value%')));
     }
     $files = $adapter->getFileInfo();
     $return_file = '';
     foreach ($files as $file => $info) {
         //Créé l'image sur le serveur
         if (!$adapter->isUploaded($file)) {
             throw new Exception($this->_('An error occurred during process. Please try again later.'));
         } else {
             if (!$adapter->isValid($file)) {
                 if (count($adapter->getMessages()) == 1) {
                     $erreur_message = $this->_('Error : <br/>');
                 } else {
                     $erreur_message = $this->_('Errors : <br/>');
                 }
                 foreach ($adapter->getMessages() as $message) {
                     $erreur_message .= '- ' . $message . '<br/>';
                 }
                 throw new Exception($erreur_message);
             } else {
                 $new_name = uniqid("file_");
                 if (isset($params['uniq']) and $params['uniq'] == 1) {
                     if (isset($params['desired_name'])) {
                         $new_name = $params['desired_name'];
                     } else {
                         $format = pathinfo($info["name"], PATHINFO_EXTENSION);
                         if (!in_array($format, array("png", "jpg", "jpeg", "gif"))) {
                             $format = "jpg";
                         }
                         $new_name = $params['uniq_prefix'] . uniqid() . ".{$format}";
                     }
                     $new_pathname = $params['destination_folder'] . '/' . $new_name;
                     $adapter->addFilter(new Zend_Filter_File_Rename(array('target' => $new_pathname, 'overwrite' => true)));
                 }
                 $adapter->receive($file);
                 $return_file = $new_name;
             }
         }
     }
     return $return_file;
 }
예제 #3
0
 public function uploadAction()
 {
     if (!empty($_FILES)) {
         try {
             $path = '/var/apps/iphone/';
             $base_path = Core_Model_Directory::getBasePathTo($path);
             $filename = uniqid() . '.pem';
             if (!is_dir($base_path)) {
                 mkdir($base_path, 0775, true);
             }
             $adapter = new Zend_File_Transfer_Adapter_Http();
             $adapter->setDestination($base_path);
             $adapter->setValidators(array('Extension' => array('pem', 'case' => false)));
             $adapter->getValidator('Extension')->setMessages(array('fileExtensionFalse' => $this->_("Extension not allowed, \\'%s\\' only", '%extension%')));
             $files = $adapter->getFileInfo();
             foreach ($files as $file => $info) {
                 if (!$adapter->isUploaded($file)) {
                     throw new Exception($this->_('An error occurred during process. Please try again later.'));
                 } else {
                     if (!$adapter->isValid($file)) {
                         if (count($adapter->getMessages()) == 1) {
                             $erreur_message = $this->_('Error : <br/>');
                         } else {
                             $erreur_message = $this->_('Errors : <br/>');
                         }
                         foreach ($adapter->getMessages() as $message) {
                             $erreur_message .= '- ' . $message . '<br/>';
                         }
                         throw new Exception($erreur_message);
                     } else {
                         $adapter->addFilter(new Zend_Filter_File_Rename(array('target' => $base_path . $filename, 'overwrite' => true)));
                         $adapter->receive($file);
                     }
                 }
             }
             $certificat = new Push_Model_Certificat();
             $certificat->find('ios', 'type');
             if (!$certificat->getId()) {
                 $certificat->setType('ios');
             }
             $certificat->setPath($path . $filename)->save();
             $datas = array('success' => 1, 'files' => 'eeeee', 'message_success' => $this->_('Infos successfully saved'), 'message_button' => 0, 'message_timeout' => 2);
         } catch (Exception $e) {
             $datas = array('error' => 1, 'message' => $e->getMessage());
         }
         $this->getLayout()->setHtml(Zend_Json::encode($datas));
     }
 }
예제 #4
0
 /**
  * Update profile Employee
  * @return type
  */
 public function updateProfileAction()
 {
     $this->view->headTitle('Update Profile');
     $form = new Employee_Form_UpdateProfile();
     $id = (int) $this->getParam('id', '');
     if (!$id) {
         $this->_helper->redirector('list-profile');
     }
     $employeeMapper = new Employee_Model_EmployeeMapper();
     $result = $employeeMapper->findId($id);
     if (!$result) {
         $this->view->message = "Nhan vien khong ton tai";
         return;
     }
     $this->view->form = $form;
     //set up URL image
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $uploadPath = APPLICATION_PATH . '/../public/images/avatar';
     $adapter->setDestination($uploadPath);
     $adapter->addFilter('Rename', $result->getEmployeeId() . '.jpg');
     $this->view->fileName = $result->getEmployeeId() . '.jpg';
     if (!$adapter->receive()) {
         $messages = $adapter->getMessages();
     }
     $avatar = $adapter->getFileName();
     $this->_processShowForm($form, $result);
     if ($this->_processUpdateFormProfile($form)) {
         echo "Update success";
         $this->view->message = "Update success";
         $params = array('id' => $id);
         $this->_helper->redirector("show-profile", 'profile', 'employee', $params);
     }
 }
예제 #5
0
 /**
  * handleFileTransfer
  * @author Thomas Schedler <*****@*****.**>
  */
 private function handleFileTransfer()
 {
     $this->objUpload = new Zend_File_Transfer_Adapter_Http();
     $this->objUpload->setOptions(array('useByteString' => false));
     /**
      * validators for upload of media
      */
     $arrExcludedExtensions = $this->core->sysConfig->upload->excluded_extensions->extension->toArray();
     $this->objUpload->addValidator('Size', false, array('min' => 1, 'max' => $this->core->sysConfig->upload->max_filesize));
     $this->objUpload->addValidator('ExcludeExtension', false, $arrExcludedExtensions);
     /**
      * check if medium is uploaded
      */
     if (!$this->objUpload->isUploaded(self::UPLOAD_FIELD)) {
         $this->core->logger->warn('isUploaded: ' . implode('\\n', $this->objUpload->getMessages()));
         throw new Exception('File is not uploaded!');
     }
     /**
      * check if upload is valid
      */
     if (!$this->objUpload->isValid(self::UPLOAD_FIELD)) {
         $this->core->logger->warn('isValid: ' . implode('\\n', $this->objUpload->getMessages()));
         throw new Exception('Uploaded file is not valid!');
     }
 }
예제 #6
0
 public function uploadAction()
 {
     try {
         if (empty($_FILES) || empty($_FILES['file']['name'])) {
             throw new Exception($this->_("No file has been sent"));
         }
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $adapter->setDestination(Core_Model_Directory::getTmpDirectory(true));
         if ($adapter->receive()) {
             $file = $adapter->getFileInfo();
             $data = $this->_getPackageDetails($file['file']['tmp_name']);
         } else {
             $messages = $adapter->getMessages();
             if (!empty($messages)) {
                 $message = implode("\n", $messages);
             } else {
                 $message = $this->_("An error occurred during the process. Please try again later.");
             }
             throw new Exception($message);
         }
     } catch (Exception $e) {
         $data = array("error" => 1, "message" => $e->getMessage());
     }
     $this->_sendHtml($data);
 }
예제 #7
0
 public function uploadAction()
 {
     if ($code = $this->getRequest()->getPost("code")) {
         try {
             if (empty($_FILES) || empty($_FILES['file']['name'])) {
                 throw new Exception("No file has been sent");
             }
             $path = Core_Model_Directory::getPathTo(System_Model_Config::IMAGE_PATH);
             $base_path = Core_Model_Directory::getBasePathTo(System_Model_Config::IMAGE_PATH);
             if (!is_dir($base_path)) {
                 mkdir($base_path, 0777, true);
             }
             $adapter = new Zend_File_Transfer_Adapter_Http();
             $adapter->setDestination($base_path);
             if ($adapter->receive()) {
                 $file = $adapter->getFileInfo();
                 $config = new System_Model_Config();
                 $config->find($code, "code");
                 $config->setValue($path . DS . $file['file']['name'])->save();
                 $message = sprintf("Your %s has been successfully saved", $code);
                 $this->_sendHtml(array("success" => 1, "message" => $this->_($message)));
             } else {
                 $messages = $adapter->getMessages();
                 if (!empty($messages)) {
                     $message = implode("\n", $messages);
                 } else {
                     $message = $this->_("An error occurred during the process. Please try again later.");
                 }
                 throw new Exception($message);
             }
         } catch (Exception $e) {
             $data = array("error" => 1, "message" => $e->getMessage());
         }
     }
 }
예제 #8
0
 public function uploadAction()
 {
     try {
         if (empty($_FILES) || empty($_FILES['module']['name'])) {
             throw new Exception("No file has been sent");
         }
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $adapter->setDestination(Core_Model_Directory::getTmpDirectory(true));
         //            $adapter->addValidator('MimeType', false, 'application/zip');
         if ($adapter->receive()) {
             $file = $adapter->getFileInfo();
             $parser = new Installer_Model_Installer_Module_Parser();
             if ($parser->setFile($file['module']['tmp_name'])->check()) {
                 $infos = pathinfo($file['module']['tmp_name']);
                 $filename = $infos['filename'];
                 $this->_redirect('installer/module/install', array('module_name' => $filename));
             } else {
                 $messages = $parser->getErrors();
                 $message = implode("\n", $messages);
                 throw new Exception($this->_($message));
             }
         } else {
             $messages = $adapter->getMessages();
             if (!empty($messages)) {
                 $message = implode("\n", $messages);
             } else {
                 $message = $this->_("An error occurred during the process. Please try again later.");
             }
             throw new Exception($message);
         }
     } catch (Exception $e) {
         $this->getSession()->addError($e->getMessage());
         $this->_redirect('installer/module');
     }
 }
예제 #9
0
 /**
  * indexAction
  * @author Thomas Schedler <*****@*****.**>
  * @version 1.0
  */
 public function indexAction()
 {
     try {
         $this->core->logger->debug('media->controllers->UploadController->indexAction()');
         $this->objUpload = new Zend_File_Transfer_Adapter_Http();
         /**
          * validators for upload of media
          */
         $arrExcludedExtensions = $this->core->sysConfig->upload->excluded_extensions->extension->toArray();
         $this->objUpload->addValidator('Size', false, array('min' => 1, 'max' => $this->core->sysConfig->upload->max_filesize));
         $this->objUpload->addValidator('ExcludeExtension', false, $arrExcludedExtensions);
         /**
          * check if medium is uploaded
          */
         if (!$this->objUpload->isUploaded(self::UPLOAD_FIELD)) {
             $this->core->logger->warn('isUploaded: ' . implode('\\n', $this->objUpload->getMessages()));
             throw new Exception('File is not uploaded!');
         }
         /**
          * check if upload is valid
          */
         //      if (!$this->objUpload->isValid(self::UPLOAD_FIELD)) {
         //        $this->core->logger->warn('isValid: '.implode('\n', $this->objUpload->getMessages()));
         //      	throw new Exception('Uploaded file is not valid!');
         //      }
         if ($this->getRequest()->isPost()) {
             $objRequest = $this->getRequest();
             $this->intParentId = $objRequest->getParam('folderId');
             /**
              * check if is image or else document
              */
             if ($this->intParentId > 0 && $this->intParentId != '') {
                 if (strpos($this->objUpload->getMimeType(self::UPLOAD_FIELD), 'image/') !== false) {
                     $this->handleImageUpload();
                 } else {
                     $this->handleFileUpload();
                 }
             }
         }
     } catch (Exception $exc) {
         $this->core->logger->err($exc);
     }
 }
 public function indexAction()
 {
     SxCms_Acl::requireAcl('filemanager', 'filemanager.index');
     $base = APPLICATION_PATH . '/../public_html/files/';
     $base = realpath($base);
     $path = base64_decode($this->_getParam('path'));
     if ($this->getRequest()->isPost()) {
         if (null !== $this->_getParam('folder')) {
             SxCms_Acl::requireAcl('filemanager', 'filemanager.add.folder');
             if (strlen($this->_getParam('folder'))) {
                 $dirname = $path . '/' . $this->_getParam('folder');
                 mkdir($base . $dirname);
                 $this->_redirect('/admin/filemanager/index/path/' . base64_encode($path));
             }
         } else {
             SxCms_Acl::requireAcl('filemanager', 'filemanager.add.file');
             $adapter = new Zend_File_Transfer_Adapter_Http();
             $adapter->setDestination(realpath($base) . $path);
             if ($adapter->receive()) {
                 $filename = realpath($adapter->getFileName('filename'));
                 $file = new SxCms_File($filename);
                 $path = $file->getPathnameFromBase();
                 $nfile = $path . '/' . $file->getBasename();
                 $this->_redirect('/admin/filemanager/edit/file/' . base64_encode($nfile) . '/path/' . base64_encode($path));
             } else {
                 $msg = Sanmax_MessageStack::getInstance('SxCms_Filemanager');
                 $msg->addMessage('file', $adapter->getMessages());
             }
         }
     }
     $this->view->messages = Sanmax_MessageStack::getInstance('SxCms_Filemanager');
     try {
         $it = new SxCms_Filesystem(realpath($base . $path));
     } catch (Exception $e) {
         $it = new SxCms_Filesystem($base);
         $path = '';
         $e;
     }
     $topdir = explode('/', $path);
     if (count($topdir) > 1) {
         array_pop($topdir);
         $topdir = implode('/', $topdir);
     } else {
         $topdir = '';
     }
     $this->view->files = $it;
     $this->view->path = $path;
     $this->view->showpath = explode('/', $path);
     $this->view->topdir = $topdir;
     if ($this->_getParam('full')) {
         $this->_helper->layout->setLayout('nolayout');
         $this->view->full = true;
     }
 }
 public function __construct($arrParam = array(), $options = null)
 {
     //////////////////////////////////
     //Kiem tra Name /////////////
     //////////////////////////////////
     if ($arrParam['action'] == 'add') {
         $options = array('table' => 'da_album', 'field' => 'album_name');
     } elseif ($arrParam['action'] == 'edit') {
         $options = array('table' => 'da_album', 'field' => 'album_name', 'exclude' => array('field' => 'id', 'value' => $arrParam['id']));
     }
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_NotEmpty(), true)->addValidator(new Zend_Validate_StringLength(3, 100), true);
     if (!$validator->isValid($arrParam['album_name'])) {
         $message = $validator->getMessages();
         $this->_messageError['album_name'] = 'Tên album: ' . current($message);
         $arrParam['album_name'] = '';
     }
     //////////////////////////////////
     //Kiem tra Picture small ///////////
     //////////////////////////////////
     $upload = new Zend_File_Transfer_Adapter_Http();
     $fileInfo = $upload->getFileInfo('picture');
     $fileName = $fileInfo['picture']['name'];
     if (!empty($fileName)) {
         $upload->addValidator('Extension', true, array('jpg', 'gif', 'png'), 'picture');
         $upload->addValidator('Size', true, array('min' => '2KB', 'max' => '1000KB'), 'picture');
         if (!$upload->isValid('picture')) {
             $message = $upload->getMessages();
             $this->_messageError['picture'] = 'Hình ảnh đại diện: ' . current($message);
         }
     }
     //////////////////////////////////
     //Kiem tra Order /////////////
     //////////////////////////////////
     $validator = new Zend_Validate();
     $validator->addValidator(new Zend_Validate_StringLength(1, 10), true)->addValidator(new Zend_Validate_Digits(), true);
     if (!$validator->isValid($arrParam['order'])) {
         $message = $validator->getMessages();
         $this->_messageError['order'] = 'Sắp xếp: ' . current($message);
         $arrParam['order'] = '';
     }
     //////////////////////////////////
     //Kiem tra Status /////////////
     //////////////////////////////////
     if (empty($arrParam['status']) || !isset($arrParam['status'])) {
         $arrParam['status'] = 0;
     }
     //========================================
     // TRUYEN CAC GIA TRI DUNG VAO MANG $_arrData
     //========================================
     $this->_arrData = $arrParam;
 }
예제 #12
0
파일: FileUploader.php 프로젝트: jager/cms
 public function transferFile()
 {
     if (!is_dir($this->_path)) {
         mkdir($this->_path, 0777, true);
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($this->_path);
     if (!$adapter->receive()) {
         $messages = $adapter->getMessages();
         throw new Exception(implode("<br />", $messages));
     }
     return $adapter->getFileInfo();
 }
 protected function _imageResizeAndSave($object)
 {
     $path = APPLICATION_ROOT . '/public_html/images/topcontentblock/';
     $system->lng = $this->_getParam('lng');
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($path);
     $adapter->setOptions(array('ignoreNoFile' => true));
     if (!$adapter->receive()) {
         $msgr = Sanmax_MessageStack::getInstance('SxModule_Topcontentblock_Validator');
         $msgr->addMessage('file', $adapter->getMessages(), 'title');
     }
     if ($object->getPicture() == null) {
         $object->setPicture('');
     }
     $files = $adapter->getFileInfo();
     foreach ($files as $file) {
         if (!$file['tmp_name']) {
             continue;
         }
         $path0 = $path . "253X115/";
         $path1 = $path . "1263X575/";
         $path2 = $path . "1263X325/";
         $filename = $object->createThumbName($file['name']) . '_' . time() . '.jpg';
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(253, 115);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(100);
         $image->setImageFormat('jpeg');
         $image->writeImage($path0 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(1263, 575);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setImageFormat('jpeg');
         $image->writeImage($path1 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(1263, 325);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setImageFormat('jpeg');
         $image->writeImage($path2 . $filename);
         $image->clear();
         $image->destroy();
         unlink($file['tmp_name']);
         $object->setPicture($filename);
     }
 }
 protected function _imageResizeAndSave($object)
 {
     $path = APPLICATION_ROOT . '/public_html/images/eyecatchers/';
     $system->lng = $this->_getParam('lng');
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($path);
     $adapter->setOptions(array('ignoreNoFile' => true));
     if (!$adapter->receive()) {
         $msgr = Sanmax_MessageStack::getInstance('SxModule_Eyecatchers_Validator');
         $msgr->addMessage('file', $adapter->getMessages(), 'title');
     }
     if ($object->getPicture() == null) {
         $object->setPicture('');
     }
     $files = $adapter->getFileInfo();
     foreach ($files as $file) {
         if (!$file['tmp_name']) {
             continue;
         }
         $path0 = $path . "253x115/";
         $path1 = $path . "980x450/";
         if (!is_dir($path0)) {
             mkdir($path0, 0777, true);
         }
         if (!is_dir($path1)) {
             mkdir($path1, 0777, true);
         }
         $filename = $object->createThumbName($file['name']) . '_' . time() . '.png';
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(253, 115);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(100);
         $image->setBackgroundColor(new ImagickPixel('transparent'));
         $image->setImageFormat('png32');
         $image->writeImage($path0 . $filename);
         $image->clear();
         $image->destroy();
         $image = new Imagick($file['tmp_name']);
         $image->cropThumbnailImage(980, 450);
         $image->setCompression(Imagick::COMPRESSION_JPEG);
         $image->setImageCompressionQuality(75);
         $image->setBackgroundColor(new ImagickPixel('transparent'));
         $image->setImageFormat('png32');
         $image->writeImage($path1 . $filename);
         $image->clear();
         $image->destroy();
         unlink($file['tmp_name']);
         $object->setPicture($filename);
     }
 }
예제 #15
0
 public function introasyncajaxAction()
 {
     $this->getResponse()->setHeader('Content-Type', 'application/json');
     $this->_helper->viewRenderer->setNoRender(true);
     $this->_helper->layout()->disableLayout();
     $params = $this->_getAllParams();
     $intro = new Application_Model_O_GlobalConsultation();
     $validate = new Yy_Validate_Value();
     if ($validate->isValid($params['id'])) {
         $intro->setId($params['id']);
     } else {
         $intro->setCtime(date('Y-m-d H:i:s'));
     }
     if ($validate->isValid($params['title'])) {
         $intro->setTitle($params['title']);
     }
     if ($validate->isValid($params['content'])) {
         $intro->setContent($params['content']);
     }
     if ($validate->isValid($params['sort'])) {
         $intro->setSort($params['sort']);
     }
     if ($validate->isValid($params['status'])) {
         $intro->setStatus($params['status']);
     }
     try {
         $intro->save();
         $id = $intro->getId();
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $wrdir = Yy_Utils::getWriteDir();
         $adapter->setDestination($wrdir);
         if (!$adapter->receive()) {
             $messages = $adapter->getMessages();
             //echo implode("\n", $messages);
         }
         $filename = $adapter->getFileName();
         if (is_string($filename)) {
             $handle = fopen($filename, 'rb');
             $img = addslashes(fread($handle, filesize($filename)));
             fclose($handle);
             Application_Model_M_GlobalConsultation::updateImage($id, $img);
         }
         $url = '/diagnosis/introview?id=' . $id;
         $this->redirect($url);
     } catch (Zend_Db_Exception $e) {
         //$this->redirect('/error');
         $this->redirect('/error?message=' . $e->getMessage());
     }
 }
예제 #16
0
파일: Foto.php 프로젝트: jager/cms
 private function transfer($destination)
 {
     //s( $destination ); return;
     if (!is_dir($destination)) {
         mkdir($destination, 0777, true);
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($destination);
     if (!$adapter->receive()) {
         $messages = $adapter->getMessages();
         return implode("<br />", $messages);
     } else {
         return $adapter;
     }
 }
 /**
  * Provides an image browser feature for the rich text editor
  *
  * @return void
  */
 public function browseAction()
 {
     $params = Zend_Registry::get('params');
     // This is displayed inside the editor - so we need set a blank layout (no header/footer)
     $this->_helper->layout->setLayout('popup');
     $gallery = new Datasource_Cms_Gallery();
     $categoryID = $this->getRequest()->getParam('cid');
     $editorFuncNum = $this->getRequest()->getParam('CKEditorFuncNum');
     if ($this->getRequest()->isPost()) {
         // A new image has been sent - handle it
         $upload = new Zend_File_Transfer_Adapter_Http();
         $upload->setDestination($params->cms->imageUploadPath);
         $upload->addValidator('Extension', false, 'jpg,jpeg,png,gif');
         $upload->addValidator('Count', false, 1);
         $upload->addValidator('Size', false, 10240000);
         if ($upload->receive()) {
             // File has been uploaded succesfully
             $this->view->uploadSuccess = true;
             $imageFilename = $upload->getFileName(null, false);
             $imageLocation = $upload->getFileName();
             list($imageWidth, $imageHeight) = getimagesize($imageLocation);
             $imageID = $gallery->addNew(0, $imageFilename, $imageWidth, $imageHeight);
             // Resize and save a few pr
             $cmsImage = new Application_Cms_Image();
             if ($imageWidth > $imageHeight) {
                 $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/200_' . $imageFilename, 200, null);
                 $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/400_' . $imageFilename, 400, null);
             } else {
                 $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/200_' . $imageFilename, null, 150);
                 $cmsImage->resamplePhoto($imageLocation, $params->cms->imageUploadPath . '/previews/400_' . $imageFilename, null, 400);
             }
             $this->_helper->getHelper('FlashMessenger')->addMessage(array('deleted' => true));
             // $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/images/edit?id='. $imageID); // Forward to image editor
             $this->_helper->getHelper('Redirector')->goToUrl('/cms-admin/images/browse?CKEditorFuncNum=' . $editorFuncNum);
         } else {
             // An error occurred - deal with the error messages
             $errorMessages = $upload->getMessages();
         }
     } else {
         // No image uploaded - show the gallery
         if (!$categoryID) {
             $categoryID = 0;
         }
         $imageList = $gallery->getImagesByCategoryID($categoryID);
         $this->view->imageList = $this->view->partialLoop('partials/image-browser-image.phtml', $imageList);
         $this->view->editorFuncNum = $editorFuncNum;
     }
 }
 /**
  * 上传
  */
 public function uploadAction()
 {
     echo '<form enctype="multipart/form-data" action="" method="POST">
         <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
         Choose a file to upload: <input name="uploadedfile" type="file" />
         <br />
         <input type="submit" value="Upload File" />
         </form>';
     if ($this->_request->isPost()) {
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $uploadfile = '1111' . $this->_request->getPost('uploadedfile');
         // Returns the mimetype for the 'foo' form element
         if (!$adapter->receive($uploadfile)) {
             $messages = $adapter->getMessages();
             echo implode("\n", $messages);
         }
     }
 }
예제 #19
0
 public function indexAction()
 {
     if ($this->_request->isPost()) {
         // 判断是否是post上传
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $adapter->setDestination('./upfiles');
         //设置上传文件存储路径
         if (!$adapter->receive()) {
             //执行上传操作
             $messages = $adapter->getMessages();
             //获取返回的错误信息
             echo implode("<br>", $messages);
             //输出错误信息
         } else {
             echo "<script>alert('上传成功!');</script>";
         }
     }
 }
 private function upload()
 {
     $todir = $this->_cfg['temp']['path'] . $this->getRequest()->getParam('docid', 'unknown_doc');
     if (!file_exists($todir)) {
         mkdir($todir);
     }
     $adapter = new Zend_File_Transfer_Adapter_Http(array('ignoreNoFile' => true));
     $filename = $adapter->getFileName('upload', false);
     $adapter->addValidator('Extension', false, $this->getRequest()->getParam('type') == 'images' ? $this->imgExts : $this->fileExts)->addValidators($this->getRequest()->getParam('type') == 'images' ? $this->imgValidators : $this->fileValidators)->addFilter('Rename', array('target' => $todir . DIRECTORY_SEPARATOR . iconv('utf-8', FS_CHARSET, $filename), 'overwrite' => true));
     //		$adapter->setDestination($todir);
     $result = new stdClass();
     $result->messages = array();
     $result->uploadedUrl = '';
     if (!$adapter->isValid()) {
         $result->messages = $adapter->getMessages();
     } else {
         if ($adapter->receive() && $adapter->isUploaded()) {
             $result->uploadedUrl = ($this->getRequest()->getParam('type') == 'images' ? '' : 'downloads/') . $filename;
         }
     }
     $result->CKEditorFuncNum = $this->getRequest()->getParam('CKEditorFuncNum');
     return $result;
 }
예제 #21
0
 public function uploadAction()
 {
     $form = new forms_UploadForm();
     if ($this->getRequest()->isPost()) {
         $dType = $this->_getParam('dataType', 'html');
         $this->view->dType = $dType;
         if ($dType == 'json') {
             $this->_helper->layout->setLayout('json');
         }
         if ($form->isValid($_POST)) {
             $adapter = new Zend_File_Transfer_Adapter_Http();
             $adapter->setDestination(ROOT_DIR . '/public/files/uploaded');
             if (!$adapter->receive()) {
                 $this->view->errors = implode("<br />", $adapter->getMessages());
                 $this->view->message = '';
             } else {
                 if ($dType == 'json') {
                     $this->view->errors = '';
                     $this->view->message = 'File uploaded successfully';
                 } else {
                     $redirector = $this->_helper->getHelper('Redirector');
                     //setGotoSimple("action","controller");
                     $redirector->setCode(303)->setExit(false)->setGotoSimple("index", "index");
                     $redirector->redirectAndExit();
                 }
             }
         } else {
             $this->view->errors = 'Error: Invalid form';
             $this->view->message = '';
         }
     } else {
         $redirector = $this->_helper->getHelper('Redirector');
         //setGotoSimple("action","controller");
         $redirector->setCode(303)->setExit(false)->setGotoSimple("index", "index");
         $redirector->redirectAndExit();
     }
 }
예제 #22
0
 /**
  * Handler for files uploader
  * @return array
  */
 private function _uploadFiles($savePath = null)
 {
     $this->_uploadHandler->clearValidators();
     $this->_uploadHandler->clearFilters();
     if (!$savePath) {
         $savePath = $this->_getSavePath();
     }
     $fileInfo = $this->_uploadHandler->getFileInfo();
     $file = reset($fileInfo);
     preg_match('~[^\\x00-\\x1F"<>\\|:\\*\\?/]+\\.[\\w\\d]{2,8}$~iU', $file['name'], $match);
     if (!$match) {
         return array('result' => 'Corrupted filename', 'error' => true);
     }
     $this->_uploadHandler->addFilter('Rename', array('target' => $savePath . DIRECTORY_SEPARATOR . $file['name'], 'overwrite' => true));
     if ($this->_uploadHandler->isUploaded() && $this->_uploadHandler->isValid()) {
         try {
             $this->_uploadHandler->receive();
         } catch (Exceptions_SeotoasterException $e) {
             $response = array('result' => $e->getMessage(), 'error' => true);
         }
     }
     $response = array('result' => $this->_uploadHandler->getMessages(), 'error' => !$this->_uploadHandler->isReceived());
     return $response;
 }
예제 #23
0
 /**
  *
  * @return array 
  */
 public function uploadFiles()
 {
     $return = array('files' => array());
     try {
         $dir = $this->getDirDocs();
         $adapter = new Zend_File_Transfer_Adapter_Http();
         $adapter->setDestination($dir);
         $typeValidator = new Zend_Validate_File_Extension($this->_extensions);
         $sizeFile = new Zend_Validate_File_Size($this->_maxSize);
         $adapter->addValidator($typeValidator, true)->addValidator($sizeFile, true);
         $files = $adapter->getFileInfo();
         foreach ($files as $file => $info) {
             if (!$adapter->isUploaded($file)) {
                 continue;
             }
             $name = $this->_getNewFileName($dir, $info['name']);
             $fileInfo = array('size' => $info['size'], 'name' => $name);
             if (!$adapter->isValid($file)) {
                 $messages = $adapter->getMessages();
                 $fileInfo['error'] = array_shift($messages);
                 $return['files'][] = $fileInfo;
                 continue;
             }
             $adapter->addFilter('Rename', $dir . $name, $file);
             $adapter->receive($file);
             $pathFile = $this->publicFileUrl($dir . $name);
             $fileInfo['url'] = $pathFile;
             $fileInfo['delete_url'] = '/client/document/delete/?file=' . $pathFile;
             $fileInfo['delete_type'] = 'DELETE';
             $return['files'][] = $fileInfo;
         }
         return $return;
     } catch (Exception $e) {
         return $return;
     }
 }
예제 #24
0
 /**
  * Upload the file and return the new value.
  *
  * @param Phprojekt_Model_Interface $model  Current module.
  * @param string                    $field  Name of the field in the module.
  * @param integer                   $itemId Id of the current item.
  *
  * @throws Exception On no write access or exceed the Max upload size.
  *
  * @return string Md5 string of all the files separated by ||.
  */
 public static function uploadFile($model, $field, $itemId)
 {
     self::_checkParamField($model, $field);
     self::_checkWritePermission($model, $itemId);
     $config = Phprojekt::getInstance()->getConfig();
     $files = self::_getSessionFiles($field);
     // Remove all the upload files that are not "uploadedFile"
     foreach (array_keys($_FILES) as $key) {
         if ($key != 'uploadedFile') {
             unset($_FILES[$key]);
         }
     }
     // Fix name for save it as md5
     if (is_array($_FILES) && !empty($_FILES) && isset($_FILES['uploadedFile'])) {
         $md5name = md5(mt_rand() . time());
         $addedFile = array('md5' => $md5name, 'name' => self::_makeUniqueName($_FILES['uploadedFile']['name'], $files));
         $_FILES['uploadedFile']['name'] = $md5name;
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($config->uploadPath);
     if (!$adapter->receive()) {
         $messages = $adapter->getMessages();
         foreach ($messages as $index => $message) {
             $messages[$index] = Phprojekt::getInstance()->translate($message);
             if ($index == 'fileUploadErrorFormSize') {
                 $maxSize = isset($config->maxUploadSize) ? (int) $config->maxUploadSize : Phprojekt::DEFAULT_MAX_UPLOAD_SIZE;
                 $maxSize = (int) ($maxSize / 1024);
                 $messages[$index] .= ': ' . $maxSize . ' Kb.';
             }
         }
         throw new Exception(implode("\n", $messages));
     } else {
         $files[] = $addedFile;
         self::addFilesToUnusedFileList(array($addedFile));
     }
     self::_setSessionFiles($files, $field);
     return $files;
 }
예제 #25
0
 /**
  * Upload plugin zip file.
  *
  * @param string $formName name of the form on the user interface
  * @param stdclass $json
  * @return array
  *
  * $tempFileName,
  * $tempFilePath,
  * $json
  */
 function upload($formName, $json)
 {
     $rootPath = RM_Environment::getConnector()->getRootPath();
     //1. upload zip - check if this file name a .zip extension
     //2. move zip to temp directory
     $tempFolderName = 'temp';
     $tempFolderPath = $rootPath . DIRECTORY_SEPARATOR . 'RM' . DIRECTORY_SEPARATOR . 'userdata' . DIRECTORY_SEPARATOR . $tempFolderName;
     $validators = array();
     $validators[] = new Zend_Validate_File_Extension('zip');
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setValidators($validators);
     try {
         $adapter->setDestination($tempFolderPath);
     } catch (Zend_File_Transfer_Exception $exception) {
         throw new RM_Exception($exception->getMessage());
     }
     if (!$adapter->receive()) {
         $message = $this->_translate->_('Admin.Plugins.InstallMsg', 'UploadFailed');
         $message .= '. ' . implode("; ", $adapter->getMessages());
         throw new RM_Exception($message);
     } else {
         $json = $this->_addMessageToJson($json, $this->_translate->_('Admin.Plugins.InstallMsg', 'UploadSuccess'));
     }
     //3. create new directory for a plugin
     $files = $adapter->getFileInfo();
     $tempFileName = $files[$formName]['name'];
     $tempFilePath = $tempFolderPath . DIRECTORY_SEPARATOR . $tempFileName;
     return array($tempFileName, $tempFilePath, $json);
 }
예제 #26
0
 /** Give them a logo
  * @access public
  * @return void
  *
  */
 public function logoAction()
 {
     $form = new AddStaffLogoForm();
     $form->details->setLegend('Add a logo: ');
     $this->view->form = $form;
     if ($this->_request->isPost()) {
         $formData = $this->_request->getPost();
         if ($form->isValid($formData)) {
             $upload = new Zend_File_Transfer_Adapter_Http();
             $upload->addValidator('NotExists', true, array(self::LOGOPATH));
             if ($upload->isValid()) {
                 $filename = $form->getValue('image');
                 $insertData = array();
                 $insertData['host'] = $filename;
                 $insertData['updated'] = $this->getTimeForForms();
                 $insertData['updatedBy'] = $this->getIdentityForForms();
                 $regions = new StaffRegions();
                 $where = array();
                 $where[] = $regions->getAdapter()->quoteInto('id = ?', $this->getParam('id'));
                 $regions->update($insertData, $where);
                 $upload->receive();
                 $this->getFlash()->addMessage('The image has been resized and zoomified!');
                 $this->redirect('/admin/contacts/institution/id/' . $this->getParam('id'));
             } else {
                 $this->getFlash()->addMessage('There is a problem with your upload. Probably that image exists.');
                 $this->view->errors = $upload->getMessages();
             }
         } else {
             $form->populate($formData);
             $this->getFlash()->addMessage('Check your form for errors');
         }
     }
 }
예제 #27
0
 /**
  * Uploads a batch file to the rig client. The user must already been to be
  * assigned to a rig.
  * <br />
  * Unlike the other functions in this controller, the response is not JSON but
  * a text string with the format:
  * <ul>
  *  <li>true - Succeeding uploading and invoking batch control.</li>
  *  <li>false; &lt;error reason;&gt; - Failed uploading or invoking batch
  *  control with a provided reason.</li>
  * </ul>
  */
 public function torigclientAction()
 {
     $this->_helper->viewRenderer->setNoRender();
     $this->_helper->layout()->disableLayout();
     $response = Sahara_Soap::getSchedServerSessionClient()->getSessionInformation(array('userQName' => $this->_auth->getIdentity()));
     if (!$response->isInSession) {
         /* Not in session, so unable to determine the rig clients address. */
         $error = array('success' => 'false', 'error' => array('code' => -1, 'operation' => 'Batch control request', 'reason' => 'not in session'));
         echo "error; Not in session.";
         return;
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $dest = $this->_config->upload->dir;
     if (!$dest) {
         $this->_logger->error("Batch download directory not configured, 'upload.dir' property.");
         throw new Exception("Batch download directory not configured.");
     }
     $adapter->setDestination($dest)->addValidator('Count', false, 1);
     /* Size file validator. */
     if ($size = $this->_config->upload->size) {
         $adapter->addValidator('FilesSize', false, $size);
     }
     /* Extension file validator. */
     if ($ext = $this->_config->upload->extension) {
         $adapter->addValidator('Extension', false, $ext);
     }
     if (!$adapter->receive()) {
         $error = 'File validation has failed.';
         foreach ($adapter->getMessages() as $k => $v) {
             switch ($k) {
                 case 'fileExtensionFalse':
                     $error .= ' The file extension was incorrect.';
                     break;
                 case 'fileUploadErrorIniSize':
                 case 'fileUploadErrorFormSize':
                     $error .= ' The file size was too large.';
                     break;
                 default:
                     $error .= ' ' . $v;
                     break;
             }
         }
         echo "error; {$error}";
         return;
     }
     $file = $adapter->getFileName();
     list($ns, $name) = explode(':', $this->_auth->getIdentity());
     $request = array('requestor' => $name, 'fileName' => basename($file), 'batchFile' => file_get_contents($file));
     if (!$request['batchFile']) {
         $this->_logger->warn("Failed to read batch file {$file}.");
         echo 'false; Upload to read batch file.';
         return;
     }
     unlink($file);
     try {
         $rigClient = new Sahara_Soap($response->contactURL . '?wsdl');
         header('Content-Type', 'text/plain');
         $response = $rigClient->performBatchControl($request);
         echo $response->success ? 'true' : 'false; ' . $response->error->reason;
     } catch (Exception $ex) {
         $this->_logger->error("Soap error calling batch 'performPrimitiveControl'. Message: " . $ex->getMessage() . ', code: ' . $ex->getCode() . '.');
         echo 'false; ' . $ex->getMessage();
     }
 }
 public function resizeAndSave()
 {
     $path = APPLICATION_ROOT . '/public_html/images/faqcategory/';
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination($path);
     $adapter->setOptions(array('ignoreNoFile' => true));
     if (!$adapter->receive()) {
         $msgr = Sanmax_MessageStack::getInstance('SxModule_Faq_Category');
         $msgr->addMessage('file', $adapter->getMessages(), 'file');
     }
     $files = $adapter->getFileInfo();
     foreach ($files as $file) {
         if ($file['tmp_name'] == '') {
             continue;
         }
         //unlink($file['tmp_name']);
         $this->_cat->setPicture($file['name']);
     }
 }
예제 #29
0
 /**
  * Runs the upload routine and then rendera the upload.phtml template.
  *
  * This function draws the upload field in the form.
  *
  * OPTIONAL request parameters:
  * <pre>
  *  - string  <b>moduleName</b>    Current module name.
  *  - string  <b>field</b>         Name of the field in the module.
  *  - integer <b>MAX_FILE_SIZE</b> Max size allowed for the file.
  *  - integer <b>itemId</b>        Id of the current item.
  * </pre>
  *
  * @return void
  */
 public function fileUploadAction()
 {
     $module = Cleaner::sanitize('alnum', $this->getRequest()->getParam('moduleName', 'Project'));
     $field = Cleaner::sanitize('alnum', $this->getRequest()->getParam('field', null));
     $maxSize = (int) $this->getRequest()->getParam('MAX_FILE_SIZE', null);
     $itemId = (int) $this->getRequest()->getParam('itemId', null);
     $addedValue = '';
     $model = Phprojekt_Loader::getModel($module, $module);
     $this->_fileCheckParamField($model, $field);
     $this->_fileCheckWritePermission($model, $itemId);
     $value = $_SESSION['uploadedFiles_' . $field];
     // Remove all the upload files that are not "uploadedFile"
     foreach (array_keys($_FILES) as $key) {
         if ($key != 'uploadedFile') {
             unset($_FILES[$key]);
         }
     }
     // Fix name for save it as md5
     if (is_array($_FILES) && !empty($_FILES) && isset($_FILES['uploadedFile'])) {
         $md5name = md5(mt_srand());
         $addedValue = $md5name . '|' . $_FILES['uploadedFile']['name'];
         $_FILES['uploadedFile']['name'] = $md5name;
     }
     $adapter = new Zend_File_Transfer_Adapter_Http();
     $adapter->setDestination(Phprojekt::getInstance()->getConfig()->uploadPath);
     $this->getResponse()->clearHeaders();
     $this->getResponse()->clearBody();
     if (!$adapter->receive()) {
         $messages = $adapter->getMessages();
         foreach ($messages as $index => $message) {
             $messages[$index] = Phprojekt::getInstance()->translate($message);
             if ($index == 'fileUploadErrorFormSize') {
                 $maxSize = (int) ($maxSize / 1024);
                 $messages[$index] .= ': ' . $maxSize . ' Kb.';
             }
         }
         $this->view->errorMessage = implode("\n", $messages);
     } else {
         if (!empty($value)) {
             $value .= '||';
         }
         $value .= $addedValue;
     }
     $_SESSION['uploadedFiles_' . $field] = $value;
     $linkBegin = Phprojekt::getInstance()->getConfig()->webpath . 'index.php/Default/File/';
     $this->_fileRenderView($linkBegin, $module, $itemId, $field, $value, true);
 }
예제 #30
0
 /** Change staff profile image
  */
 public function logoAction()
 {
     $contacts = new Contacts();
     $people = $contacts->fetchRow($contacts->select()->where('dbaseID = ?', $this->getIdentityForForms()));
     $inst = $people->identifier;
     $this->view->inst = $inst;
     $logos = new InstLogos();
     $logoslisted = $logos->getLogosInst($inst);
     $this->view->logos = $logoslisted;
     $form = new AddStaffLogoForm();
     $form->details->setLegend('Add a logo: ');
     $this->view->form = $form;
     if ($this->_request->isPost()) {
         $formData = $this->_request->getPost();
         if ($form->isValid($formData)) {
             $upload = new Zend_File_Transfer_Adapter_Http();
             $upload->addValidator('NotExists', true, array(self::LOGOPATH));
             if ($upload->isValid()) {
                 $filename = $form->getValue('logo');
                 $largepath = self::LOGOPATH;
                 $original = $largepath . $filename;
                 $name = substr($filename, 0, strrpos($filename, '.'));
                 $ext = '.jpg';
                 $converted = $name . $ext;
                 $insertData = array();
                 $insertData['image'] = $converted;
                 $insertData['instID'] = $inst;
                 $insertData['created'] = $this->getTimeForForms();
                 $insertData['createdBy'] = $this->getIdentityForForms();
                 foreach ($insertData as $key => $value) {
                     if (is_null($value) || $value == "") {
                         unset($insertData[$key]);
                     }
                 }
                 $replace = $form->getValue('replace');
                 if ($replace == 1) {
                     foreach ($logoslisted as $l) {
                         unlink(self::LOGOPATH . 'thumbnails/' . $l['image']);
                         unlink(self::LOGOPATH . $l['image']);
                         unlink(self::LOGOPATH . 'resized/' . $l['image']);
                     }
                 }
                 $smallpath = self::LOGOPATH . 'thumbnails/' . $converted;
                 $mediumpath = self::LOGOPATH . 'resized/' . $converted;
                 //create medium size
                 $phMagick = new phMagick($original, $mediumpath);
                 $phMagick->resize(300, 0);
                 $phMagick->convert();
                 $phMagick = new phMagick($original, $smallpath);
                 $phMagick->resize(100, 0);
                 $phMagick->convert();
                 $logos->insert($insertData);
                 $upload->receive();
                 $this->getFlash()->addMessage('The image has been resized and zoomified!');
                 $this->redirect('/users/account/');
             } else {
                 $this->getFlash()->addMessage('There is a problem with your upload. Probably that image exists.');
                 $this->view->errors = $upload->getMessages();
             }
         } else {
             $form->populate($formData);
             $this->getFlash()->addMessage('Check your form for errors');
         }
     }
 }