public function saveFile($file) { $rep_dest = "../var/uploads/"; $upload = new upload($file); $upload->file_overwrite = true; //supprime le fichier si existe if ($upload->uploaded) { //file $upload->file_new_name_body = uniqid(); $upload->Process($rep_dest); $upload->clean(); return $rep_dest . $upload->file_dst_name; } return null; }
/** * Efetua upload de arquivos. * * @param array $file Arquivo da variável $_FILES['somefile'] * @param string $where Caminho absoluto para onde salvar o arquivo, ex.: FILES_PATH . '/somewhere' * @param string $exitFilename Nome do arquivo no final do processo de upload * @param array $allowedExt Lista de extenssoes permitidas para o upload * @return \stdClass * @throws Exception */ public function uploadFile($file, $where, $exitFilename = null, array $allowedExt = array('jpeg', 'jpg', 'pdf', 'png', 'gif')) { $result = new \stdClass(); $result->filename = ""; $result->pathAndFilename = ""; $result->fileExt = ""; $upload = new \upload($file); if ($upload->uploaded) { // Formatos Aceitos (Extensoes) if (in_array($upload->file_src_name_ext, $allowedExt)) { // Formatos Aceitos (Mimetypes) $upload->allowed = array('image/jpg', 'image/pjpeg', 'image/jpeg', 'image/png', 'image/gif', 'application/x-zip-compressed', 'application/pdf', 'application/download', 'application/applefile'); $upload->Process($where); // Upload deu tudo certo? if ($upload->processed) { // Define resultado $result->fileExt = $upload->file_src_name_ext; $result->filename = $upload->file_dst_name; $result->pathAndFilename = $where . $upload->file_dst_name; // Permissao total no arquivo chmod($result->pathAndFilename, 0777); // Se for para mudar o nome do arquivo de saida if ($exitFilename) { // Renomeia if (!rename($result->pathAndFilename, $where . $exitFilename . '.' . $upload->file_src_name_ext)) { throw new Exception("Não foi possível mover o arquivo '{$result->pathAndFilename}'"); } $result->filename = $exitFilename . '.' . $upload->file_src_name_ext; $result->pathAndFilename = $where . $exitFilename . '.' . $upload->file_src_name_ext; } } else { throw new \Exception($upload->error); } } else { throw new \Exception("Extenssão inválida"); } } else { throw new \Exception($upload->error); } return $result; }
function install() { $rep = $this->getResponse('json'); $this->msg = "installation échouée"; if (isset($_FILES["archive"])) { $rep_dest = "var/uploads/"; $upload = new upload($_FILES["archive"]); $upload->file_overwrite = true; //supprime le file si existe $upload->allowed = array('application/zip'); if ($upload->uploaded) { // It could be something like $upload->Process('www/my_uploads/'); $upload->Process($rep_dest); //extraction de larchive $zip = new ZipArchive(); $zip->open($upload->file_dst_pathname); // if (!$zip->getFromName('module.xml')) { //if module file doesnt exists $this->msg = "installation échouée: fichier d'installation absent"; } else { $moduleXml = simplexml_load_string($zip->getFromName('module.xml')); //verifiying the compatibility with jelix core version if ($this->compatibility($moduleXml->dependencies->jelix)) { $zip->extractTo('modules/' . $moduleXml->info['name'] . '/'); //we extract to module directory $this->setConfig($moduleXml->info['name']); //set module config $this->installScript($moduleXml->info['name']); //$this->showOnMenu($moduleXml->info['name']); $this->msg = "module installé"; $this->success = true; } else { $this->success = false; $this->msg = "module non installé : versions non compatibles"; } } $zip->close(); //close archive $upload->clean(); //clean server temp unlink($upload->file_dst_pathname); //clean second app temp } } $rep->data = array('success' => $this->success, 'msg' => $this->msg); return $rep; }
public static function updateConfigEmpreendimento() { $EmpreendimentoTO = new EmpreendimentoTO(); $EmpreendimentoDao = new EmpreendimentoDao(); $EmpreendimentoTO->id = isset($_POST['id']) ? $_POST['id'] : NULL; $EmpreendimentoTO->nome_empreendimento = isset($_POST['nome_empreendimento']) ? $_POST['nome_empreendimento'] : NULL; $EmpreendimentoTO->nickname = isset($_POST['nickname']) ? $_POST['nickname'] : NULL; $EmpreendimentoTO->dsc_empreendimento = isset($_POST['dsc_empreendimento']) ? $_POST['dsc_empreendimento'] : NULL; $EmpreendimentoTO->url_facebook = isset($_POST['url_facebook']) ? $_POST['url_facebook'] : NULL; $EmpreendimentoTO->url_twitter = isset($_POST['url_twitter']) ? $_POST['url_twitter'] : NULL; $EmpreendimentoTO->url_google_plus = isset($_POST['url_google_plus']) ? $_POST['url_google_plus'] : NULL; $EmpreendimentoTO->url_linkedin = isset($_POST['url_linkedin']) ? $_POST['url_linkedin'] : NULL; $EmpreendimentoTO->url_pinterest = isset($_POST['url_pinterest']) ? $_POST['url_pinterest'] : NULL; $EmpreendimentoTO->nme_logo = isset($_POST['nme_logo']) ? $_POST['nme_logo'] : NULL; $EmpreendimentoTO->end_email_contato = isset($_POST['end_email_contato']) ? $_POST['end_email_contato'] : NULL; $EmpreendimentoTO->num_telefone = isset($_POST['num_telefone']) ? $_POST['num_telefone'] : NULL; $EmpreendimentoTO->num_cnpj = isset($_POST['num_cnpj']) ? $_POST['num_cnpj'] : NULL; $EmpreendimentoTO->num_inscricao_estadual = isset($_POST['num_inscricao_estadual']) ? $_POST['num_inscricao_estadual'] : NULL; $EmpreendimentoTO->num_inscricao_municipal = isset($_POST['num_inscricao_municipal']) ? $_POST['num_inscricao_municipal'] : NULL; $EmpreendimentoTO->nme_razao_social = isset($_POST['nme_razao_social']) ? $_POST['nme_razao_social'] : NULL; $EmpreendimentoTO->nme_fantasia = isset($_POST['nme_fantasia']) ? $_POST['nme_fantasia'] : NULL; $EmpreendimentoTO->num_cep = isset($_POST['num_cep']) ? $_POST['num_cep'] : NULL; $EmpreendimentoTO->nme_logradouro = isset($_POST['nme_logradouro']) ? $_POST['nme_logradouro'] : NULL; $EmpreendimentoTO->num_logradouro = isset($_POST['num_logradouro']) ? $_POST['num_logradouro'] : NULL; $EmpreendimentoTO->nme_bairro_logradouro = isset($_POST['nme_bairro_logradouro']) ? $_POST['nme_bairro_logradouro'] : NULL; $EmpreendimentoTO->cod_estado = isset($_POST['cod_estado']) ? $_POST['cod_estado'] : NULL; $EmpreendimentoTO->cod_cidade = isset($_POST['cod_cidade']) ? $_POST['cod_cidade'] : NULL; $EmpreendimentoTO->num_percentual_credito_simples = isset($_POST['num_percentual_credito_simples']) ? $_POST['num_percentual_credito_simples'] : NULL; $EmpreendimentoTO->flg_contribuinte_icms = isset($_POST['flg_contribuinte_icms']) ? (int) $_POST['flg_contribuinte_icms'] : NULL; $EmpreendimentoTO->flg_contribuinte_ipi = isset($_POST['flg_contribuinte_ipi']) ? (int) $_POST['flg_contribuinte_ipi'] : NULL; $EmpreendimentoTO->num_inscricao_estadual_st = isset($_POST['num_inscricao_estadual_st']) ? $_POST['num_inscricao_estadual_st'] : NULL; $EmpreendimentoTO->cod_regime_tributario = isset($_POST['cod_regime_tributario']) && is_numeric($_POST['cod_regime_tributario']) ? $_POST['cod_regime_tributario'] : NULL; $EmpreendimentoTO->cod_regime_pis_cofins = isset($_POST['cod_regime_pis_cofins']) && is_numeric($_POST['cod_regime_pis_cofins']) ? $_POST['cod_regime_pis_cofins'] : NULL; $EmpreendimentoTO->cod_tipo_empresa = isset($_POST['cod_tipo_empresa']) && is_numeric($_POST['cod_tipo_empresa']) ? $_POST['cod_tipo_empresa'] : NULL; $EmpreendimentoTO->cod_zoneamento = isset($_POST['cod_zoneamento']) && is_numeric($_POST['cod_zoneamento']) ? $_POST['cod_zoneamento'] : NULL; $Validator = new DataValidator(); $Validator->set_msg('O nome do empreendimento é obrigatório')->set('nome_empreendimento', $EmpreendimentoTO->nome_empreendimento)->is_required(); $Validator->set_msg('O ID do empreendimento é obrigatório')->set('id', $EmpreendimentoTO->id)->is_required(); $Validator->set_msg('O nickname do empreendimento é obrigatório')->set('nickname', $EmpreendimentoTO->nickname)->is_required(); if (isset($_FILES['nme_logo'])) { $status_upload = false; $handle = new upload($_FILES['nme_logo']); $handle->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png'); list($width, $height) = getimagesize($_FILES['nme_logo']['tmp_name']); if (!($width >= 118 && $height >= 36)) { $Validator->_errors['nme_logo'][] = 'O Tamanho da imagem deve ser igual ou superior a 118x36. Está imagem tem ' . $width . "x" . $height; } else { if ($handle->uploaded) { $handle->Process(CAMINHO_UPLOAD_IMG_LOGO); if ($handle->processed) { $status_upload = true; $EmpreendimentoTO->nme_logo = $handle->file_dst_name; } } if (!$status_upload) { if ($handle->error == 'Incorrect type of file') { $Validator->_errors['nme_logo'][] = 'O formato da imagem deve ser jpeg, jpg ou gif'; } else { Flight::halt(500, 'Ocorreu um erro ao fazer o upload da imagem ' . $handle->error); } } } } if (!$Validator->validate()) { Flight::response()->status(406)->header('Content-Type', 'application/json')->write(json_encode($Validator->get_errors()))->send(); return; } if ($EmpreendimentoDao->updateConfigEmpreendimento($EmpreendimentoTO)) { $inscricoes_estaduais = isset($_POST['inscricoes_estaduais']) ? $_POST['inscricoes_estaduais'] : array(); $ids_not_delete = array(); foreach ($inscricoes_estaduais as $key => $value) { $InscricaoEstadualDao = new InscricaoEstadualDao(); $InscricaoEstadual = new stdClass(); $InscricaoEstadual->id_empreendimento = $value['id_empreendimento']; $InscricaoEstadual->num_inscricao_estadual = $value['num_inscricao_estadual']; $InscricaoEstadual->num_inscricao_estadual_st = $value['num_inscricao_estadual_st']; $InscricaoEstadual->uf = $value['uf']; if (!(isset($value['id']) && $value['id'])) { $InscricaoEstadualTO = new InscricaoEstadualTO(); $InscricaoEstadualTO->__setAll($value); $ids_not_delete[] = $InscricaoEstadualDao->save($InscricaoEstadualTO); } else { $ids_not_delete[] = $value['id']; $InscricaoEstadualDao->updateInscricao($InscricaoEstadual, 'id=' . $value['id']); } } $InscricaoEstadualDao->deleteInscricao('id_empreendimento = ' . $EmpreendimentoTO->id . ' AND id NOT IN(' . join(',', $ids_not_delete) . ')'); Flight::halt(200); } else { Flight::halt(500, 'erro ao atualizar empreendimento'); } }
public static function updateProduto() { $ProdutoTO = new ProdutoTO(); $ProdutoDao = new ProdutoDao(); $validator = new DataValidator(); $ProdutoTO->id = isset($_POST["id"]) ? $_POST["id"] : NULL; $ProdutoTO->meta_title = isset($_POST["meta_title"]) ? $_POST["meta_title"] : NULL; $ProdutoTO->meta_description = isset($_POST["meta_description"]) ? $_POST["meta_description"] : NULL; $ProdutoTO->descricao_curta = isset($_POST["descricao_curta"]) ? $_POST["descricao_curta"] : NULL; $ProdutoTO->img = isset($_POST["img"]) ? $_POST["img"] : NULL; $ProdutoTO->codigo_barra = isset($_POST["codigo_barra"]) ? $_POST["codigo_barra"] : NULL; $ProdutoTO->nome = isset($_POST["nome"]) ? $_POST["nome"] : NULL; $ProdutoTO->sabor = isset($_POST["sabor"]) ? $_POST["sabor"] : NULL; $ProdutoTO->peso = isset($_POST["peso"]) ? $_POST["peso"] : NULL; $ProdutoTO->valor_desconto_cliente = isset($_POST["valor_desconto_cliente"]) && !empty($_POST["valor_desconto_cliente"]) ? $_POST["valor_desconto_cliente"] : 0; $ProdutoTO->id_fabricante = isset($_POST["id_fabricante"]) && !empty($_POST["id_fabricante"]) ? $_POST["id_fabricante"] : NULL; $ProdutoTO->id_importador = isset($_POST["id_importador"]) && !empty($_POST["id_importador"]) ? $_POST["id_importador"] : NULL; $ProdutoTO->id_categoria = isset($_POST["id_categoria"]) && !empty($_POST["id_categoria"]) ? $_POST["id_categoria"] : NULL; $ProdutoTO->qtd_minima_estoque = isset($_POST["qtd_minima_estoque"]) ? $_POST["qtd_minima_estoque"] : NULL; $ProdutoTO->descricao = isset($_POST["descricao"]) ? $_POST["descricao"] : NULL; $ProdutoTO->flg_produto_composto = isset($_POST["flg_produto_composto"]) ? $_POST["flg_produto_composto"] : 0; $ProdutoTO->id_tamanho = isset($_POST["id_tamanho"]) && is_numeric($_POST["id_tamanho"]) && (int) $_POST["id_tamanho"] > 0 ? $_POST["id_tamanho"] : NULL; $ProdutoTO->id_cor = isset($_POST["id_cor"]) && is_numeric($_POST["id_cor"]) && (int) $_POST["id_cor"] > 0 ? $_POST["id_cor"] : NULL; $ProdutoTO->cod_ncm = isset($_POST["cod_ncm"]) && is_numeric($_POST["cod_ncm"]) ? $_POST["cod_ncm"] : NULL; $ProdutoTO->ex_tipi = isset($_POST["ex_tipi"]) && is_numeric($_POST["ex_tipi"]) ? $_POST["ex_tipi"] : NULL; $ProdutoTO->cod_especializacao_ncm = isset($_POST["cod_especializacao_ncm"]) && is_numeric($_POST["cod_especializacao_ncm"]) ? $_POST["cod_especializacao_ncm"] : NULL; $ProdutoTO->cod_forma_aquisicao = isset($_POST["cod_forma_aquisicao"]) && is_numeric($_POST["cod_forma_aquisicao"]) ? $_POST["cod_forma_aquisicao"] : NULL; $ProdutoTO->cod_origem_mercadoria = isset($_POST["cod_origem_mercadoria"]) && is_numeric($_POST["cod_origem_mercadoria"]) ? $_POST["cod_origem_mercadoria"] : NULL; $ProdutoTO->cod_tipo_tributacao_ipi = isset($_POST["cod_tipo_tributacao_ipi"]) && is_numeric($_POST["cod_tipo_tributacao_ipi"]) ? $_POST["cod_tipo_tributacao_ipi"] : NULL; $ProdutoTO->cod_regra_tributos = isset($_POST["cod_regra_tributos"]) && is_numeric($_POST["cod_regra_tributos"]) ? $_POST["cod_regra_tributos"] : NULL; $ProdutoTO->num_cest = isset($_POST["num_cest"]) && is_numeric($_POST["num_cest"]) ? $_POST["num_cest"] : NULL; $ProdutoTO->dsc_unidade_medida = isset($_POST["dsc_unidade_medida"]) ? $_POST["dsc_unidade_medida"] : NULL; $id_empreendimento = isset($_POST['id_empreendimento']) ? $_POST['id_empreendimento'] : ""; $precos = isset($_POST['precos']) && is_array($_POST['precos']) ? $_POST['precos'] : array(); $fornecedores = isset($_POST['fornecedores']) && is_array($_POST['fornecedores']) ? $_POST['fornecedores'] : array(); $empreendimentos = isset($_POST['empreendimentos']) && is_array($_POST['empreendimentos']) ? $_POST['empreendimentos'] : array(); $del_empreendimentos = isset($_POST['del_empreendimentos']) && is_array($_POST['del_empreendimentos']) ? $_POST['del_empreendimentos'] : array(); $insumos = isset($_POST['insumos']) && is_array($_POST['insumos']) ? $_POST['insumos'] : array(); $categorias = isset($_POST['categorias']) && is_array($_POST['categorias']) ? $_POST['categorias'] : array(); if ($ProdutoTO->flg_produto_composto == 1) { if (!(isset($insumos) && is_array($insumos) && count($insumos) > 0)) { $validator->_errors['insumos'][] = 'É obrigatório informar ao menos um insumo para compor o produto'; } } /* $validator->set_msg('O ID do produto é obrigatório') ->set('id',$ProdutoTO->id) ->is_required(); $validator->set_msg('O codigo do empreendimento é obrigatório') ->set('id_empreendimento',$id_empreendimento) ->is_required(); $validator->set_msg('O codigo de barra do produto é obrigatório') ->set('codigo_barra',$ProdutoTO->codigo_barra) ->is_required(); $validator->set_msg('O nome do produto é obrigatório') ->set('nome',$ProdutoTO->nome) ->is_required(); $validator->set_msg('O sabor do produto é obrigatório') ->set('sabor',$ProdutoTO->sabor) ->is_required(); $validator->set_msg('O peso do produto é obrigatório') ->set('peso',$ProdutoTO->peso) ->is_required(); $validator->set_msg('O fabricante do produto é obrigatório') ->set('id_fabricante',$ProdutoTO->id_fabricante) ->is_required(); $validator->set_msg('O importador do produto é obrigatório') ->set('id_importador',$ProdutoTO->id_importador) ->is_required(); $validator->set_msg('A categoria do produto é obrigatório') ->set('id_categoria',$ProdutoTO->id_categoria) ->is_required(); $validator->set_msg('A quantidade minina do produto é obrigatório') ->set('qtd_minima_estoque',$ProdutoTO->qtd_minima_estoque) ->is_required(); if(!(isset($fornecedores) && is_array($fornecedores) && count($fornecedores) > 0)){ $validator->_errors['fornecedores'][] = 'É obrigatório informar pelo menos um fornecedor'; } $preco['vlr_custo'] = isset($preco['vlr_custo']) ? $preco['vlr_custo'] : 0 ; $preco['perc_imposto_compra'] = isset($preco['perc_imposto_compra']) ? $preco['perc_imposto_compra'] : 0 ; $preco['perc_desconto_compra'] = isset($preco['perc_desconto_compra']) ? $preco['perc_desconto_compra'] : 0 ; $preco['perc_venda_atacado'] = isset($preco['perc_venda_atacado']) ? $preco['perc_venda_atacado'] : 0 ; $preco['perc_venda_varejo'] = isset($preco['perc_venda_varejo']) ? $preco['perc_venda_varejo'] : 0 ; $preco['perc_venda_intermediario'] = isset($preco['perc_venda_intermediario']) ? $preco['perc_venda_intermediario'] : 0 ; $validator->set_msg('O valor de tabela é obrigatório') ->set('vlr_custo',$preco['vlr_custo']) ->is_required(); */ if (!(isset($empreendimentos) && is_array($empreendimentos) && count($empreendimentos) > 0)) { $validator->_errors['empreendimentos'][] = 'É obrigatório vincular o produto pelo menos a um empreendimento'; } $new_image = false; if (isset($_FILES['img'])) { $ProdutoTO->img = NULL; $status_upload = false; $handle = new upload($_FILES['img']); $handle->allowed = array('image/jpeg', 'image/jpg'); if ($handle->uploaded) { $handle->Process(CAMINHO_UPLOAD_IMG_PRODUTO); if ($handle->processed) { $status_upload = true; $ProdutoTO->img = $handle->file_dst_name; $new_image = CAMINHO_UPLOAD_IMG_PRODUTO . $handle->file_dst_name; } } if (!$status_upload) { if ($handle->error == 'Incorrect type of file') { $validator->_errors['img'][] = 'O formato da imagem deve ser jpeg ou jpg'; } else { Flight::halt(500, 'Ocorreu um erro ao fazer o upload da imagem ' . $handle->error); } } } $ProdutoTO->nme_arquivo_nutricional = NULL; if (isset($_FILES['arquivo-produto'])) { $status_upload_file = false; $handle = new upload($_FILES['arquivo-produto']); if ($handle->uploaded) { $handle->Process(CAMINHO_UPLOAD_FILE_PRODUTO); if ($handle->processed) { $status_upload_file = true; $ProdutoTO->nme_arquivo_nutricional = $handle->file_dst_name; } } if (!$status_upload_file) { Flight::halt(500, 'Ocorreu um erro ao fazer o upload do arquivo nutricional' . $handle->error); } } if (!$validator->validate()) { Flight::response()->status(406)->header('Content-Type', 'application/json')->write(json_encode($validator->get_errors()))->send(); return; } if (!$ProdutoDao->updateProduto($ProdutoTO)) { Flight::halt(500, 'erro ao atualizar pro'); } if ((int) $ProdutoTO->flg_produto_composto == 1) { $ProdutoDao->delInsumos($ProdutoTO->id); if (!$ProdutoDao->insertProdutoInsumo($ProdutoTO->id, $insumos)) { Flight::halt(500, 'Erro ao cadastrar o insumos'); } } $ProdutoCategoriaDao = new ProdutoCategoriaDao(); $ProdutoCategoriaDao->delCategorias($ProdutoTO->id); if (!$ProdutoCategoriaDao->insertProdutoCategorias($ProdutoTO->id, $categorias)) { Flight::halt(500, 'Erro ao cadastrar categorias'); } foreach ($del_empreendimentos as $key => $empreendimento) { if (isset($empreendimento['id_produto']) && isset($empreendimento['id_empreendimento'])) { $ProdutoDao->deleteEmpreendimentoProduto($empreendimento['id_produto'], $empreendimento['id_empreendimento']); } } foreach ($empreendimentos as $key => $empreendimento) { if (!isset($empreendimento['id']) || empty($empreendimento['id'])) { $ProdutoEmpreendimentoTO = new ProdutoEmpreendimentoTO(); $ProdutoEmpreendimentoTO->id_produto = $ProdutoTO->id; $ProdutoEmpreendimentoTO->id_empreendimento = $empreendimento['id_empreendimento']; if (!$ProdutoDao->produtoEmpreendimento($ProdutoEmpreendimentoTO)) { Flight::halt(500, 'Erro ao cadastrar o id_empreendimento'); } } } foreach ($precos as $preco) { $PrecoProdutoTO = new PrecoProdutoTO(); $PrecoProdutoDao = new PrecoProdutoDao(); $PrecoProdutoTO->id_produto = $ProdutoTO->id; $PrecoProdutoTO->id_empreendimento = $preco['id_empreendimento']; $PrecoProdutoTO->vlr_custo = $preco['vlr_custo']; $PrecoProdutoTO->perc_imposto_compra = $preco['perc_imposto_compra']; $PrecoProdutoTO->perc_desconto_compra = $preco['perc_desconto_compra']; $PrecoProdutoTO->perc_venda_atacado = $preco['perc_venda_atacado']; $PrecoProdutoTO->perc_venda_intermediario = $preco['perc_venda_intermediario']; $PrecoProdutoTO->perc_venda_varejo = $preco['perc_venda_varejo']; if ($preco['id_empreendimento'] == $id_empreendimento) { $preco_emp_current = $preco; } if (!$PrecoProdutoDao->atualizaPreco($PrecoProdutoTO)) { Flight::halt(500, 'erro ao atualizar preço'); } } $ProdutoFornecedorTO = new ProdutoFornecedorTO(); $ProdutoDao->delAllFornecedor($ProdutoTO->id); foreach ($fornecedores as $key => $value) { $ProdutoFornecedorTO->id_produto = $ProdutoTO->id; $ProdutoFornecedorTO->id_fornecedor = $value['id_fornecedor']; if (!$ProdutoDao->fornecedorProduto($ProdutoFornecedorTO)) { Flight::halt(500, 'Erro ao cadastrar o produto'); } } $InventarioController = new InventarioController(); $inventario = isset($_POST['inventario']) ? $_POST['inventario'] : array(); if (is_array($inventario) && count($inventario) > 0) { $InventarioController->salveInventarioSimples($inventario, $id_empreendimento); } $valor_campo_extra = isset($_POST['valor_campo_extra']) ? $_POST['valor_campo_extra'] : array(); if (is_array($valor_campo_extra) && count($valor_campo_extra) > 0) { $CampoExtraProdutoDao = new CampoExtraProdutoDao(); $CampoExtraProdutoDao->save($id_empreendimento, $_POST['id'], $valor_campo_extra); } $ProdutoCombinacaoDao = new ProdutoCombinacaoDao(); $produtos_combinacoes = isset($_POST['combinacoes']) && is_array($_POST['combinacoes']) ? $_POST['combinacoes'] : array(); $combinacoes = array(); foreach ($produtos_combinacoes as $produto_combinacao) { if (!isset($produto_combinacao['id_produto']) || $produto_combinacao['id_produto'] != $produto_combinacao['id_combinacao']) { if (!isset($produto_combinacao['id_produto_combinacao'])) { $r = $ProdutoCombinacaoDao->saveProdutoCombinacao($_POST['id'], $produto_combinacao, $_POST['id_empreendimento']); $combinacoes[] = $r; } else { $r = $ProdutoCombinacaoDao->updateProdutoCombinacao($_POST['id'], $produto_combinacao, $_POST['id_empreendimento']); $combinacoes[] = $r; } } else { $combinacoes[] = $produto_combinacao; } } $ProdutoCombinacaoDao->saveCombinacoes($combinacoes, $_POST['id']); $saida = array('id' => (int) $ProdutoTO->id); if ($new_image) { $saida['local_new_image'] = $new_image; } Flight::response()->status(200)->header('Content-Type', 'application/json')->write(json_encode($saida))->send(); }
/** * */ public function saveFile($file, $file_name) { $rep_dest = 'var/uploads/'; $upload = new upload($file); $upload->file_overwrite = true; //supprime le fichier si existe if ($upload->uploaded) { //file $upload->file_new_name_body = $file_name; // It could be something like $upload->Process('www/my_uploads/'); $upload->Process($rep_dest); //$upload->clean(); return $upload->file_dst_name; } return null; }
<div style="float: left"> <input type="submit" id="insert" name="insert" value="{#insert}" onclick="ImageDialog.insert();return false;" /> </div> <div style="float: right"> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </div> </form> <?php include './classes/class.upload.php'; if (isset($_POST['action']) && $_POST['action'] == 'image') { include './config.php'; $handle = new upload($_FILES['image_field'], $language); include './config.php'; $handle->Process($server_image_directory); if ($handle->uploaded) { if ($handle->processed) { echo "<script>setTimeout(\"document.getElementById('src').value='" . $url_image_directory . "/" . $handle->file_dst_name . "'\", 200)</script>"; echo "<script>setTimeout(\"ImageDialog.showPreviewImage(document.getElementById('src').value)\", 400)</script>"; } else { $error_str = str_replace("'", "`", $handle->error); echo "<script>alert('{$error_str}')</script>"; } $handle->Clean(); } else { $error_str = str_replace("'", "`", $handle->error); echo "<script>alert('{$error_str}')</script>"; } } ?>
function saveImage($imagepath) { $imagepath = trim($imagepath); if (isset($this->_k2_item_id) && is_int($this->_k2_item_id) && $this->_k2_item_id > 0) { //echo JPATH_ADMINISTRATOR .DS."components".DS."com_k2".DS.'lib'.DS.'class.upload.php'; //die(); require_once JPATH_ADMINISTRATOR . DS . "components" . DS . "com_k2" . DS . 'lib' . DS . 'class.upload.php'; $image = JPATH_SITE . DS . JPath::clean($imagepath); $handle = new upload($image); $handle->allowed = array('image/*'); $params =& JComponentHelper::getParams('com_k2'); if ($handle->uploaded) { //Original image $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'src'; $handle->image_convert = 'jpg'; $handle->jpeg_quality = 100; $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = md5("Image" . $this->_k2_item_id); $handle->Process($savepath); $filename = $handle->file_dst_name_body; $savepath = JPATH_SITE . DS . 'media' . DS . 'k2' . DS . 'items' . DS . 'cache'; //XLarge image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_XL'; if (JRequest::getInt('itemImageXL')) { $imageWidth = JRequest::getInt('itemImageXL'); } else { $imageWidth = $params->get('itemImageXL', '800'); } $handle->image_x = $imageWidth; $handle->Process($savepath); //Large image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_L'; if (JRequest::getInt('itemImageL')) { $imageWidth = JRequest::getInt('itemImageL'); } else { $imageWidth = $params->get('itemImageL', '600'); } $handle->image_x = $imageWidth; $handle->Process($savepath); //Medium image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_M'; if (JRequest::getInt('itemImageM')) { $imageWidth = JRequest::getInt('itemImageM'); } else { $imageWidth = $params->get('itemImageM', '400'); } $handle->image_x = $imageWidth; $handle->Process($savepath); //Small image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_S'; if (JRequest::getInt('itemImageS')) { $imageWidth = JRequest::getInt('itemImageS'); } else { $imageWidth = $params->get('itemImageS', '200'); } $handle->image_x = $imageWidth; $handle->Process($savepath); //XSmall image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_XS'; if (JRequest::getInt('itemImageXS')) { $imageWidth = JRequest::getInt('itemImageXS'); } else { $imageWidth = $params->get('itemImageXS', '100'); } $handle->image_x = $imageWidth; $handle->Process($savepath); //Generic image $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality'); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename . '_Generic'; $imageWidth = $params->get('itemImageGeneric', '300'); $handle->image_x = $imageWidth; $handle->Process($savepath); } // $handle->clean(); if ($handle->error == '') { return 'no error'; } else { return $handle->error . " " . $imagepath; } } else { return 'It seems like the item were not creted (no item_id was given) so the image was not imported.'; } }
list($intOriginalWidth, $intOriginalHeight) = getimagesize($handle->file_src_pathname); //set a min width $handle->image_min_width = $headshot_large_width; $handle->image_x = $intOriginalWidth; $handle->file_new_name_body = 'headshot_original'; $lboolResize = TRUE; $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->file_overwrite = true; $handle->file_auto_rename = false; $handle->dir_auto_chmod = true; // now, we start the upload 'process'. That is, to copy the uploaded file // from its temporary location to the wanted location // It could be something like $handle->Process('/home/www/my_uploads/'); $handle->Process($dir_dest); // we check if everything went OK if ($handle->processed) { //if resize is true, large was uploaded so resize and create 2 thumbnails //if resize is false, print error if ($lboolResize) { list($width, $height) = getimagesize($dir_dest . DIRECTORY_SEPARATOR . "headshot_original.jpg"); $rscThumbnail = imagecreatetruecolor($headshot_thumb_width, $headshot_thumb_width); $rscLargeImage = imagecreatetruecolor($headshot_large_width, $headshot_large_width); $rscOriginalImage = imagecreatefromjpeg($dir_dest . DIRECTORY_SEPARATOR . "headshot_original.jpg"); imagecopyresampled($rscThumbnail, $rscOriginalImage, 0, 0, 0, 0, $headshot_thumb_width, $headshot_thumb_width, $width, $height); imagecopyresampled($rscLargeImage, $rscOriginalImage, 0, 0, 0, 0, $headshot_large_width, $headshot_large_width, $width, $height); imagejpeg($rscThumbnail, $dir_dest . DIRECTORY_SEPARATOR . "headshot.jpg"); imagejpeg($rscLargeImage, $dir_dest . DIRECTORY_SEPARATOR . "headshot_large.jpg"); } // everything was fine ! Close the modal window and reload page to show changes
//$foo->file_overwrite = true; //$foo->image_convert = 'jpg'; //$foo->image_resize = false; //$foo->Process("$img_dst_source/{$a['id']}"); //if (!$foo->processed) { // echo 'error : ' . $foo->error; //} ////chmod("$img_dst_source/{$a['id']}/{$foo->file_dst_name}", 0755); $foo->file_overwrite = true; $foo->image_convert = 'jpg'; $foo->image_resize = true; $foo->image_ratio_crop = false; $foo->image_ratio = true; $foo->image_x = 600; $foo->image_y = 400; $foo->Process("{$img_dst_large}/{$a['id']}"); if (!$foo->processed) { echo 'error : ' . $foo->error; } //chmod("$img_web_large/{$a['id']}/{$foo->file_dst_name}", 0755); echo "<p><img src='{$img_web_large}/{$a['id']}/{$foo->file_dst_name}' /></p>"; $foo->file_overwrite = true; $foo->image_convert = 'jpg'; $foo->image_resize = true; $foo->image_ratio = false; $foo->image_ratio_crop = true; $foo->image_y = 125; $foo->image_x = 125; $foo->Process("{$img_dst_thumb}/{$a['id']}"); if (!$foo->processed) { echo 'error : ' . $foo->error;
} $img->dir_auto_create = true; $img->image_x = $size_x; $img->image_y = $size_y; $img->process($cache_dir . $size . '/'); // Вывод ошибок и очистка if ($img->processed) { $img->clean(); } else { echo 'error : ' . $img->error; } $image_name = Text::strtolow(str_replace(' ', '_', $image_name)); $image_name = str_replace('(', '', $image_name); $image_name = str_replace(')', '', $image_name); // Получаем изображение из кэша $img = new upload($cache_dir . $size . '/' . $image_name); // Вывод изображения header('Content-type: ' . $img->file_src_mime); echo $img->Process(); exit; } } } else { $img = new upload($dir . $image_name); // Вывод оригинального изображения header('Content-type: ' . $img->file_src_mime); echo $img->Process(); exit; } } exit;
$foo->file_new_name_body = 'logo'; $foo->file_new_name_ext = 'jpg'; $foo->file_overwrite = true; $foo->file_auto_rename = false; $foo->auto_create_dir = false; $foo->dir_auto_chmod = false; $foo->dir_chmod = 0755; $foo->image_convert = 'jpg'; $foo->file_safe_name = false; $foo->jpeg_quality = 85; $foo->mime_check = false; $foo->image_resize = true; $foo->image_ratio_crop = true; $foo->image_y = 125; $foo->image_x = 125; $foo->Process("{$img_dst_logo}/{$pid}/"); if (!$foo->processed) { file_put_contents("{$img_dst_logosource}/{$pid}/{$file_name}.log", $foo->error, FILE_APPEND); //echo 'ERROR ON LOGO THUMBNAIL: ' . $foo->error; //exit(0); } unlink("{$img_dst_logosource}/{$pid}/{$file_name}"); echo '1'; exit; } } if (isset($get['cmd']) && $get['cmd'] == 'upload_videos') { if (!empty($_FILES)) { // first make our directory if (!is_dir("{$img_dst_video}/{$pid}")) { mkdir("{$img_dst_video}/{$pid}", 0755);
} /** * Simplify using filters for STRINGS * @param $x * @return mixed */ function FStr($x) { return filter_var($x, FILTER_SANITIZE_SPECIAL_CHARS); } /** * UPLOADING IMAGES * NEEDS THIS CLASS : https://github.com/verot/class.upload.php */ $Upload = new upload($_FILES["bannerupload"]); if ($Upload->uploaded) { $Upload->Process("../IMG/bannersystem/"); if ($Upload->processed) { /** * PUT MORE CODE HERE - HERE IS WHEN ALL GOES WELL */ $FileName = $Upload->file_dst_name; $Upload->clean(); } else { echo 'error : ' . $Upload->error; } } else { echo 'error : ' . $Upload->error; echo "<br><br>"; echo "LOG: " . $Upload->log; }
<div style="float: left"> <input type="submit" id="insert" name="insert" value="{#insert}" onclick="ImageDialog.insert();return false;" /> </div> <div style="float: right"> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </div> </form> <?php include './classes/class.upload.php'; if (isset($_POST['action']) && $_POST['action'] == 'image') { $handle = new upload($_FILES['image_field'], $language); include './config.php'; if ($handle->image_resize === true) { $handle->Process($server_thumbnail_directory); $thumbnail_path = $url_thumbnail_directory . DIRECTORY_SEPARATOR . $handle->file_dst_name; $handle->image_resize = false; $handle->Process($server_image_directory); $image_path = $url_image_directory . DIRECTORY_SEPARATOR . $handle->file_dst_name; } else { $handle->Process($server_image_directory); $path = $url_image_directory . DIRECTORY_SEPARATOR . $handle->file_dst_name; } if ($handle->uploaded) { if ($handle->processed) { echo "<script>setTimeout(\"document.getElementById('src').value='{$thumbnail_path}'\", 200)</script>"; echo "<script>setTimeout(\"document.getElementById('original_src').value='{$image_path}'\", 400)</script>"; echo "<script>setTimeout(\"ImageDialog.showPreviewImage(document.getElementById('src').value)\", 600)</script>"; } else { $error_str = str_replace("'", "`", $handle->error);
public static function downloadImage($url, $params) { $cacheTime = $params->get('feedcache', 60); $imgcheckmime = (int) $params->get('checkmime', 1); $url = str_replace(" ", "%20", JString::trim($url)); if (!$params->get('storeimages', 0) || !$cacheTime || JString::strlen($url) < 6 || JString::substr($url, 0, 4) != "http") { return $url; } $ext = JString::strtolower(end(explode('.', $url, 2))); if (empty($ext)) { $ext = 'jpg'; } $valid_ext = array('png', 'jpg', 'jpeg', 'gif', 'bmp', 'ico'); if ($imgcheckmime && !in_array($ext, $valid_ext)) { return $url; } $cachePath = JPATH_SITE . DS . 'cache' . DS . 'mod_we_ufeed_display'; $cacheTime = $cacheTime * 60; //to seconds $filename = JFile::makeSafe(md5($url) . "." . $ext); if (!JFolder::exists($cachePath)) { JFolder::create($cachePath); } if (JFile::exists($cachePath . DS . $filename)) { if (time() < filemtime($cachePath . DS . $filename) + $cacheTime && is_readable($cachePath . DS . $filename)) { return JString::trim(JURI::root(true) . '/cache/mod_we_ufeed_display/' . $filename); } else { JFile::delete($cachePath . DS . $filename); } } $buffer = ""; if (in_array('curl', get_loaded_extensions()) && !@ini_get('safe_mode')) { $ch = curl_init(); // cURL curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $buffer = @curl_exec($ch); curl_close($ch); } elseif (empty($buffer) && @ini_get('allow_url_fopen')) { $buffer = @file_get_contents($url); } $img = $url; if (!empty($buffer) && JFile::write($cachePath . DS . $filename, $buffer) && filesize($cachePath . DS . $filename) > 999) { $img = JURI::root(true) . '/cache/mod_we_ufeed_display/' . $filename; $stored = true; } else { $img = $url; if (JFile::exists($cachePath . DS . $filename)) { JFile::delete($cachePath . DS . $filename); } } $allowResize = false; if ($allowResize && $stored && $cropImages) { if (!class_exists('upload')) { require_once dirname(__FILE__) . DS . 'resizer.php'; } $handle = new upload($cachePath . DS . $filename); $handle->image_resize = true; $handle->image_ratio_y = true; $handle->image_convert = 'jpg'; $handle->jpeg_quality = $params->get('imagesQuality', 100); $handle->file_auto_rename = false; $handle->file_overwrite = true; $handle->file_new_name_body = $filename; $handle->image_x = $params->get('resizewidth', '150'); $handle->Process($cachePath); $handle->Clean(); } return $img; }
public function elem($post, $get, $FILES) { require_once sys . '/plugin/class.upload/class.upload.php'; $post = array_merge(array('chpu' => '', 'marker' => '', 'active_path' => ''), $post); $file = isset($FILES['form']) ? $FILES['form'] : array(); $form = isset($post['form']) ? $post['form'] : array(); $activePath = isset($post['active_path']) && $post['active_path'] != '' ? 1 : 0; $updateId = isset($post['id']) && $post['id'] != '' ? (int) $post['id'] : false; if ($updateId !== false) { Fx::db()->update(Fx::service_context()->namespace['construct_db'], array('chpu' => $post['chpu'], 'active_path' => $activePath, 'marker' => $post['marker'], 'date' => time()), array('id' => $updateId)); $ref = Fx::db()->find(Fx::service_context()->namespace['construct_db'], array('ref' => $updateId)); foreach ($ref as $v) { Fx::db()->update(Fx::service_context()->namespace['construct_db'], array('chpu' => $post['chpu'], 'active_path' => $post['active_path'], 'marker' => $post['marker'], 'date' => time()), array('id' => $v['id'])); } $lastId = $updateId; } else { $num = count(Fx::db()->find(Fx::service_context()->namespace['construct_db'], array('parent' => (int) $post['parent']))); Fx::db()->insert(Fx::service_context()->namespace['construct_db'], array('parent' => (int) $post['parent'], 'ref' => '', 'object' => $post['object'], 'chpu' => $post['chpu'], 'num' => $num, 'active_path' => $activePath, 'marker' => $post['marker'], 'date' => time())); $form['id'] = $lastId = Fx::db()->lastID(); } $table = Fx::db()->find(Fx::service_context()->namespace['struct_db'], array('code' => $post['object'])); $table = $table[0]; $row = Fx::db()->find(Fx::service_context()->namespace['struct_td'], array('parent' => $table['id'])); $rows = array(); foreach ($row as $v) { $rows[$v['code']] = array('id' => $v['id'], 'size' => $v['size'], 'type' => $v['type'], 'param' => json_decode($v['param'], true)); } foreach ($form as $k => $v) { if (is_string($v)) { $form[$k] = Fx::db()->esc($v); } } foreach ($rows as $k => $v) { if (!isset($form[$k])) { $form[$k] = ''; } } $path = root . '/' . Fx::service_context()->config['folder']['files'] . '/' . $lastId . '/'; if (isset($file['tmp_name'])) { foreach ($file['tmp_name'] as $k => $v) { $savePath = '/' . Fx::service_context()->config['folder']['files'] . '/' . $lastId . '/'; $fileName = isset($form[$k]['name']) && $form[$k]['name'] != '' ? trim($form[$k]['name']) : $k; $gist = $rows[$k]; $fn = isset($form[$k]['url']) && $form[$k]['url'] != '' ? $form[$k]['url'] : $v['file']; $mime = Fx::io()->mime($file['name'][$k]['file'] != '' ? $file['name'][$k]['file'] : $form[$k]['url']); if (isset($form[$k]['url']) && $form[$k]['url'] !== '') { Fx::io()->create_file(root . '/' . 'temporary.tmp'); Fx::io()->in_file(root . '/' . 'temporary.tmp', file_get_contents($fn)); $fn = root . '/' . 'temporary.tmp'; } if ($fn != '') { if (empty($fn)) { continue; } $IMG = new upload($fn); if ($IMG->uploaded) { $IMG->file_new_name_body = $fileName; $IMG->file_new_name_ext = $mime; $gistParam = $gist['param']; $width = isset($gistParam['width']) && $gistParam['width'] != '' ? $gistParam['width'] : 1000; $height = isset($gistParam['height']) && $gistParam['height'] != '' ? $gistParam['height'] : 1000; // Param if (isset($gist['param']['method'])) { switch ($gist['param']['method']) { case 'scale': // Подгоняем по размеру и пропорциям, без полей $IMG->image_resize = true; $IMG->image_ratio = true; $IMG->image_y = $height; $IMG->image_x = $width; break; case 'crop': // Точно по размеру игнорируя пропорции $IMG->image_resize = true; $IMG->image_ratio_crop = true; $IMG->image_y = $height; $IMG->image_x = $width; break; case 'width': // ресайзим по ширине $IMG->image_resize = true; $IMG->image_ratio_x = true; $IMG->image_y = $height; break; case 'height': // ресайзим по высоте $IMG->image_resize = true; $IMG->image_ratio_y = true; $IMG->image_x = $width; break; } } if (is_file($path . $fileName . '.' . $mime)) { unlink($path . $fileName . '.' . $mime); } $IMG->Process($path); if (!$IMG->processed) { setSystemMessage('error', $IMG->error); } $IMG->clean(); if (isset($gist['param']['zip']) && $gist['param']['zip'] == 1) { $zip = new ZipArchive(); if ($zip->open($path . $fileName . '.zip', ZIPARCHIVE::CREATE) === TRUE) { $zip->addFile($path . $fileName . '.' . $mime, $fileName . '.' . $mime); } $zip->close(); if (file_exists($path . $fileName . '.' . $mime)) { unlink($path . $fileName . '.' . $mime); } $savePath = $savePath . $fileName . '.zip'; } else { $savePath = $savePath . $fileName . '.' . $mime; } } else { setSystemMessage('error', $IMG->error); } $form[$k] = file_exists(root . $savePath) ? $savePath : ''; } if (is_array($form[$k])) { if (isset($form[$k]['remove']) && $form[$k]['remove'] == 1) { if (file_exists(root . $form[$k]['src'])) { unlink(root . $form[$k]['src']); } $form[$k] = ''; } else { if (isset($form[$k]['src']) && isset($form[$k]['name'])) { $imagePath = explode('/', $form[$k]['src']); $imageName = array_pop($imagePath); $imageName = explode('.', $imageName); $imageMime = array_pop($imageName); $imageName = implode('.', $imageName); if ($imageName !== $form[$k]['name']) { $newImageName = implode('/', $imagePath) . '/' . $form[$k]['name'] . '.' . $imageMime; if (is_file(root . $newImageName)) { unlink(root . $newImageName); } rename(root . $form[$k]['src'], root . $newImageName); $form[$k] = $newImageName; } else { $form[$k] = $form[$k]['src']; } } else { $form[$k] = ''; } } } } } foreach ($form as $k => $v) { if (is_array($v)) { $form[$k] = serialize($v); } } if ($updateId !== false) { Fx::db()->update($post['object'], $form, array('id' => $updateId)); } else { Fx::db()->insert($post['object'], $form); } load_url(); }
} else { $ret['msg'] = $file->error; $ret['id'] = -1; $model->setId($id); $control->delete($model); } } $file->Clean(); print json_encode($ret); break; case 'getDoc': require_once "../classes/Upload.class.php"; $link = $_SERVER['DOCUMENT_ROOT'] . '/public/uploads/docCurso' . $id . '.pdf'; $file = new upload($link); header("Content-type: " . $file->file_src_mime); echo $file->Process(); break; // caso a ação seja de editar um Curso existente // caso a ação seja de editar um Curso existente case 'edit': // cria um controller de Curso $controlCurso = CursoController::getInstance(); // cria um modelo de Curso com valores existentes no banco $modelCurso = $controlCurso->fill($id); // captura o json passado por POST e o transforma em um array $dados = json_decode($_POST['data'], true); // para cada valor do array edita os valores do modelo do Curso foreach ($dados as $campo => $valor) { $modelCurso->{'set' . ucfirst($campo)}($valor); } // edita os valores do banco para o Curso