public function uploadAjaxAction() { $this->_helper->layout->setLayout('ajax'); $data = $this->_request->getPost(); $extraDados = ""; if (isset($data['id'])) { $extraDados = $data['id'] . '-'; } $path = PUBLIC_PATH . DIRECTORY_SEPARATOR . 'uploads'; $upload = new Zend_File_Transfer_Adapter_Http(); $upload->setDestination($path); // Returns all known internal file information $files = $upload->getFileInfo(); foreach ($files as $file => $info) { // Se não existir arquivo para upload if (!$upload->isUploaded($file)) { print '<p class="alert alert-warning">Nenhum arquivo selecionado para upload<p>'; continue; } else { $fileName = $extraDados . str_replace(' ', '_', strtolower($info['name'])); // Renomeando o arquivo $upload->addFilter('Rename', array('target' => $path . DIRECTORY_SEPARATOR . $fileName, 'overwrite' => true)); } // Validação do arquivo ? if (!$upload->isValid($file)) { print '<p class="alert alert-danger" > <b>' . $file . '</b>. Arquivo inválido </p>'; continue; } else { if ($upload->receive($info['name'])) { print '<p class="alert alert-success"> Arquivo: <b>' . $info['name'] . '</b> enviado com sucesso e renomeado para: <b>' . $fileName . '</b> </p>'; } } } }
public function uploadphotoAction() { if ($this->getRequest()->isPost()) { if ($_FILES['photo']['name'][0] != '') { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(Zend_Registry::get('userImagesPath')); $files = $adapter->getFileInfo(); $i = 1; foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { $this->view->sendConfirm = 'Problem uploading files'; return $this->render('error'); } $extension = strtolower(end(explode('.', $info['name']))); $name = time() . '4' . $i . "." . $extension; $i++; $adapter->addFilter('Rename', array('target' => Zend_Registry::get('userImagesPath') . $name, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { return $this->render('error'); } } $filename = $adapter->getFileName(); $filename = basename($filename); $profile = array('photo' => $filename); if (($edited = $this->profileService->editProfile(2, $profile)) === TRUE) { $this->view->profile = $this->profileService->fetchProfile(2); } else { $this->view->profile = $edited; } $this->render('getprofile'); } } }
/** * @param string $attributeCode * @param string $type * @return bool */ protected static function handleUpload($attributeCode, $type) { if (!isset($_FILES)) { return false; } $adapter = new Zend_File_Transfer_Adapter_Http(); if ($adapter->isUploaded('typecms_' . $attributeCode . '_')) { if (!$adapter->isValid('typecms_' . $attributeCode . '_')) { Mage::throwException(Mage::helper('typecms')->__('Uploaded ' . $type . ' is invalid')); } $upload = new Varien_File_Uploader('typecms[' . $attributeCode . ']'); $upload->setAllowCreateFolders(true); if ($type == 'image') { $upload->setAllowedExtensions(array('jpg', 'gif', 'png')); } $upload->setAllowRenameFiles(true); $upload->setFilesDispersion(false); try { if ($upload->save(Mage::helper('typecms')->getBaseImageDir())) { return $upload->getUploadedFileName(); } } catch (Exception $e) { Mage::throwException('Uploaded ' . $type . ' is invalid'); } } return false; }
/** * 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!'); } }
public function changeprofileimgAction() { if ($this->getRequest()->isPost()) { if (!empty($_FILES['photo']['name'])) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination(Zend_Registry::get('profileImagesPath')); $files = $adapter->getFileInfo(); $i = 1; foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { return $this->_redirect('/profile'); } $extension = strtolower(end(explode('.', $info['name']))); $name = time() . $this->_user->id . $i++ . "." . $extension; $adapter->addFilter('Rename', array('target' => Zend_Registry::get('profileImagesPath') . $name, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { $this->view->error = 'There was a problem uploading the photo. Please try again later'; return $this->render('error'); } } $filename = $adapter->getFileName(); $filename = basename($filename); $changes = array('photo' => $filename); $profileService = new Service_Profile(); if ($edited = $profileService->editProfile($this->_user->profileid, $changes)) { return $this->_redirect('/profile'); } else { $this->view->error = 'There was a problem updating your profile. Please try again later'; return $this->render('error'); } } } else { $this->_redirect('/profile'); } }
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; }
/** * 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); } }
/** * Upload preview image * * @param string $scope the request key for file * @param string $destinationPath path to upload directory * @return bool * @throws \Magento\Framework\Exception\LocalizedException */ public function uploadPreviewImage($scope, $destinationPath) { if (!$this->_transferAdapter->isUploaded($scope)) { return false; } if (!$this->_transferAdapter->isValid($scope)) { throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Uploaded image is not valid')); } $upload = $this->_uploaderFactory->create(['fileId' => $scope]); $upload->setAllowCreateFolders(true); $upload->setAllowedExtensions($this->_allowedExtensions); $upload->setAllowRenameFiles(true); $upload->setFilesDispersion(false); if (!$upload->checkAllowedExtension($upload->getFileExtension())) { throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Invalid image file type.')); } if (!$upload->save($destinationPath)) { throw new \Magento\Framework\Exception\LocalizedException(new \Magento\Framework\Phrase('Image can not be saved.')); } return $destinationPath . '/' . $upload->getUploadedFileName(); }
public function actionInstall() { $this->_assertPostOnly(); $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; } else { $fileName = $this->_input->filterSingle('server_file', XenForo_Input::STRING); } $this->getModelFromCache('EWRporta_Model_Layouts')->installLayoutXmlFromFile($fileName); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildAdminLink('ewrporta/layouts')); }
public function actionXenGallerySave() { $this->_assertPostOnly(); $input = $this->_input->filter(array('group_id' => XenForo_Input::STRING, 'options' => XenForo_Input::ARRAY_SIMPLE, 'options_listed' => array(XenForo_Input::STRING, array('array' => true)))); $options = XenForo_Application::getOptions(); $optionModel = $this->_getOptionModel(); $group = $optionModel->getOptionGroupById($input['group_id']); foreach ($input['options_listed'] as $optionName) { if ($optionName == 'xengalleryUploadWatermark') { continue; } if (!isset($input['options'][$optionName])) { $input['options'][$optionName] = ''; } } $delete = $this->_input->filterSingle('delete_watermark', XenForo_Input::BOOLEAN); if ($delete) { $existingWatermark = $options->get('xengalleryUploadWatermark'); if ($existingWatermark) { $watermarkWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Watermark', XenForo_DataWriter::ERROR_SILENT); $watermarkWriter->setExistingData($existingWatermark); $watermarkWriter->delete(); $input['options']['xengalleryUploadWatermark'] = 0; $optionModel->updateOptions($input['options']); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(XenForo_Link::buildAdminLink('options/list', $group))); } } $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('watermark')) { $fileInfo = $fileTransfer->getFileInfo('watermark'); $fileName = $fileInfo['watermark']['tmp_name']; $watermarkWriter = XenForo_DataWriter::create('XenGallery_DataWriter_Watermark', XenForo_DataWriter::ERROR_SILENT); $existingWatermark = $options->get('xengalleryUploadWatermark'); if ($existingWatermark) { $watermarkWriter->setExistingData($existingWatermark); } $watermarkData = array('watermark_user_id' => XenForo_Visitor::getUserId(), 'is_site' => 1); $watermarkWriter->bulkSet($watermarkData); $watermarkWriter->save(); $image = new XenGallery_Helper_Image($fileName); $image->resize($options->xengalleryWatermarkDimensions['width'], $options->xengalleryWatermarkDimensions['height'], 'fit'); $watermarkModel = $this->_getWatermarkModel(); $watermarkPath = $watermarkModel->getWatermarkFilePath($watermarkWriter->get('watermark_id')); if (XenForo_Helper_File::createDirectory(dirname($watermarkPath), true)) { XenForo_Helper_File::safeRename($fileName, $watermarkPath); $input['options']['xengalleryUploadWatermark'] = $watermarkWriter->get('watermark_id'); } } $optionModel->updateOptions($input['options']); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $this->getDynamicRedirect(XenForo_Link::buildAdminLink('options/list', $group))); }
public function uploadAction() { if (!empty($_FILES)) { try { $path = '/var/apps/iphone/certificates/'; $base_path = Core_Model_Directory::getBasePathTo($path); $filename = uniqid() . '.pem'; $app_id = $this->getRequest()->getParam('app_id'); 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_Certificate(); $certificat->find(array('type' => 'ios', 'app_id' => $app_id)); if (!$certificat->getId()) { $certificat->setType('ios')->setAppId($app_id); } $certificat->setPath($path . $filename)->save(); $datas = array('success' => 1, 'files' => 'eeeee', 'message_success' => $this->_('Info 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)); } }
public function actionImport() { if (!$this->perms['admin']) { return $this->responseNoPermission(); } if (XenForo_Application::autoload('EWRmedio_XML_Premium')) { $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; $this->getModelFromCache('EWRmedio_Model_Services')->importService($fileName); } } return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('media/admin/services')); }
public function save($path, $extension, $userid = 0) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $files = $adapter->getFileInfo(); foreach ($files as $file => $info) { if (!$adapter->isUploaded($file)) { return false; } $filename = $this->generateFileName($extension, $userid); $adapter->addFilter('Rename', array('target' => $path . $filename, 'overwrite' => TRUE)); if (!$adapter->receive($info['name'])) { return false; } } $filename = $adapter->getFileName(); $filename = basename($filename); return $filename; }
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; }
/** * 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; }
/** * * @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; } }
/** * Upload image and return uploaded image file name or false * * @throws Mage_Core_Exception * @param string $scope the request key for file * @return bool|string */ public function uploadImage($scope) { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->addValidator('ImageSize', true, $this->_imageSize); $adapter->addValidator('Size', true, self::MAX_FILE_SIZE); if ($adapter->isUploaded($scope)) { // validate image if (!$adapter->isValid($scope)) { Mage::throwException(Mage::helper('hello')->__('Uploaded image is not valid')); } $upload = new Varien_File_Uploader($scope); $upload->setAllowCreateFolders(true); $upload->setAllowedExtensions($this->_allowedExtensions); $upload->setAllowRenameFiles(true); $upload->setFilesDispersion(false); if ($upload->save($this->getBaseDir())) { return $upload->getUploadedFileName(); } } return false; }
public function saveFieldsValues($fields, $values, $nodeeditorInfo) { if ($values['MODE'] == 'ADD') { $oldvalues = array(); $oldid = $values['NODEID']; $id = $this->getNextId(); $values['NODEID'] = $id; } else { // $oldvalues = $this->getFieldsValues($fields, $values['NODEID'], $nodeeditorInfo); $oldid = $id = $values['NODEID']; } if (array_key_exists('_FILE_EDITOR', $values)) { $values['_FILE_EDITOR'] = preg_replace("' ?ilo-full-src=\".*\"'Ui", '', $values['_FILE_EDITOR']); } // file_put_contents("t:\\values.txt", serialize($values)); /* $createHistoryRecord = $nodeeditorInfo['ISHISTORY']; if($createHistoryRecord) { $this->regMod($values); file_put_contents($this->_cfg['docs_mod']['path'] . "$id.ser", serialize($values)); $this->copyRes($this->_cfg['temp']['path'] . $id, $this->_cfg['docs_mod']['path'] . $id); $this->full_del_dir($this->_cfg['temp']['path'] . $id); return; }*/ if (isset($nodeeditorInfo['VALUES_FILTER_CLASS'])) { $prepClass = 'Admin_Model_' . trim($nodeeditorInfo['VALUES_FILTER_CLASS']); $prepObj = new $prepClass(); if (method_exists($prepObj, 'beforeSaveValues')) { $prepObj->beforeSaveValues($values); } } $tables = $this->getFieldsByTables($fields); $this->_db->beginTransaction(); $sql = "select RDB\$SET_CONTEXT('USER_TRANSACTION', 'CURRENT_USERID', ?) from RDB\$DATABASE"; $this->_db->fetchCol($sql, $this->_acl->userid); try { foreach ($tables as $table => &$table_fields) { if ($table == '_UPLOAD_') { $upload = new Zend_File_Transfer_Adapter_Http(array('ignoreNoFile' => true)); // $upload->addValidator('Size', true, '20M'); if (!$upload->isValid()) { throw new Zend_Exception('Upload not valid<br>' . implode('<br>', $upload->getMessages())); } if ($upload->receive() && $upload->isUploaded()) { $tmpFile = $upload->getFileName(); $docFile = $this->_cfg['docs']['path'] . $values['NODEID'] . '.bin'; if (file_exists($docFile)) { unlink($docFile); } if (!rename($tmpFile, $docFile)) { throw new Zend_Exception("File not renamed from \"{$tmpFile}\" to \" {$docFile}\""); } } //else throw new Zend_Exception('Upload not valid<br>' . implode('<br>', $upload->getMessages())); } elseif (strpos($table, 'V_ADD_') === 0) { $sql = 'update or insert into ' . $table . '(NODEID, FIELDNAME, VAL) values(?,?,?) matching(NODEID, FIELDNAME)'; $table_fields_values[0] = $values['NODEID']; foreach ($table_fields as &$fieldname) { $table_fields_values[1] = $fieldname; $table_fields_values[2] = !empty($values[$fieldname]) ? is_array($values[$fieldname]) ? implode(",", $values[$fieldname]) : $values[$fieldname] : null; $this->_db->query($sql, $table_fields_values); } } else { array_push($table_fields, 'NODEID'); if ($table == 'CONTENTTREE') { if (in_array('PARENTID', $table_fields)) { if ($values['MODE'] == 'ADD') { // || ($oldvalues['PARENTID'] != $values['PARENTID'])) $this->checkAllowedNode($values['PARENTID'], $values['NODETYPEID'], 'ADD'); } //problem with OCCUR_MIN=1 and edit } else { $table_fields = array_merge(array('PARENTID'), $table_fields); } if (!in_array('NODETYPEID', $table_fields)) { $table_fields = array_merge(array('NODETYPEID'), $table_fields); } } elseif ($table == '_NODB_') { foreach ($table_fields as &$fieldname) { if (strpos($fieldname, '_FILE_') === 0) { // начинается с _FILE_ $this->saveXmlFileContent($values['NODEID'], $values[$fieldname]); } } continue; } $fieldsStr = implode(",", $table_fields); $paramsStr = implode(",", array_fill(0, count($table_fields), '?')); $sql = 'update or insert into ' . $table . '(' . $fieldsStr . ') values(' . $paramsStr . ') matching(NODEID)'; $table_fields_values = array(); foreach ($table_fields as &$fieldname) { array_push($table_fields_values, $values[$fieldname] !== '' ? is_array($values[$fieldname]) ? implode(",", $values[$fieldname]) : $values[$fieldname] : null); } // try { $this->_db->query($sql, $table_fields_values); // } catch (Zend_Exception $e) { // throw new Zend_Exception($sql . "\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); // } } } $this->_db->commit(); if (isset($nodeeditorInfo['VALUES_FILTER_CLASS'])) { $prepClass = 'Admin_Model_' . trim($nodeeditorInfo['VALUES_FILTER_CLASS']); $prepObj = new $prepClass(); if (method_exists($prepObj, 'afterSaveValues')) { $prepObj->afterSaveValues($values); } } $this->copyResources($oldid, $id, false); } catch (Zend_Exception $e) { $this->_db->rollback(); throw $e; } }
/** * Validate user input for option * * @throws Mage_Core_Exception * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...) * @return Mage_Catalog_Model_Product_Option_Type_Default */ public function validateUserValue($values) { AO::getSingleton('checkout/session')->setUseNotice(false); $this->setIsValid(true); $option = $this->getOption(); // Set option value from request (Admin/Front reorders) if (isset($values[$option->getId()]) && is_array($values[$option->getId()])) { if (isset($values[$option->getId()]['order_path'])) { $orderFileFullPath = AO::getBaseDir() . $values[$option->getId()]['order_path']; } else { $this->setUserValue(null); return $this; } $ok = is_file($orderFileFullPath) && is_readable($orderFileFullPath) && isset($values[$option->getId()]['secret_key']) && substr(md5(file_get_contents($orderFileFullPath)), 0, 20) == $values[$option->getId()]['secret_key']; $this->setUserValue($ok ? $values[$option->getId()] : null); return $this; } elseif ($this->getProduct()->getSkipCheckRequiredOption()) { $this->setUserValue(null); return $this; } /** * Upload init */ $upload = new Zend_File_Transfer_Adapter_Http(); $file = 'options_' . $option->getId() . '_file'; try { $runValidation = $option->getIsRequire() || $upload->isUploaded($file); if (!$runValidation) { $this->setUserValue(null); return $this; } $fileInfo = $upload->getFileInfo($file); $fileInfo = $fileInfo[$file]; } catch (Exception $e) { $this->setIsValid(false); AO::throwException(AO::helper('catalog')->__("Files upload failed")); } /** * Option Validations */ // Image dimensions $_dimentions = array(); if ($option->getImageSizeX() > 0) { $_dimentions['maxwidth'] = $option->getImageSizeX(); } if ($option->getImageSizeY() > 0) { $_dimentions['maxheight'] = $option->getImageSizeY(); } if (count($_dimentions) > 0) { $upload->addValidator('ImageSize', false, $_dimentions); } // File extension $_allowed = $this->_parseExtensionsString($option->getFileExtension()); if ($_allowed !== null) { $upload->addValidator('Extension', false, $_allowed); } else { $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions')); if ($_forbidden !== null) { $upload->addValidator('ExcludeExtension', false, $_forbidden); } } /** * Upload process */ $this->_initFilesystem(); if ($upload->isUploaded($file) && $upload->isValid($file)) { $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION); $fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']); $dispersion = Varien_File_Uploader::getDispretionPath($fileName); $filePath = $dispersion; $destination = $this->getQuoteTargetDir() . $filePath; $this->_createWriteableDir($destination); $upload->setDestination($destination); $fileHash = md5(file_get_contents($fileInfo['tmp_name'])); $filePath .= DS . $fileHash . '.' . $extension; $fileFullPath = $this->getQuoteTargetDir() . $filePath; $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true)); if (!$upload->receive()) { $this->setIsValid(false); AO::throwException(AO::helper('catalog')->__("File upload failed")); } $_imageSize = @getimagesize($fileFullPath); if (is_array($_imageSize) && count($_imageSize) > 0) { $_width = $_imageSize[0]; $_height = $_imageSize[1]; } else { $_width = 0; $_height = 0; } $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20))); } elseif ($upload->getErrors()) { $errors = array(); foreach ($upload->getErrors() as $errorCode) { if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) { $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle()); } elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) { $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle()); } elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG || $errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG) { $errors[] = AO::helper('catalog')->__("Maximum allowed image size for '%s' is %sx%s px.", $option->getTitle(), $option->getImageSizeX(), $option->getImageSizeY()); } } if (count($errors) > 0) { $this->setIsValid(false); AO::throwException(implode("\n", $errors)); } } else { $this->setIsValid(false); AO::throwException(AO::helper('catalog')->__('Please specify the product required option(s)')); } return $this; }
public function actionImport() { if ($this->isConfirmedPost()) { $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; } else { $fileName = $this->_input->filterSingle('server_file', XenForo_Input::STRING); } $deleteAll = $this->_input->filterSingle('delete_all', XenForo_Input::UINT); $this->_getWidgetModel()->importFromFile($fileName, $deleteAll); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildAdminLink('widgets')); } else { return $this->responseView('WidgetFramework_ViewAdmin_Widget_Import', 'wf_widget_import'); } }
/** * Accepts the form * * Takes two roundtrips: * - first we get a HEAD request that should be answerd with * responsecode 204 * - then we get a post that only submits $_FILES (so actual $_POST will be empty) * this will be an xml file for the actuel response and optionally images and/or video * proper responses are * 201 received and stored * 202 received ok, not stored */ public function submissionAction() { $this->makeRosaResponse(); if ($this->getRequest()->isHead()) { $this->getResponse()->setHttpResponseCode(204); } elseif ($this->getRequest()->isPost()) { //Post // We get $_FILES variable holding the formresults as xml and all possible // attachments like photo's and video's $upload = new \Zend_File_Transfer_Adapter_Http(); // We should really add some validators here see http://framework.zend.com/manual/en/zend.file.transfer.validators.html // Returns all known internal file information $files = $upload->getFileInfo(); foreach ($files as $file => $info) { // file uploaded ? if (!$upload->isUploaded($file)) { print "Why haven't you uploaded the file ?"; continue; } // validators are ok ? if (!$upload->isValid($file)) { print "Sorry but {$file} is not what we wanted"; continue; } } //Dit moet een filter worden (rename filter) http://framework.zend.com/manual/en/zend.file.transfer.filters.html $upload->setDestination($this->responseDir); //Hier moeten we denk ik eerst de xml_submission_file uitlezen, en daar //iets mee doen if ($upload->receive('xml_submission_file')) { $xmlFile = $upload->getFileInfo('xml_submission_file'); $answerXmlFile = $xmlFile['xml_submission_file']['tmp_name']; $resultId = $this->processReceivedForm($answerXmlFile); if ($resultId === false) { //form not accepted! foreach ($xml->children() as $child) { $log->log($child->getName() . ' -> ' . $child, \Zend_Log::ERR); } } else { //$log->log(print_r($files, true), \Zend_Log::ERR); //$log->log($deviceId, \Zend_Log::ERR); \MUtil_File::ensureDir($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/'); $upload->setDestination($this->responseDir . 'forms/' . (int) $this->openrosaFormID . '/'); foreach ($upload->getFileInfo() as $file => $info) { if ($info['received'] != 1) { //Rename to responseid_filename //@@TODO: move to form subdir, for better separation $upload->addFilter('Rename', $resultId . '_' . $info['name'], $file); } } //Now receive the other files if (!$upload->receive()) { $messages = $upload->getMessages(); echo implode("\n", $messages); } $this->getResponse()->setHttpResponseCode(201); //Form received ok } } } }
/** * Upload and create preview image * * @throws Mage_Core_Exception * @param string $scope the request key for file * @return bool */ public function uploadPreviewImage($scope) { $adapter = new Zend_File_Transfer_Adapter_Http(); if (!$adapter->isUploaded($scope)) { return false; } if (!$adapter->isValid($scope)) { Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Uploaded image is not valid')); } $upload = new Varien_File_Uploader($scope); $upload->setAllowCreateFolders(true); $upload->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'xbm', 'wbmp')); $upload->setAllowRenameFiles(true); $upload->setFilesDispersion(false); if (!$upload->save($this->getImagePathOrigin())) { Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Image can not be saved.')); } $fileName = $this->getImagePathOrigin() . DS . $upload->getUploadedFileName(); $this->removePreviewImage()->createPreviewImage($fileName); $this->_getIoFile()->rm($fileName); return true; }
protected function _getFormStep1() { $form = new Zend_Form(); $form->addElement('text', 'accountKey', array('label' => 'Account Key', 'required' => true)); $form->addElement('text', 'usersCount', array('label' => 'Users Count', 'required' => true, 'validators' => array('Int'))); $form->addElement('text', 'startDate', array('label' => 'Start Date', 'required' => true)); $form->addElement('text', 'endDate', array('label' => 'End Date', 'required' => true)); $form->addElement('file', 'applicationsFile', array('description' => 'allowed formats: CSV. Structure of file: Application Name (Required), ' . 'Title, Path, URL Visited', 'validators' => array(new Zend_Validate_File_Extension('csv')))); $transferAdapter = new Zend_File_Transfer_Adapter_Http(); $form->addElement('textarea', 'applications', array('attribs' => array('rows' => 4), 'description' => 'Type only applications names separated by comma. They will be added ' . 'to applications form provided file.', 'required' => !$transferAdapter->isUploaded('applicationsFile'))); $form->addDisplayGroup(array('applications', 'applicationsFile'), 'applicationsGroup', array('legend' => 'Applications')); $form->addElement('file', 'usersNamesFile', array('description' => 'allowed format: CSV. Structure of file: First Name, Last Name', 'validators' => array(new Zend_Validate_File_Extension('csv')))); $form->addElement('textarea', 'usersNames', array('attribs' => array('rows' => 4), 'description' => 'Type the first and the second names separated by comma. ' . 'If you load the file and type the names in textarea the ' . 'names will be taken from this one first.')); $form->addDisplayGroup(array('usersNames', 'usersNamesFile'), 'usersGroup', array('legend' => 'Users Names')); $form->addElement('hidden', 'step', array('value' => 2)); $form->addElement('submit', 'submit', array('label' => 'Next Step')); return $form; }
public function editarAction() { $form = new Application_Form_Produto(); $form->setAction($this->_helper->url('editar')); $request = $this->getRequest(); $dados = $this->getRequest()->getParams(); $id = $this->getRequest()->getParam('id'); $dados = $this->getRequest()->getParams(); $form->setAction($this->_helper->url('editar/id/' . $id)); /* Obtem um unico usuário através do id passado */ $produto = $this->_produto->find($id)->current(); $imagens = $this->_imagens->fetchAll("pro_id_fk='{$id}'", "ima_id DESC"); $produto->pro_tamanhos = json_decode($produto->pro_tamanhos); $this->view->categoria = $produto->cat_id_fk; $this->view->imagens = $imagens; $produto->pro_valor = number_format($produto->pro_valor, 2, ',', '.'); $form->populate($produto->toArray()); if ($request->isPost() && $form->isValid($request->getPost())) { try { $numeros = $dados["pro_tamanhos"]; foreach ($numeros as $key => $value) { $numeracao[] = $value; } $json = json_encode($numeracao); $valor = str_replace('.', '', $dados["pro_valor"]); $valor = str_replace(',', '.', $valor); $produto->pro_nome = $dados["pro_nome"]; $produto->pro_identificador = $dados["pro_identificador"]; $produto->pro_descricao = $dados["pro_descricao"]; $produto->pro_valor = $valor; $produto->cat_id_fk = $dados["select_categoria"]; $produto->pro_tamanhos = $json; $produto->pro_pontos = $dados["pro_pontos"]; $produto->save(); /** Faz o upload das imagens **/ $dir = "./uploads/produtos/"; $adapter = new Zend_File_Transfer_Adapter_Http(); try { $this->_imagens = new Application_Model_ImagensProdutos(); $form->getElement('imagens')->setDestination("{$dir}"); foreach ($adapter->getFileInfo() as $file => $info) { if ($adapter->isUploaded($file)) { $name = $adapter->getFileName($file); require_once APPLICATION_PATH . '/../library/Tokem/Functions/functions.php'; $fileName = removeAcentos($info['name']); $newFileName = strtolower(str_replace(' ', '', $fileName)); $img_nome = md5(microtime()) . '_' . $newFileName; $fname = $dir . "/" . $img_nome; $caminho = ltrim($dir, "."); $image = array("ima_nome" => "{$img_nome}", "pro_id_fk" => $id); $imagem = $this->_imagens->fetchRow("pro_id_fk='{$id}'"); if (!empty($imagem)) { unlink("../public/uploads/produtos/" . $imagem->ima_nome); $imagem->ima_nome = $img_nome; $imagem->save(); } else { $this->_imagens->insert($image); } /** * Let's inject the renaming filter */ $adapter->addFilter(new Zend_Filter_File_Rename(array('target' => $fname, 'overwrite' => true)), null, $file); /** * And then we call receive manually */ $adapter->receive($file); } } $flashMessenger = $this->_helper->FlashMessenger; $flashMessenger->addMessage(' <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Sucesso</strong> - Tudo ocorreu bem! </div> '); $this->_helper->redirector('index'); exit; } catch (Exception $e) { echo $e->getMessage(); exit; $flashMessenger = $this->_helper->FlashMessenger; $flashMessenger->addMessage('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>ERRO</strong> - Ocorreu um erro inesperado! se persistir entre em contato com o suporte! </div>'); $this->_helper->redirector('index'); exit; } /** fim do upload de imagens **/ $flashMessenger = $this->_helper->FlashMessenger; $flashMessenger->addMessage(' <div class="alert alert-success alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>Sucesso</strong> - Tudo ocorreu bem! </div> '); } catch (Zend_Db_Exception $e) { echo $e->getMessage(); exit; $flashMessenger = $this->_helper->FlashMessenger; $flashMessenger->addMessage('<div class="alert alert-danger alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> <strong>ERRO</strong> - Ocorreu um erro inesperado! se persistir entre em contato com o suporte! </div>'); } $this->_helper->redirector('index'); exit; } $this->view->form = $form; }
/** * Upgrades the specified add-on. The given file must match the specified * add-on, or an error will occur. * * @return XenForo_ControllerResponse_Abstract */ public function actionUpgrade() { $addOnId = $this->_input->filterSingle('addon_id', XenForo_Input::STRING); $addOn = $this->_getAddOnOrError($addOnId); if ($this->isConfirmedPost()) { $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; } else { $fileName = $this->_input->filterSingle('server_file', XenForo_Input::STRING); } $this->_getAddOnModel()->installAddOnXmlFromFile($fileName, $addOn['addon_id']); // ugly hack... $redirect = XenForo_Link::buildAdminLink('add-ons') . $this->getLastHash($addOnId); if (XenForo_Application::isRegistered('addOnRedirect')) { $redirect = XenForo_Application::get('addOnRedirect'); } return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, $redirect); } else { $viewParams = array('addOn' => $addOn); return $this->responseView('XenForo_ViewAdmin_AddOn_Upgrade', 'addon_upgrade', $viewParams); } }
/** * Save attribute file for given object * * @param Mage_Core_Model_Abstract $object * @return BL_FileAttributes_Model_Attribute_Backend_File */ protected function _saveAttributeFile($object) { $helper = Mage::helper('fileattributes'); $attribute = $this->getAttribute(); $value = $object->getData($attribute->getName()); $label = $attribute->getFrontendLabel(); $maxFileSize = $this->getUploadMaxFilesize(); /* Using enableHeaderCheck() on Zend "mime-type" file validators seems to be not useful, as it checks the type retrieved from Zend_File_Transfer, and Zend_File_Transfer_Adapter_Abstract::_detectMimeType() seems to not be using a different detection than those validators, actually it does just return "application/octet-stream" by default */ //$allowMimeHeaderCheck = Mage::helper('fileattributes/config')->getAllowMimeHeaderCheck(); if (is_array($value) && !empty($value['delete'])) { // Just reset value, files deletion is accessible from elsewhere if ($object->getId()) { $this->_saveObjectAttributeValue($object, ''); } else { $this->_pendingSaveObject = $object; $this->_pendingSaveValue = ''; } return $this; } $upload = new Zend_File_Transfer_Adapter_Http(); $file = $attribute->getName(); try { $origData = $object->getOrigData(); $origFile = isset($origData[$file]) ? $origData[$file] : null; $newFile = is_array($value) ? $value['value'] : $value; if (!$upload->isUploaded($file) && (!$attribute->getIsRequired() || $newFile == $origFile)) { // No need to go further return $this; } $fileInfo = $upload->getFileInfo($file); $fileInfo = $fileInfo[$file]; $fileInfo['title'] = $fileInfo['name']; } catch (Exception $e) { // Upload error if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] < $maxFileSize) { $size = Mage::helper('fileattributes')->getFileSizeForDisplay($maxFileSize, 2); Mage::throwException($helper->__('The file you uploaded for "%s" attribute is larger than the %s allowed by server', $label, $size)); } else { Mage::throwException($helper->__('An error occured during file upload for "%s" attribute', $label)); } } $config = Mage::helper('fileattributes/config')->getAttributeConfiguration($attribute->getId()); // Validation for MIME types if (isset($config['allowed_mime_types']) && is_array($validate = $config['allowed_mime_types'])) { $upload->addValidator('MimeType', false, array_keys($validate)); //$upload->getValidator('MimeType')->enableHeaderCheck($allowMimeHeaderCheck); } elseif (isset($config['forbidden_mime_types']) && is_array($validate = $config['forbidden_mime_types'])) { $upload->addValidator('ExcludeMimeType', false, array_keys($validate)); //$upload->getValidator('ExcludeMimeType')->enableHeaderCheck($allowMimeHeaderCheck); } // Validation for image-only flag if (isset($config['image_only']) && $config['image_only']) { $upload->addValidator('IsImage', false); //$upload->getValidator('IsImage')->enableHeaderCheck($allowMimeHeaderCheck); } // Validation for image dimensions $validate = array(); if ($config['image_min_width'] > 0) { $validate['minwidth'] = $config['image_min_width']; } if ($config['image_max_width'] > 0) { $validate['maxwidth'] = $config['image_max_width']; } if ($config['image_min_height'] > 0) { $validate['minheight'] = $config['image_min_height']; } if ($config['image_max_height'] > 0) { $validate['maxheight'] = $config['image_max_height']; } if (count($validate) > 0) { $upload->addValidator('ImageSize', false, $validate); } // Validation for file extensions if (isset($config['allowed_file_extensions']) && is_array($validate = $config['allowed_file_extensions'])) { $upload->addValidator('Extension', false, $validate); } elseif (isset($config['forbidden_file_extensions']) && is_array($validate = $config['forbidden_file_extensions'])) { $upload->addValidator('ExcludeExtension', false, $validate); } // Validation for maximum filesize (take the smallest between config and server ones) $validate = $config['file_max_size'] > 0 ? min($config['file_max_size'], $maxFileSize) : $maxFileSize; $upload->addValidator('FilesSize', false, array('max' => $validate)); // Let's upload (if possible) ! if ($upload->isUploaded($file) && $upload->isValid($file)) { try { $uploader = new Varien_File_Uploader($attribute->getName()); $uploader->setAllowCreateFolders(true)->setAllowRenameFiles(true)->setFilesDispersion(false); if (!$uploader->save($this->getTargetDir())) { Mage::throwException($helper->__('File "%s" upload failed for "%s" attribute', $fileInfo['name'], $label)); } if ($object->getId()) { $this->_saveObjectAttributeValue($object, $uploader->getUploadedFileName()); } else { $this->_pendingSaveObject = $object; $this->_pendingSaveValue = $uploader->getUploadedFileName(); } } catch (Exception $e) { Mage::throwException($helper->__('An error occured during file "%s" upload for "%s" attribute : "%s"', $fileInfo['name'], $label, $e->getMessage())); } } elseif (($errors = $upload->getErrors()) && ($errors = $this->_parseValidatorErrors($errors, $fileInfo, $label)) && count($errors) > 0) { // Known upload error(s) Mage::throwException(implode("<br />", $errors)); } else { // Unknown or not handled upload error Mage::throwException($helper->__('You must upload a valid file for "%s" attribute', $label)); } }
public function actionImport() { $this->_assertPostOnly(); $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; } else { $fileName = $this->_input->filterSingle('server_file', XenForo_Input::STRING); } if (!file_exists($fileName) || !is_readable($fileName)) { throw new XenForo_Exception(new XenForo_Phrase('please_enter_valid_file_name_requested_file_not_read'), true); } $file = BBM_Helper_Bbm::scanXmlFile($fileName); if ($file->getName() != 'bbm_bbcodes') { throw new XenForo_Exception(new XenForo_Phrase('bbm_xml_invalid'), true); } $BbCodes = count($file->BbCode); $overrideOption = $this->_input->filterSingle('bbm_override', XenForo_Input::STRING); if ($BbCodes == 1) { $code = $this->_getImportValues($file->BbCode); if (!isset($code['tag'])) { throw new XenForo_Exception(new XenForo_Phrase('bbm_xml_invalid'), true); } if (is_array($this->_getBbmBbCodeModel()->getBbCodeByTag($code['tag']))) { $viewParams = array('code' => $code, 'xml' => $file->asXML()); return $this->responseView('Bbm_ViewAdmin_Bbm_BbCode_Import_Override', 'bbm_bb_codes_import_override', $viewParams); } $dw = XenForo_DataWriter::create('BBM_DataWriter_BbCodes'); $dw->bulkSet($code); $dw->save(); //Update simple cache $this->_getBbmBbCodeModel()->simplecachedActiveBbCodes(); return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildAdminLink('bbm-bbcodes')); } else { $new = array(); $updated = array(); $notupdated = array(); foreach ($file->BbCode as $BbCode) { $code = $this->_getImportValues($BbCode); if (!isset($code['tag'])) { throw new XenForo_Exception(new XenForo_Phrase('bbm_xml_invalid'), true); } if (is_array($this->_getBbmBbCodeModel()->getBbCodeByTag($code['tag'])) && !$overrideOption) { $notupdated[] = $code['tag']; continue; } $dw = XenForo_DataWriter::create('BBM_DataWriter_BbCodes'); if (is_array($this->_getBbmBbCodeModel()->getBbCodeByTag($code['tag'])) && $overrideOption) { $updated[] = $code['tag']; $tag = $code['tag']; $tagId = $this->_getBbmBbCodeModel()->getBbCodeIdFromTag($tag); if ($this->_getBbmBbCodeModel()->getBbCodeById($tagId)) { $dw->setExistingData($tagId); $this->_getBbmButtonsModel()->addUpdateButtonInAllConfigs($code); } $dw->bulkSet($code); $dw->save(); } else { $new[] = $code['tag']; $dw->bulkSet($code); $dw->save(); } } //Update simple cache $this->_getBbmBbCodeModel()->simplecachedActiveBbCodes(); $viewParams = array('new' => $new, 'updated' => $updated, 'notupdated' => $notupdated); return $this->responseView('Bbm_ViewAdmin_Bulk_Import_Results', 'bbm_bb_codes_import_results', $viewParams); } }
public function actionThumb() { $this->_assertPostOnly(); $mediaID = $this->_input->filterSingle('media_id', XenForo_Input::UINT); if (!($media = $this->getModelFromCache('EWRmedio_Model_Media')->getMediaByID($mediaID))) { return $this->responseRedirect(XenForo_ControllerResponse_Redirect::RESOURCE_CANONICAL_PERMANENT, XenForo_Link::buildPublicLink('media')); } if (!$this->perms['mod'] && $media['user_id'] !== XenForo_Visitor::getUserId()) { return $this->responseNoPermission(); } $fileTransfer = new Zend_File_Transfer_Adapter_Http(); if ($fileTransfer->isUploaded('upload_file')) { $fileInfo = $fileTransfer->getFileInfo('upload_file'); $fileName = $fileInfo['upload_file']['tmp_name']; $this->getModelFromCache('EWRmedio_Model_Thumbs')->buildThumb($media['media_id'], $fileName); } return $this->responseRedirect(XenForo_ControllerResponse_Redirect::SUCCESS, XenForo_Link::buildPublicLink('media/edit', $media)); }
/** * Validate uploaded file * * @throws Mage_Core_Exception * @return Mage_Catalog_Model_Product_Option_Type_File */ protected function _validateUploadedFile() { $option = $this->getOption(); $processingParams = $this->_getProcessingParams(); /** * Upload init */ $upload = new Zend_File_Transfer_Adapter_Http(); $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file'; $maxFileSize = $this->getFileSizeService()->getMaxFileSize(); try { $runValidation = $option->getIsRequire() || $upload->isUploaded($file); if (!$runValidation) { $this->setUserValue(null); return $this; } $fileInfo = $upload->getFileInfo($file); $fileInfo = $fileInfo[$file]; $fileInfo['title'] = $fileInfo['name']; } catch (Exception $e) { // when file exceeds the upload_max_filesize, $_FILES is empty if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $maxFileSize) { $this->setIsValid(false); $value = $this->getFileSizeService()->getMaxFileSizeInMb(); Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__("The file you uploaded is larger than %s Megabytes allowed by server", $value)); } else { switch ($this->getProcessMode()) { case Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL: Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Please specify the product\'s required option(s).')); break; default: $this->setUserValue(null); break; } return $this; } } /** * Option Validations */ // Image dimensions $_dimentions = array(); if ($option->getImageSizeX() > 0) { $_dimentions['maxwidth'] = $option->getImageSizeX(); } if ($option->getImageSizeY() > 0) { $_dimentions['maxheight'] = $option->getImageSizeY(); } if (count($_dimentions) > 0) { $upload->addValidator('ImageSize', false, $_dimentions); } // File extension $_allowed = $this->_parseExtensionsString($option->getFileExtension()); if ($_allowed !== null) { $upload->addValidator('Extension', false, $_allowed); } else { $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions')); if ($_forbidden !== null) { $upload->addValidator('ExcludeExtension', false, $_forbidden); } } // Maximum filesize $upload->addValidator('FilesSize', false, array('max' => $maxFileSize)); /** * Upload process */ $this->_initFilesystem(); if ($upload->isUploaded($file) && $upload->isValid($file)) { $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION); $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($fileInfo['name']); $dispersion = Mage_Core_Model_File_Uploader::getDispretionPath($fileName); $filePath = $dispersion; $fileHash = md5($this->_filesystem->read($fileInfo['tmp_name'])); $filePath .= DS . $fileHash . '.' . $extension; $fileFullPath = $this->getQuoteTargetDir() . $filePath; $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true)); $this->getProduct()->getTypeInstance()->addFileQueue(array('operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this)); $_width = 0; $_height = 0; if ($this->_filesystem->isReadable($fileInfo['tmp_name'])) { $_imageSize = getimagesize($fileInfo['tmp_name']); if ($_imageSize) { $_width = $_imageSize[0]; $_height = $_imageSize[1]; } } $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20))); } elseif ($upload->getErrors()) { $errors = $this->_getValidatorErrors($upload->getErrors(), $fileInfo); if (count($errors) > 0) { $this->setIsValid(false); Mage::throwException(implode("\n", $errors)); } } else { $this->setIsValid(false); Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('Please specify the product required option(s)')); } return $this; }
/** * Store uploaded file in proper directory for module/page * * $params = array( * 'field' => 'form field name' * 'dir' => 'subdirectory for this file' * 'extensions' => array('jpg','png' ...) * 'mimetypes' => array('image/jpg', 'image/png') * ) * * @param array $params * @return string|false */ public function upload(array $params) { //check dir path $dir = $params['dir']; $paths = $this->getPath($dir); if ($paths === false) { $this->_lastErrorMessage = "Invalid dir [{$dir}]"; return false; } if (!isset($params['field'])) { $this->_lastErrorMessage = "Field not specifield"; return false; } $fieldName = $params['field']; $freeSpace = $this->getFreeSpace(); $extensions = array(); $mimeTypes = array(); //valid extensions if (isset($params['extensions']) && is_array($params['extensions'])) { $extensions = $params['extensions']; } //valid mime types if (isset($params['mimetypes']) && is_array($params['mimetypes'])) { $mimeTypes = $params['mimetypes']; } try { $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->addValidator("Count", false, array("min" => 1, "max" => 5))->addValidator("Size", false, array("max" => $freeSpace))->addValidator("Extension", false, $extensions)->addValidator('MimeType', false, $mimeTypes); $adapter->setDestination($paths['real']); $files = $adapter->getFileInfo(); $result = array(); foreach ($files as $file => $info) { // file uploaded ? if (!$adapter->isUploaded($info['name']) || !$adapter->isValid($info['name'])) { $this->_lastErrorMessage = implode(" ", $adapter->getMessages()); continue; } if (strpos($file, $fieldName) !== 0) { continue; } if ($adapter->receive($info["name"])) { $result[] = $dir . "/" . $info["name"]; } } if (count($result)) { return $result; } else { if ($this->_lastErrorMessage == '') { $this->_lastErrorMessage = "No files uploaded"; } else { $this->_lastErrorMessage .= ". No files uploaded"; } return false; } } catch (Exception $ex) { $this->_lastErrorMessage = $ex->getMessage(); return false; } }