metaestat_uploadshp_submit.php
9.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
<?php
/*
* Faz o upload de shapefile e insere no banco de dados
*/
include_once("admin.php");
include_once("login.php");
if(verificaOperacaoSessao("admin/metaestat/editorbanco") == false){
echo "Vc nao pode realizar essa operacao.";exit;
}
error_reporting(0);
if (ob_get_level() == 0) ob_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="../../css/geral.css" />
<title></title>
</head>
<body bgcolor="white" style="background-color:white;text-align:left;">
<p>
<?php
if($_POST["tabelaDestino"] == ""){
echo "Nome da tabela não definido";
exit;
}
if($_POST["srid"] == ""){
echo "SRID não definido";
exit;
}
if ($_FILES['i3GEOuploadshp']['name'] == ""){
echo "Arquivo não definido";
exit;
}
if (isset($_FILES['i3GEOuploadshp']['name'])){
require_once (dirname(__FILE__)."/../../ms_configura.php");
echo "<p class='paragrafo' >Carregando o arquivo...</p>";
ob_flush();
flush();
sleep(1);
$arqshp = $_FILES['i3GEOuploadshp']['tmp_name'];
//verifica nomes e sobe arquivo
verificaNome($_FILES['i3GEOuploadshp']['name'],"shp");
$nomePrefixo = str_replace(" ","_",removeAcentos(str_replace(".shp","",$_FILES['i3GEOuploadshp']['name'])));
$nomePrefixo = $nomePrefixo."_".(nomeRandomico(4));
$Arquivo = $_FILES['i3GEOuploadshp']['tmp_name'];
$status = move_uploaded_file($Arquivo,$dir_tmp."/".$nomePrefixo.".shp");
if($status != 1)
{echo "<p class='paragrafo' >Ocorreu um erro no envio do arquivo SHP";exit;}
$Arquivo = $_FILES['i3GEOuploadshx']['tmp_name'];
$status = move_uploaded_file($Arquivo,$dir_tmp."/".$nomePrefixo.".shx");
if($status != 1)
{echo "<p class='paragrafo' >Ocorreu um erro no envio do arquivo SHX";exit;}
$Arquivo = $_FILES['i3GEOuploaddbf']['tmp_name'];
$status = move_uploaded_file($Arquivo,$dir_tmp."/".$nomePrefixo.".dbf");
if($status != 1)
{echo "<p class='paragrafo' >Ocorreu um erro no envio do arquivo DBF";exit;}
if(!file_exists($dir_tmp."/".$nomePrefixo.".shp"))
{echo "<p class='paragrafo' >Ocorreu algum problema no envio do arquivo ".$dir_tmp."/".$nomePrefixo;paraAguarde();exit;}
$arqshp = $dir_tmp."/".$nomePrefixo.".shp";
//pega os parametros de conexao
include("classe_metaestat.php");
$m = new Metaestat();
$conexao = $m->listaConexao($_POST["i3GEOuploadcodigoconexao"],true);
//array(5) { ["codigo_estat_conexao"]=> string(1) "1" ["bancodedados"]=> string(8) "geosaude" ["host"]=> string(9) "localhost" ["porta"]=> string(4) "5432" ["usuario"]=> string(8) "postgres" }
//pega as colunas do shapefile
$shapefileObj = ms_newShapefileObj($arqshp,-1);
$numshapes = $shapefileObj->numshapes;
$mapObj = ms_newMapObjFromString("MAP END");
$layer = ms_newLayerObj($mapObj);
$layer->set("data",$arqshp);
$layer->open();
$colunasTemp = $layer->getItems();
$colunas = array();
foreach($colunasTemp as $c){
//abaixo gid e forçado a entrar
if(!is_numeric($c) && strtolower($c) != "gid"){
$colunas[] = $c;
}
}
echo "<br>Numshapes existentes no SHP: ". $numshapes;
$tipo = $shapefileObj->type;
echo "<br>Tipo: ". $tipo;
echo "<br>Colunas: ";
var_dump($colunas);
ob_flush();
flush();
sleep(1);
$sqinsert = array();
//verifica o tipo de coluna
$tipoColuna = array();
if($numshapes < 10){
$testar = $numshapes;
}
else{
$testar = 10;
}
foreach($colunas as $coluna){
$tipo = "numeric";
for ($i=0; $i<$testar;$i++){
$s = $layer->getShape(new resultObj($i));
$v = $s->getValue($layer,$coluna);
if(!is_numeric($v)){
$tipo = "varchar";
}
}
$tipoColuna[$coluna] = $tipo;
}
echo "<br>Tipos das colunas: <pre>";
var_dump($tipoColuna);
echo "</pre>";
ob_flush();
flush();
sleep(1);
try {
$dbh = new PDO('pgsql:dbname='.$conexao["bancodedados"].';user='.$conexao["usuario"].';password='.$conexao["senha"].';host='.$conexao["host"].';port='.$conexao["porta"]);
} catch (PDOException $e) {
echo '<span style=color:red >Connection failed: ' . $e->getMessage();
exit;
}
//gera o script para criar a tabela
//verifica se a tabela ja existe
$sql = "SELECT table_name FROM information_schema.tables where table_schema = '".$_POST["i3GEOuploadesquema"]."' AND table_name = '".$_POST["tabelaDestino"]."'";
$res = $dbh->query($sql,PDO::FETCH_ASSOC);
if(count($res->fetchAll())>0){
$tabelaExiste = true;
}
else{
$tabelaExiste = false;
}
//encoding do banco de dados
$sql = "SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = '".$conexao["bancodedados"]."'";
$res = $dbh->query($sql,PDO::FETCH_ASSOC);
$encodingdb = $res->fetchAll();
$encodingdb = $encodingdb[0];
$encodingdb = $encodingdb["pg_encoding_to_char"];
if($encodingdb == "UTF8"){
$encodingdb = "UTF-8";
}
if($encodingdb == "LATIN1"){
$encodingdb = "ISO-8859-1";
}
//a tabela nao existe e e do tipo create
$sqltabela = array();
if($tabelaExiste == false && $_POST["tipoOperacao"] == "criar"){
$sql = "CREATE TABLE ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]."(the_geom geometry";
foreach($colunas as $coluna){
$sql .= ",".strtolower($coluna)." ".$tipoColuna[$coluna];
}
$sql .= ")WITH(OIDS=FALSE)";
$sqltabela[] = $sql;
$sqltabela[] = "ALTER TABLE ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]." OWNER TO ".$conexao["usuario"];
$sqltabela[] = "CREATE INDEX ".$_POST["tabelaDestino"]."_indx_thegeom ON ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]." USING gist (the_geom )";
echo "<br>Sql tabela: <pre>";
var_dump($sqltabela);
echo "</pre>";
ob_flush();
flush();
sleep(1);
}
if($tabelaExiste == true && $_POST["tipoOperacao"] == "criar"){
echo "<span style=color:red >A tabela existe. Não pode ser criada.</span>";
exit;
}
//se a tabela existe e e para remover os registros
if($tabelaExiste == true && $_POST["tipoOperacao"] == "apagar"){
$sqltabela[] = "delete from ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"];
}
if($tabelaExiste == true && $_POST["tipoOperacao"] == "apagar" && $_POST["i3GEOuploadesquema"] != "i3geo_metaestat"){
echo "<span style=color:red >Não é possível executar essa operação nesse esquema.</span>";
exit;
}
//gera o script para inserir os dados
$linhas = array();
$insert = "INSERT INTO ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]." (".strtolower(implode(",",$colunas)).",the_geom)";
echo "<br>Preparando inclusão de dados";
ob_flush();
flush();
sleep(1);
for ($i=0; $i<$numshapes;$i++){
$s = $layer->getShape(new resultObj($i));
$vs = array();
foreach($colunas as $coluna){
if($tipoColuna[$coluna] == "varchar"){
$texto = $s->getValue($layer,$coluna);
//echo $i." - ".mb_detect_encoding($texto)."<br>";
$texto = str_replace("'","",$texto);
$enc = mb_detect_encoding($texto);
if(enc != ""){
$texto = "'".mb_convert_encoding($texto,$encodingdb,$enc)."'";
}
else{
$texto = "'".$texto."'";
}
if($texto == "''"){
$texto = 'null';
}
$vs[] = $texto;
}
else{
$valor = $s->getValue($layer,$coluna);
if($valor == "" || (empty($valor) && $valor != 0)){
$valor = 'nulo';
}
$vs[] = $valor;
}
}
$vs[] = "st_geomfromtext('".$s->toWkt()."','".$_POST["srid"]."')";
$str = implode(",",$vs);
$str = str_replace("nulo",'null',$str);
$linhas[] = $insert."VALUES(".$str.")";
}
//echo "<pre>".var_dump($linhas);exit;
$layer->close();
echo "<br>Incluindo dados";
echo "<script>window.scrollTo(0,10000);</script>";
ob_flush();
flush();
sleep(1);
if($_POST["incluiserialshp"] == "on"){
$linhas[] = "alter table ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]." add gid serial CONSTRAINT ".$_POST["tabelaDestino"]."_gid_pkey PRIMARY KEY";
echo "<br>alter table ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"]." add gid serial CONSTRAINT ".$_POST["tabelaDestino"]."_gid_pkey PRIMARY KEY";
}
foreach($sqltabela as $linha){
try {
$dbh->query($linha);
} catch (PDOException $e) {
echo 'Erro: ' . $e->getMessage();
}
}
foreach($linhas as $linha){
try {
$res = $dbh->query($linha);
if($res == false){
echo "<br><br><span style=color:red >Erro em: </span>".$linha;
}
} catch (PDOException $e) {
echo 'Erro: ' . $e->getMessage();
}
}
echo "<br>Registros existentes no SHP: ". $numshapes;
$sql = "select * from ".$_POST["i3GEOuploadesquema"].".".$_POST["tabelaDestino"];
$q = $dbh->query($sql,PDO::FETCH_ASSOC);
$r = $q->fetchAll();
echo "<br>Registros na tabela final: ". count($r);
echo "<br>Diferenças podem ocorrer em função de caracteres acentuados não suportados pelo banco de dados";
echo "<br><b>Feito!!!<br>Faça o reload da página";
}
else{
echo "<p class='paragrafo' >Erro ao enviar o arquivo. Talvez o tamanho do arquivo seja maior do que o permitido.</p>";
}
function verificaNome($nome,$ext){
$nome = strtolower($nome);
$lista = explode(".",$nome);
$extensao = $lista[count($lista) - 1];
if($extensao != $ext){
echo "Nome de arquivo inválido.";
exit;
}
}
?>
<script>window.scrollTo(0,10000);</script>
</body>
</html>