Statistics
| Revision:

root / i3geo60 / classesphp / classe_analise.php @ 6498

History | View | Annotate | Download (87 KB)

1
<?php
2
/*
3
 Title: classe_analise.php
4

5
Gera an&aacute;lises espaciais, como buffer, calculo de centr�ides, etc.
6

7
Licenca:
8

9
GPL2
10

11

12
i3Geo Interface Integrada de Ferramentas de Geoprocessamento para Internet
13

14
Direitos Autorais Reservados (c) 2006 Minist&eacute;rio do Meio Ambiente Brasil
15
Desenvolvedor: Edmar Moretti edmar.moretti@gmail.com
16

17
Este programa &eacute; software livre; voc&ecirc; pode redistribu&iacute;-lo
18
e/ou modific&aacute;-lo sob os termos da Licen&ccedil;a P&uacute;blica Geral
19
GNU conforme publicada pela Free Software Foundation;
20

21
Este programa &eacute; distribu&iacute;do na expectativa de que seja &uacute;til,
22
por&eacute;m, SEM NENHUMA GARANTIA; nem mesmo a garantia impl&iacute;cita
23
de COMERCIABILIDADE OU ADEQUA&Ccedil;&Atilde;O A UMA FINALIDADE ESPEC&Iacute;FICA.
24
Consulte a Licen&ccedil;a P&uacute;blica Geral do GNU para mais detalhes.
25
Voc&ecirc; deve ter recebido uma c�pia da Licen&ccedil;a P&uacute;blica Geral do
26
        GNU junto com este programa; se n&atilde;o, escreva para a
27
Free Software Foundation, Inc., no endere&ccedil;o
28
59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
29

30
Arquivo:
31

32
i3geo/classesphp/classe_analise.php
33
*/
34
/*
35
 Classe: Analise
36

37
*/
38
class Analise
39
{
40
        /*
41
         Variavel: $mapa
42

43
        Objeto mapa
44
        */
45
        public $mapa;
46
        /*
47
         Variavel: $arquivo
48

49
        Arquivo map file
50
        */
51
        protected $arquivo;
52
        /*
53
         Variavel: $layer
54

55
        Objeto layer
56
        */
57
        protected $layer;
58
        /*
59
         Variavel: $nome
60

61
        Nome do layer
62
        */
63
        protected $nome;
64
        /*
65
         Variavel: $diretorio
66

67
        Diret&oacute;rio do arquivo map_file
68
        */
69
        protected $diretorio;
70
        /*
71
         Variavel: $qyfile
72

73
        Nome do arquivo de sele&ccedil;&atilde;o (.qy)
74
        */
75
        public $qyfile;
76
        /*
77
         Variavel: $v
78

79
        Vers&atilde;o atual do Mapserver (primeiro d&iacute;gito)
80
        */
81
        public $v;
82
        /*
83
         Variavel: $dbaseExiste
84

85
        Indica se a biblioteca dbase est&aacute; carregada
86
        */
87
        protected $dbaseExiste;
88
        /*
89
         Function: __construct
90

91
        Cria um objeto Analise
92

93
        parameters:
94

95
        $map_file - Endere&ccedil;o do mapfile no servidor.
96

97
        $tema - Nome do tema que ser&aacute; processado
98

99
        $ext - Extens&atilde;o geogr&aacute;fica do mapa
100
        */
101
        function __construct($map_file,$tema="",$locaplic="",$ext="")
102
        {
103
                //error_reporting(0);
104
                $this->qyfile = str_replace(".map",".qy",$map_file);
105
                include_once(dirname(__FILE__)."/funcoes_gerais.php");
106
                if(empty($locaplic)){
107
                        $locaplic = dirname(__FILE__)."/..";
108
                }
109
                $this->v = versao();
110
                $this->v = $this->v["principal"];
111
                $this->dbaseExiste = false;
112
                if(function_exists("dbase_create"))
113
                {
114
                        $this->dbaseExiste = true;
115
                }
116
                $this->locaplic = $locaplic;
117
                $this->mapa = ms_newMapObj($map_file);
118
                $this->arquivo = $map_file;
119
                if($tema != "" && @$this->mapa->getlayerbyname($tema))
120
                {
121
                        $this->layer = $this->mapa->getlayerbyname($tema);
122
                }
123
                $this->nome = $tema;
124
                $this->diretorio = dirname($this->arquivo);
125
                if($ext && $ext != ""){
126
                        $e = explode(" ",$ext);
127
                        $extatual = $this->mapa->extent;
128
                        $extatual->setextent((min($e[0],$e[2])),(min($e[1],$e[3])),(max($e[0],$e[2])),(max($e[1],$e[3])));
129
                }
130
        }
131
        /*
132
         Method: criaDefDb
133

134
        Cria um array contendo as defini&ccedil;&otilde;es das colunas que ser&atilde;o criadas em uma tabela DBF conforme as exig&ecirc;ncias de arquivos dbf
135

136
        parameters:
137

138
        $itens - array com os nomes originais das colunas
139

140
        return:
141
        {array}
142
        */
143
        function criaDefDb($itens,$unico=true){
144
                $c = 0;
145
                $def = array();
146
                foreach ($itens as $ni){
147
                        $ni = strtoupper($ni);
148
                        if($unico == true){
149
                                $def[] = array(substr($ni, 0, 8).$c,"C","254");
150
                        }
151
                        else{
152
                                $def[] = array($ni,"C","254");
153
                        }
154
                        $c = $c + 1;
155
                }
156
                return $def;
157
        }
158
        /*
159
         Method: truncaS
160

161
        Trunca o comprimento de uma string em 255 caracteres
162

163
        parameters:
164

165
        $s - string
166

167
        return
168
        {string}
169
        */
170
        function truncaS($s){
171
                if(strlen($s) > 255){
172
                        $s = substr($s,0,255);
173
                }
174
                return $s;
175
        }
176
        /*
177
         Method: salva
178

179
        Salva o mapfile atual
180
        */
181
        function salva()
182
        {
183
                if (connection_aborted()){
184
                        exit();
185
                }
186
                $this->mapa->save($this->arquivo);
187
        }
188

    
189
        /*
190
         function: analiseDistriPt
191

192
        Gera an&aacute;lise de distribui&ccedil;&atilde;o de pontos.
193

194
        Executa script R para gerar a imagem.
195

196
        parameters:
197

198
        $locaplic - Localiza&ccedil;&atilde;o da aplica&ccedil;&atilde;o I3Geo
199

200
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver
201

202
        $R_path - Onde fica o R
203

204
        $numclasses - N&uacute;mero de classes que ser&atilde;o representadas
205

206
        $tipo - Tipo de an&aacute;lise.
207

208
        $cori - Cor inicial em rgb.
209

210
        $corf - Cor final em rgb.
211

212
        $tmpurl - Url com o nome da imagem final (apenas para relatorio)
213

214
        $sigma - desvio padr&atilde;o para a op&ccedil;&atilde;o kernel
215

216
        $limitepontos - "TRUE"|"FALSE" limita o resultado ao limite geogr&aacute;fico dos pontos se "TRUE" ou ao limite do mapa se "FALSE"
217

218
        $extendelimite - extende o limite dos pontos em um determinado percentual em rela&ccedil;&atilde;o a &aacute;rea final de abrang&ecirc;ncia
219

220
        $item - item contendo os pesos utilizado na operacao de calculo de densidade (opcional)
221

222
        Include:
223
        <class.palette.php>
224
        */
225
        function analiseDistriPt($locaplic,$dir_tmp,$R_path,$numclasses,$tipo,$cori,$corf,$tmpurl,$sigma="",$limitepontos="TRUE",$tema2="",$extendelimite=5,$item="")
226
        {
227
                set_time_limit(120);
228
                //
229
                //pega os dados do tema dois para as fun&ccedil;&otilde;es que o utilizam
230
                //
231
                $dados1 = $this->gravaCoordenadasPt($this->nome,$limitepontos,$extendelimite,$item);
232
                $nomearq = $dados1["prefixoarquivo"];
233
                $dimx = $dados1["dimx"];
234
                $dimy = $dados1["dimy"];
235
                $dimz = $dados1["dimz"];
236
                if (isset($tema2) && $tema2 != ""){
237
                        $dados2 = $this->gravaCoordenadasPt($tema2,$limitepontos,$extendelimite);
238
                        $nomearq2 = $dados2["prefixoarquivo"];
239
                        $dimx2 = $dados2["dimx"];
240
                        $dimy2 = $dados2["dimy"];
241
                }
242
                switch ($tipo){
243
                        //cluster espacial
244
                        case "cluster":
245
                                $this->mapaCluster($nomearq,$nomearq2,$dimx,$dimy,$dir_tmp,$R_path,$locaplic);
246
                                return "ok";
247
                                break;
248
                                //delaunay e voronoi
249
                        case "deldir":
250
                                //error_reporting(0);
251
                                $this->mapaDeldir($nomearq,$dir_tmp,$R_path,$locaplic);
252
                                $this->deldirDir2shp($nomearq."dirsgs",$dir_tmp,$locaplic);
253
                                $this->deldirDel2shp($nomearq."delsgs",$dir_tmp,$locaplic);
254
                                return "ok";
255
                                break;
256
                        case "kernel":
257
                                $this->mapaKernel($nomearq,$dimx,$dimy,$dir_tmp,$R_path,$locaplic,$sigma);
258
                                break;
259
                        case "densidade":
260
                                $this->mapaDensidade($nomearq,$dimx,$dimy,$dir_tmp,$R_path,$locaplic,$dimz);
261
                                break;
262
                        case "distancia":
263
                                $this->mapaDistancia($nomearq,$dimx,$dimy,$dir_tmp,$R_path,$locaplic);
264
                                break;
265
                        case "relatorio":
266
                                $r = $this->mapaRelatorioAnaliseDist($nomearq,$dimx,$dimy,$dir_tmp,$R_path,$locaplic);
267
                                return($tmpurl.basename($this->diretorio)."/".basename($nomearq).'.htm');
268
                                break;
269
                }
270
                //cria a imagem
271
                $minmax = $this->criaImagemR($nomearq);
272
                //cria as cores
273
                include_once("class.palette.php");
274
                $cori = RGB2hex(explode(",",$cori));
275
                $corf = RGB2hex(explode(",",$corf));
276
                $myPalette=new palette(array($cori,$corf),($numclasses + 1));
277
                //cria os parametros das classes
278
                $cls = $this->classesRasterI($minmax[0],$minmax[1],$numclasses,$myPalette->colorRGB);
279

    
280
                if (count($cls) != $numclasses){
281
                        return("erro.");
282
                }
283
                //adiciona o novo tema
284
                if (file_exists($nomearq.".png")){
285
                        $novolayer = criaLayer($this->mapa,MS_LAYER_RASTER,MS_DEFAULT,($tipo." (".$this->nome.")"),$metaClasse="SIM");
286
                        $novolayer->set("data",$nomearq.".png");
287
                        $novolayer->set("template","none.htm");
288
                        $novolayer->setmetadata("download","sim");
289
                        //classes
290
                        $numclassesatual = $novolayer->numclasses;
291
                        for ($i=0; $i < $numclassesatual; ++$i){
292
                                $classe = $novolayer->getClass($i);
293
                                $classe->set("status",MS_DELETE);
294
                        }
295
                        for ($i=0; $i < $numclasses; ++$i){
296
                                $classe = ms_newClassObj($novolayer);
297
                                $novoestilo = ms_newStyleObj($classe);
298
                                $ncor = $novoestilo->color;
299
                                $cores = $cls[$i]["cores"];
300
                                $ncor->setrgb($cores[0],$cores[1],$cores[2]);
301
                                $classe->setexpression($cls[$i]["expressao"]);
302
                                $classe->set("name",$cls[$i]["nomeclasse"]);
303
                        }
304
                        $of = $this->mapa->outputformat;
305
                        //$of->set("imagemode",MS_IMAGEMODE_RGB);
306
                        //
307
                        //reposiciona o layer
308
                        //
309
                        $layer = $this->mapa->getlayerbyname($this->nome);
310
                        if($layer != ""){
311
                                $temp = ms_newLayerObj($this->mapa,$novolayer);
312
                                $novolayer->set("status",MS_DELETE);
313
                                $temp = ms_newLayerObj($this->mapa,$layer);
314
                                $layer->set("status",MS_DELETE);
315
                        }
316
                        else{
317
                                $indicel = $novolayer->index;
318
                                $numlayers = $this->mapa->numlayers;
319
                                $nummove = 0;
320
                                for ($i = $numlayers-1;$i > 0;$i--)
321
                                {
322
                                        $layerAbaixo = $this->mapa->getlayer($i);
323
                                        $tipo = $layerAbaixo->type;
324
                                        if (($tipo != 2) && ($tipo != 3))
325
                                        {
326
                                                $nummove++;
327
                                        }
328
                                }
329
                                if ($nummove > 2)
330
                                {
331
                                        for ($i=0;$i<=($nummove - 3);++$i)
332
                                        {
333
                                                $this->mapa->movelayerup($indicel);
334
                                        }
335
                                }
336
                        }
337
                }
338
                else
339
                {return("erro");
340
                }
341
                if(file_exists($this->qyfile))
342
                {
343
                        unlink($this->qyfile);
344
                }
345
                return($novolayer->name);
346
        }
347
        /*
348
         function: mapaRelatorioAnaliseDist
349

350
        Gera um relat�rio da an&aacute;lise de distribui&ccedil;&atilde;o de pontos.
351

352
        Executa script R para gerar relat�rio .
353

354
        parameters:
355

356
        $arqpt - Prefixo dos arquivos em disco com os pontos.
357

358
        $dimx - Range em x no formato R c(-54,-53).
359

360
        $dimy - Range em y no formato R c(-25,-23).
361

362
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver.
363

364
        $R_path - Onde fica o R.
365

366
        $locaplic - Onde fica o I3Geo.
367
        */
368
        function mapaRelatorioAnaliseDist($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
369
        {
370
                set_time_limit(180);
371
                $nomedir = dirname($arqpt)."/";
372
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
373
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
374
                $tipoimg = "bitmap";
375
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
376
                {
377
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
378
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
379
                                $rcode[] = $lib;
380
                        $tipoimg = "png";
381
                }
382
                else
383
                {
384
                        if(file_exists($locaplic."/pacotes/rlib/linux"))
385
                        {
386
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
387
                                $rcode[] = $lib;
388
                        }
389
                }
390
                $rcode[] = 'library(spatstat)';
391
                $rcode[] = 'oppp <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
392
                $rcode[] = 'img<-distmap(oppp)';
393
                $rcode[] = 'zz <- file("'.$arqpt.'.htm", "w")';
394
                $rcode[] = 'sink(zz)';
395
                $rcode[] = 'cat("<br><b>Dist&acirc;ncia</b>\n", file = zz)';
396
                $rcode[] = 'sink()';
397
                $rcode[] = $tipoimg.'(file="'.$nomedir.'distancia.png")';
398
                $rcode[] = 'plot(img,main="")';
399
                $rcode[] = 'points(oppp$x,oppp$y,pch="x",col=1)';
400
                $rcode[] = 'dev.off()';
401
                $rcode[] = 'sink(zz)';
402
                $rcode[] = 'cat("<br></pre><img src=distancia.png />\n", file = zz)';
403
                $rcode[] = 'cat("<br>Resumo<pre>\n", file = zz)';
404
                $rcode[] = 'summary(img)';
405
                $rcode[] = 'cat("<br></pre>Quartis<pre>\n", file = zz)';
406
                $rcode[] = 'quantile.im(img)';
407
                $rcode[] = 'sink(zz)';
408
                $rcode[] = 'cat("<br>Histograma\n", file = zz)';
409
                $rcode[] = 'sink()';
410
                $rcode[] = $tipoimg.'(file="'.$nomedir.'histdistancia.png")';
411
                $rcode[] = 'hist.im(img,main="")';
412
                $rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
413
                $rcode[] = 'dev.off()';
414
                $rcode[] = 'sink(zz)';
415
                $rcode[] = 'cat("<br><img src=histdistancia.png />\n", file = zz)';
416
                $rcode[] = 'cat("<br></pre>Perspectiva\n", file = zz)';
417
                $rcode[] = 'sink()';
418
                $rcode[] = $tipoimg.'(file="'.$nomedir.'perspdistancia.png")';
419
                $rcode[] = 'p<-persp.im(img,colmap=terrain.colors(128),shade=0.3,theta=30,phi=45,main="")';
420
                $rcode[] = 'dev.off()';
421
                $rcode[] = 'sink(zz)';
422
                $rcode[] = 'cat("<br><img src=perspdistancia.png />\n", file = zz)';
423
                $rcode[] = 'cat("<br></pre>Contorno\n", file = zz)';
424
                $rcode[] = 'sink()';
425
                $rcode[] = $tipoimg.'(file="'.$nomedir.'contordistancia.png")';
426
                $rcode[] = 'contour.im(img,main="")';
427
                $rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
428
                $rcode[] = 'dev.off()';
429
                $rcode[] = 'sink(zz)';
430
                $rcode[] = 'cat("<br><img src=contordistancia.png />\n", file = zz)';
431
                $rcode[] = 'sink()';
432
                $rcode[] = 'img<-density.ppp(oppp)';
433
                $rcode[] = 'sink(zz)';
434
                $rcode[] = 'cat("<br><b>Densidade</b>\n", file = zz)';
435
                $rcode[] = 'sink()';
436
                $rcode[] = $tipoimg.'(file="'.$nomedir.'densidade.png")';
437
                $rcode[] = 'plot(img,main="")';
438
                $rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
439
                $rcode[] = 'dev.off()';
440
                $rcode[] = 'sink(zz)';
441
                $rcode[] = 'cat("<br></pre><img src=densidade.png />\n", file = zz)';
442
                $rcode[] = 'cat("<br>Resumo<pre>\n", file = zz)';
443
                $rcode[] = 'summary(img)';
444
                $rcode[] = 'cat("<br></pre>Quartis<pre>\n", file = zz)';
445
                $rcode[] = 'quantile.im(img)';
446
                $rcode[] = 'sink(zz)';
447
                $rcode[] = 'cat("<br>Histograma\n", file = zz)';
448
                $rcode[] = 'sink()';
449
                $rcode[] = $tipoimg.'(file="'.$nomedir.'histdensidade.png")';
450
                $rcode[] = 'hist.im(img,main="")';
451
                $rcode[] = 'dev.off()';
452
                $rcode[] = 'sink(zz)';
453
                $rcode[] = 'cat("<br><img src=histdensidade.png />\n", file = zz)';
454
                $rcode[] = 'cat("<br></pre>Perspectiva\n", file = zz)';
455
                $rcode[] = 'sink()';
456
                $rcode[] = $tipoimg.'(file="'.$nomedir.'perspdensidade.png")';
457
                $rcode[] = 'p<-persp.im(img,colmap=terrain.colors(128),shade=0.3,theta=30,phi=45,main="")';
458
                $rcode[] = 'dev.off()';
459
                $rcode[] = 'sink(zz)';
460
                $rcode[] = 'cat("<br><img src=perspdensidade.png />\n", file = zz)';
461
                $rcode[] = 'cat("<br></pre>Contorno\n", file = zz)';
462
                $rcode[] = 'sink()';
463
                $rcode[] = $tipoimg.'(file="'.$nomedir.'contordensidade.png")#,height =600, width = 600, res = 72)';
464
                $rcode[] = 'contour.im(img,main="")';
465
                $rcode[] = 'points(oppp$x,oppp$y,pch="x",col=2)';
466
                $rcode[] = 'dev.off()';
467
                $rcode[] = 'sink(zz)';
468
                $rcode[] = 'cat("<br><img src=contordensidade.png />\n", file = zz)';
469
                $rcode[] = 'sink()';
470
                $rcode[] = 'close(zz)';
471
                $r = $this->executaR($rcode,$dir_tmp,$R_path);
472
        }
473
        /*
474
         function: mapaCluster
475

476
        Gera um mapa de cluster.
477

478
        Executa script R para gerar os dados.
479

480
        parameters:
481

482
        $arqpt - Prefixo dos arquivos em disco com os pontos.
483

484
        $dimx - Range em x no formato R c(-54,-53).
485

486
        $dimy - Range em y no formato R c(-25,-23).
487

488
        $dir_tmp - Diretorio tempor&aacute;rio do mapserver.
489

490
        $R_path - Onde fica o R.
491

492
        $locaplic - Onde fica o I3Geo.
493

494
        $sigma - Bandwidth for kernel smoother in "smooth" option.
495
        */
496
        function mapaCluster($arqpt,$arqpt2,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
497
        {
498
                $gfile_name = nomeRandomico(20);
499
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
500
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
501
                $rcode[] = 'dadosx2<-scan("'.$arqpt2.'x")';
502
                $rcode[] = 'dadosy2<-scan("'.$arqpt2.'y")';
503
                $rcode[] = 'd1<-data.frame(cbind(dadosx,dadosy))';
504
                $rcode[] = 'names(d1)<-(c("x","y"))';
505
                $rcode[] = 'd2<-data.frame(cbind(dadosx2,dadosy2))';
506
                $rcode[] = 'names(d2)<-(c("col1","col2"))';
507
                $rcode[] = 'd2<-as.matrix.data.frame(d2)';
508
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')){
509
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
510
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
511
                                $rcode[] = $lib;
512
                }
513
                else{
514
                        if(file_exists($locaplic."/pacotes/rlib/linux")){
515
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
516
                                $rcode[] = $lib;
517
                        }
518
                }
519
                $rcode[] = 'library(spatclus)';
520
                $rcode[] = 'RES <- clus(d1,d2,limx='.$dimx.',limy='.$dimy.',eps=0.2)';
521
                //var_dump($rcode);
522
                $r = $this->executaR($rcode,$dir_tmp,$R_path,$gfile_name);
523
                return "ok";
524
        }
525

    
526
        /*
527
         function: mapaKernel
528

529
        Gera um mapa de kernel.
530

531
        Executa script R para gerar a imagem.
532

533
        parameters:
534
        $arqpt - Prefixo dos arquivos em disco com os pontos.
535

536
        $dimx - Range em x no formato R c(-54,-53).
537

538
        $dimy - Range em y no formato R c(-25,-23).
539

540
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver.
541

542
        $R_path - Onde fica o R.
543

544
        $locaplic - Onde fica o I3Geo.
545

546
        $sigma - Bandwidth for kernel smoother in "smooth" option.
547
        */
548
        function mapaKernel($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic,$sigma=""){
549
                $gfile_name = nomeRandomico(20);
550
                $graf = "png";
551
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
552
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
553
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')){
554
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
555
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
556
                                $rcode[] = $lib;
557
                        $tipoimg = "png";
558
                }
559
                else{
560
                        if(file_exists($locaplic."/pacotes/rlib/linux")){
561
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
562
                                $rcode[] = $lib;
563
                        }
564
                }
565
                $rcode[] = 'library(spatstat)';
566
                $rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
567
                $rcode[] = 'img <- ksmooth.ppp(pt';
568
                if (is_numeric($sigma))
569
                {
570
                        $rcode[] = ',sigma='.$sigma.')';
571
                }
572
                else
573
                {$rcode[] = ')';
574
                }
575
                $rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
576
                $rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
577
                $rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
578
                $rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
579
                $rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
580
                $rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
581
                //var_dump($rcode);
582
                $r = $this->executaR($rcode,$dir_tmp,$R_path,$gfile_name);
583
                return "ok";
584
        }
585
        /*
586
         function: mapaDensidade
587

588
        Gera um mapa de densidade de pontos.
589

590
        Executa script R para gerar a imagem.
591

592
        parameters:
593
        $arqpt - Prefixo dos arquivos em disco com os pontos.
594

595
        $dimx - Range em x no formato R c(-54,-53).
596

597
        $dimy - Range em y no formato R c(-25,-23).
598

599
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver.
600

601
        $R_path - Onde fica o R.
602

603
        $locaplic - Onde fica o I3Geo.
604

605
        $dimz - arquivo opcional com os valores de z
606
        */
607
        function mapaDensidade($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic,$dimz=""){
608
                $gfile_name = nomeRandomico(20);
609
                $graf = "png";
610
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
611
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
612
                $rcode[] = 'dadosz<-scan("'.$arqpt.'z")';
613
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')){
614
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
615
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
616
                                $rcode[] = $lib;
617
                        $tipoimg = "png";
618
                }
619
                else{
620
                        if(file_exists($locaplic."/pacotes/rlib/linux")){
621
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
622
                                $rcode[] = $lib;
623
                        }
624
                }
625
                $rcode[] = 'library(spatstat)';
626
                $rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
627
                if($dimz == ""){
628
                        $rcode[] = 'img <- density.ppp(pt)';
629
                }
630
                else{
631
                        $rcode[] = 'img <- smooth.ppp(pt, weights = dadosz)';
632
                }
633
                $rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
634
                $rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
635
                $rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
636
                $rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
637
                $rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
638
                $rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
639
                $r = $this->executaR($rcode,$dir_tmp,$R_path,$gfile_name);
640
                return "ok";
641
        }
642
        /*
643
         function: mapaDistancia
644

645
        Gera um mapa de distancia de pontos.
646

647
        Executa script R para gerar a imagem.
648

649
        parameters:
650

651
        $arqpt - Prefixo dos arquivos em disco com os pontos.
652

653
        $dimx - Range em x no formato R c(-54,-53).
654

655
        $dimy - Range em y no formato R c(-25,-23).
656

657
        $dir_tmp - Diretorio tempor&aacute;rio do mapserver.
658

659
        $R_path - Onde fica o R.
660

661
        $locaplic - Onde fica o I3Geo.
662
        */
663
        function mapaDistancia($arqpt,$dimx,$dimy,$dir_tmp,$R_path,$locaplic)
664
        {
665
                $gfile_name = nomeRandomico(20);
666
                $graf = "png";
667
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
668
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
669
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
670
                {
671
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
672
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
673
                                $rcode[] = $lib;
674
                        $tipoimg = "png";
675
                }
676
                else
677
                {
678
                        if(file_exists($locaplic."/pacotes/rlib/linux"))
679
                        {
680
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
681
                                $rcode[] = $lib;
682
                        }
683
                }
684
                $rcode[] = 'library(spatstat)';
685
                $rcode[] = 'pt <- ppp(dadosx, dadosy, '.$dimx.','.$dimy.')';
686
                $rcode[] = 'img <- distmap(pt)';
687
                $rcode[] = 'cat(img$xstep,file="'.$arqpt.'h",fill=TRUE)';
688
                $rcode[] = 'cat(img$ystep,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
689
                $rcode[] = 'cat(img$xrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
690
                $rcode[] = 'cat(img$yrange,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
691
                $rcode[] = 'cat(img$dim,file="'.$arqpt.'h",append=TRUE,fill=TRUE)';
692
                $rcode[] = 'cat(img$v,file="'.$arqpt.'img",fill=FALSE)';
693
                $r = $this->executaR($rcode,$dir_tmp,$R_path,$gfile_name);
694
                return "ok";
695
        }
696
        /*
697
         function: mapaDeldir
698

699
        Calcula a triangula&ccedil;&atilde;o de Delaunay e diagrama de Voronoi.
700

701
        Para funcionar, &eacute; necess&aacute;rio a instala&ccedil;&atilde;o da biblioteca deldir do R.
702

703
        http://cran.r-project.org/web/packages/deldir
704

705
        parameters:
706

707
        $arqpt - Prefixo dos arquivos em disco com os pontos.
708

709
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver.
710

711
        $R_path - Onde fica o R.
712

713
        $locaplic - Onde fica o I3Geo.
714
        */
715
        function mapaDeldir($arqpt,$dir_tmp,$R_path,$locaplic)
716
        {
717
                $gfile_name = nomeRandomico(20);
718
                $rcode[] = 'dadosx<-scan("'.$arqpt.'x")';
719
                $rcode[] = 'dadosy<-scan("'.$arqpt.'y")';
720
                if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
721
                {
722
                        $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/win")';
723
                        if(file_exists($locaplic.'/pacotes/rlib/win'))
724
                                $rcode[] = $lib;
725
                }
726
                else
727
                {
728
                        if(file_exists($locaplic."/pacotes/rlib/linux"))
729
                        {
730
                                $lib = '.libPaths("'.$locaplic.'/pacotes/rlib/linux")';
731
                                $rcode[] = $lib;
732
                        }
733
                }
734
                $rcode[] = 'library(deldir)';
735

    
736
                $rcode[] = 'pt <- deldir(dadosx, dadosy)';
737
                $rcode[] = 'write.csv(pt$delsgs,file="'.$arqpt.'delsgs")';
738
                $rcode[] = 'write.csv(pt$dirsgs,file="'.$arqpt.'dirsgs")';
739
                $r = $this->executaR($rcode,$dir_tmp,$R_path,$gfile_name);
740
                return "ok";
741
        }
742
        /*
743
         function deldirDel2shp
744

745
        L&ecirc; um arquivo CSV gerado pelo software R com os dados referentes a triangula&ccedil;&atilde;o de Delaunay.
746

747
        O arquivo CSV &eacute; lido e convertido em um shape file que &eacute; ent&atilde;o adicionado ao mapa.
748

749
        Parametros:
750

751
        $nomearq - nome do arquivo CSV
752

753
        $dir_tmp - diretorio tempor&aacute;rio do Mapserver
754

755
        $locaplic - diretorio da aplica&ccedil;&atilde;o i3geo
756
        */
757
        function deldirDel2shp($nomearq,$dir_tmp,$locaplic)
758
        {
759
                if (file_exists($nomearq))
760
                {
761
                        if($this->dbaseExiste == false){
762
                                include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
763
                        }
764
                        //define o nome do novo shapefile que ser&aacute; criado
765
                        $nomefinal = nomeRandomico();
766
                        $nomeshp = $this->diretorio."/".$nomefinal;
767
                        //cria o shape file
768
                        $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_ARC);
769
                        // cria o dbf
770
                        $def[] = array("x1","N","12","5");
771
                        $def[] = array("y1","N","12","5");
772
                        $def[] = array("x2","N","12","5");
773
                        $def[] = array("y2","N","12","5");
774
                        $def[] = array("ind1","N","5","0");
775
                        $def[] = array("ind2","N","5","0");
776
                        if($this->dbaseExiste == false)
777
                        {
778
                                $db = xbase_create($nomeshp.".dbf", $def);
779
                        }
780
                        else
781
                        {$db = dbase_create($nomeshp.".dbf", $def);
782
                        }
783
                        $dbname = $nomeshp.".dbf";
784
                        //le o arquivo linha a linha, pulando a primeira
785
                        //acrescenta os pontos no shape file formando as linhas
786
                        $abre = fopen($nomearq, "r");
787
                        $buffer = fgets($abre);
788
                        $poligonos = array();
789
                        while (!feof($abre))
790
                        {
791
                                $buffer = fgets($abre);
792
                                $i = explode(",",$buffer);
793
                                if(is_array($i))
794
                                {
795
                                        $i1 = floatval($i[1]);
796
                                        $i2 = floatval($i[2]);
797
                                        $i3 = floatval($i[3]);
798
                                        $i4 = floatval($i[4]);
799
                                        $i5 = floatval($i[5]);
800
                                        $i6 = floatval($i[6]);
801
                                        $poPoint1 = ms_newpointobj();
802
                                        $poPoint1->setXY($i1,$i2);
803
                                        $poPoint2 = ms_newpointobj();
804
                                        $poPoint2->setXY($i3, $i4);
805
                                        $linha = ms_newLineObj();
806
                                        $linha->add($poPoint1);
807
                                        $linha->add($poPoint2);
808
                                        $ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
809
                                        $ShapeObj->add($linha);
810
                                        $novoshpf->addShape($ShapeObj);
811
                                        $registro = array($i1,$i2,$i3,$i4,$i5,$i6);
812
                                        if($this->dbaseExiste == false)
813
                                                xbase_add_record($db,$registro);
814
                                        else
815
                                                dbase_add_record($db,$registro);
816
                                }
817
                        }
818
                        if($this->dbaseExiste == false)
819
                                xbase_close($db);
820
                        else
821
                                dbase_close($db);
822
                        fclose($abre);
823
                        //adiciona no mapa atual o novo tema
824
                        $novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Delaunay (".$nomefinal.")"),$metaClasse="SIM");
825
                        $novolayer->set("data",$nomeshp.".shp");
826
                        $novolayer->setmetadata("DOWNLOAD","SIM");
827
                        $novolayer->set("template","none.htm");
828
                        $classe = $novolayer->getclass(0);
829
                        $estilo = $classe->getstyle(0);
830
                        $estilo->set("symbolname","linha");
831
                        $estilo->set("size",2);
832
                        $cor = $estilo->color;
833
                        $cor->setrgb(255,50,0);
834
                }
835
        }
836
        /*
837
         function deldirDir2shp
838

839
        L&ecirc; um arquivo CSV gerado pelo software R com os dados referentes ao diagrama de Voronoi.
840

841
        O arquivo CSV &eacute; lido e convertido em um shape file que &eacute; ent&atilde;o adicionado ao mapa.
842

843
        Parametros:
844

845
        $nomearq - nome do arquivo CSV
846

847
        $dir_tmp - diretorio tempor&aacute;rio do Mapserver
848

849
        $locaplic - diretorio da aplica&ccedil;&atilde;o i3geo
850
        */
851
        function deldirDir2shp($nomearq,$dir_tmp,$locaplic)
852
        {
853
                if (file_exists($nomearq))
854
                {
855
                        if($this->dbaseExiste == false){
856
                                include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
857
                        }
858
                        //
859
                        //define os nomes dos novos shapefiles que ser&atilde;o criados
860
                        //
861
                        $nomeLinhas = nomeRandomico();
862
                        $nomePoligonos = nomeRandomico();
863
                        $nomeshpLinhas = $this->diretorio."/".$nomeLinhas;
864
                        $nomeshpPoligonos = $this->diretorio."/".$nomePoligonos;
865
                        //cria o shape file
866
                        $novoshpLinhas = ms_newShapefileObj($nomeshpLinhas, MS_SHP_ARC);
867
                        $novoshpPoligonos = ms_newShapefileObj($nomeshpPoligonos, MS_SHP_POLYGON);
868
                        //
869
                        // cria o dbf para o shapefile linear
870
                        //
871
                        $def[] = array("x1","N","12","5");
872
                        $def[] = array("y1","N","12","5");
873
                        $def[] = array("x2","N","12","5");
874
                        $def[] = array("y2","N","12","5");
875
                        $def[] = array("ind1","N","5","0");
876
                        $def[] = array("ind2","N","5","0");
877
                        $def[] = array("b1","C","6");
878
                        $def[] = array("b2","C","6");
879
                        if($this->dbaseExiste == false)
880
                        {
881
                                $dbLinhas = xbase_create($nomeshpLinhas.".dbf", $def);
882
                        }
883
                        else
884
                        {$dbLinhas = dbase_create($nomeshpLinhas.".dbf", $def);
885
                        }
886
                        $dbnameLinhas = $nomeshpLinhas.".dbf";
887
                        //
888
                        // cria o dbf para o shapefile poligonal
889
                        //
890
                        $def = array();
891
                        $def[] = array("area","N","12","5");
892
                        if($this->dbaseExiste == false)
893
                        {
894
                                $dbPoligonos = xbase_create($nomeshpPoligonos.".dbf", $def);
895
                        }
896
                        else
897
                        {$dbPoligonos = dbase_create($nomeshpPoligonos.".dbf", $def);
898
                        }
899
                        $dbnamePoligonos = $nomeshpPoligonos.".dbf";
900
                        //
901
                        //constr�i as linhas do diagrama
902
                        //
903
                        //le o arquivo linha a linha, pulando a primeira
904
                        //acrescenta os pontos no shape file formando as linhas
905
                        //cria o array para criar os pol&iacute;gonos
906
                        //
907
                        $abre = fopen($nomearq, "r");
908
                        $buffer = fgets($abre);
909
                        $borda = array();//guarda os pontos que ficam na borda
910
                        $poligonos = array();
911
                        while (!feof($abre))
912
                        {
913
                                $buffer = fgets($abre);
914
                                $i = explode(",",$buffer);
915
                                if(is_array($i))
916
                                {
917
                                        $i1 = floatval($i[1]);
918
                                        $i2 = floatval($i[2]);
919
                                        $i3 = floatval($i[3]);
920
                                        $i4 = floatval($i[4]);
921
                                        $i5 = floatval($i[5]);
922
                                        $i6 = floatval($i[6]);
923
                                        $poPoint1 = ms_newpointobj();
924
                                        $poPoint1->setXY($i1,$i2);
925
                                        $poPoint2 = ms_newpointobj();
926
                                        $poPoint2->setXY($i3, $i4);
927
                                        if(trim($i[7]) == "TRUE")
928
                                        {
929
                                                $borda[] = $poPoint1;
930
                                        }
931
                                        if(trim($i[8]) == "TRUE")
932
                                        {
933
                                                $borda[] = $poPoint2;
934
                                        }
935
                                        $linha = ms_newLineObj();
936
                                        $linha->add($poPoint1);
937
                                        $linha->add($poPoint2);
938
                                        if($poligonos[$i[5]])
939
                                                $poligonos[$i[5]] = array_merge(array($linha),$poligonos[$i[5]]);
940
                                        else
941
                                                $poligonos[$i[5]] = array($linha);
942
                                        if($poligonos[$i[6]])
943
                                                $poligonos[$i[6]] = array_merge(array($linha),$poligonos[$i[6]]);
944
                                        else
945
                                                $poligonos[$i[6]] = array($linha);
946
                                        $ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
947
                                        $ShapeObj->add($linha);
948
                                        $novoshpLinhas->addShape($ShapeObj);
949
                                        $registro = array($i1,$i2,$i3,$i4,$i5,$i6,$i[7],$i[8]);
950
                                        if($this->dbaseExiste == false)
951
                                                xbase_add_record($dbLinhas,$registro);
952
                                        else
953
                                                dbase_add_record($dbLinhas,$registro);
954
                                }
955
                        }
956
                        //
957
                        //adiciona os poligonos
958
                        //
959
                        foreach ($poligonos as $p)
960
                        {
961
                                $ShapeObjp = ms_newShapeObj(MS_SHAPE_LINE);
962
                                foreach ($p as $o)
963
                                {
964
                                        $ShapeObjp->add($o);
965
                                }
966
                                $ns = $ShapeObjp->convexhull();
967
                                $novoshpPoligonos->addShape($ns);
968
                                $registro = array($ns->getArea());
969
                                if($this->dbaseExiste == false)
970
                                        xbase_add_record($dbPoligonos,$registro);
971
                                else
972
                                        dbase_add_record($dbPoligonos,$registro);
973
                        }
974
                        if($this->dbaseExiste == false)
975
                                xbase_close($dbPoligonos);
976
                        else
977
                                dbase_close($dbPoligonos);
978
                        //
979
                        //adiciona o layer com os pol&iacute;gonos no mapa
980
                        //
981
                        $novolayerp = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Voronoi - poligonos (".$nomePoligonos.")"),$metaClasse="SIM");
982
                        $novolayerp->set("data",$nomeshpPoligonos.".shp");
983
                        $novolayerp->setmetadata("DOWNLOAD","SIM");
984
                        $novolayerp->set("template","none.htm");
985
                        $classe = $novolayerp->getclass(0);
986
                        $estilo = $classe->getstyle(0);
987
                        $cor = $estilo->color;
988
                        $cor->setrgb(240,240,240);
989
                        //
990
                        //adiciona no mapa atual o novo tema com as linhas do diagrama
991
                        //
992
                        if (count($borda > 2))
993
                        {
994
                                $linha = ms_newLineObj();
995
                                foreach ($borda as $ponto)
996
                                {
997
                                        $linha->add($ponto);
998
                                }
999
                                $ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
1000
                                $ShapeObj->add($linha);
1001
                                $novoshpLinhas->addShape($ShapeObj->convexhull());
1002
                                $registro = array(0,0,0,0,0,0,0,0);
1003
                                if($this->dbaseExiste == false)
1004
                                        xbase_add_record($dbLinhas,$registro);
1005
                                else
1006
                                        dbase_add_record($dbLinhas,$registro);
1007
                        }
1008
                        if($this->dbaseExiste == false)
1009
                                xbase_close($dbLinhas);
1010
                        else
1011
                                dbase_close($dbLinhas);
1012
                        fclose($abre);
1013
                        $novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Voronoi (".$nomeLinhas.")"),$metaClasse="SIM");
1014
                        $novolayer->set("data",$nomeshpLinhas.".shp");
1015
                        $novolayer->setmetadata("DOWNLOAD","SIM");
1016
                        $novolayer->set("template","none.htm");
1017
                        $classe = $novolayer->getclass(0);
1018
                        $estilo = $classe->getstyle(0);
1019
                        $estilo->set("symbolname","linha");
1020
                        $estilo->set("size",4);
1021
                        $cor = $estilo->color;
1022
                        $cor->setrgb(255,210,0);
1023
                }
1024
        }
1025
        /*
1026
         function: pontoEmPoligono
1027

1028
        Cruza um tema pontual com temas poligonais ou raster.
1029

1030
        Salva o mapa acrescentando um novo layer com o resultado.
1031

1032
        parameters:
1033

1034
        $temaPt - Tema de pontos que ser&aacute; utilizado.
1035

1036
        $temaPo - Temas poligonais separados por virgula.
1037

1038
        $locaplic - Localiza&ccedil;&atilde;o do I3geo.
1039
        */
1040
        function pontoEmPoligono($temaPt,$temasPo,$locaplic)
1041
        {
1042
                set_time_limit(3000);
1043
                if($this->dbaseExiste == false){
1044
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1045
                }
1046
                $layerPt = $this->mapa->getlayerbyname($temaPt);
1047
                $layerPt->set("template","none.htm");
1048
                $layerPt->set("tolerance",0);
1049
                //define o nome do novo shapefile que ser&aacute; criado
1050
                $nomefinal = nomeRandomico();
1051
                $nomeshp = $this->diretorio."/".$nomefinal;
1052
                //
1053
                $spts = retornaShapesSelecionados($layerPt,$this->arquivo,$this->mapa);
1054
                if(count($spts) == 0){
1055
                        $spts = retornaShapesMapext($layerPt,$this->mapa);
1056
                }
1057
                //
1058
                $itemspt = pegaItens($layerPt);
1059
                //gera o novo arquivo shape file
1060
                // cria o dbf
1061
                $def = $this->criaDefDb($itemspt,false);
1062
                //pega os itens dos temas poligonais
1063
                $layersPol = array();
1064
                $temas = explode(",",$temasPo);
1065
                $layers = array();
1066
                $nomesitens = array(); //guarda os nomes dos temas e seus itens
1067
                $conta = 0;
1068
                $listaItens = array();
1069
                foreach ($temas as $tema)
1070
                {
1071
                        $layer = $this->mapa->getlayerbyname($tema);
1072
                        $layer->set("template","none.htm");
1073
                        $layer->set("status",MS_DEFAULT);
1074
                        $items = pegaItens($layer);
1075
                        if($layer->type == MS_LAYER_RASTER)
1076
                        {
1077
                                $lineo = $spts[0]->line(0);
1078
                                $pt = $lineo->point(0);
1079
                                $layer->queryByPoint($pt, 0, 0);
1080
                        }
1081
                        $layers[] = $layer;
1082

    
1083
                        if(!$items)
1084
                        {
1085
                                return "erro ao obter a lista de itens do tema $layer->name";
1086
                        }
1087
                        $listaItens[$layer->name] = $items;
1088
                        foreach ($items as $ni)
1089
                        {
1090
                                $def[] = array("I".$conta,"C","254");
1091
                                $nomesitens[] = "Tema: ".$layer->name.", Item: ".$ni." Novo: I".$conta."<br>";
1092
                                $conta = $conta + 1;
1093
                        }
1094
                }
1095
                if($this->dbaseExiste == false)
1096
                {
1097
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1098
                }
1099
                else
1100
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1101
                }
1102
                //acrescenta os pontos no novo shapefile
1103
                $dbname = $nomeshp.".dbf";
1104
                if($this->dbaseExiste == false)
1105
                        $db=xbase_open($dbname,2);
1106
                else
1107
                        $db=dbase_open($dbname,2);
1108
                // cria o shapefile
1109
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
1110
                foreach($spts as $spt)
1111
                {
1112
                        foreach ($itemspt as $ni)
1113
                        {
1114
                                $reg[] = $this->truncaS($spt->values[$ni]);
1115
                        }
1116
                        $novoshpf->addShape($spt);
1117
                        $lineo = $spt->line(0);
1118
                        $pt = $lineo->point(0);
1119
                        //faz a pesquisa
1120
                        //error_reporting(0);
1121
                        foreach ($layers as $layer)
1122
                        {
1123
                                $layer->set("template","none.htm");
1124
                                $layer->set("toleranceunits",MS_PIXELS);
1125
                                $layer->set("tolerance",1);
1126
                                $ident = @$layer->queryByPoint($pt, 0, 0);
1127
                                if($ident == "MS_SUCCESS"){
1128
                                        $itens = $listaItens[$layer->name];
1129
                                        $sopen = $layer->open();
1130
                                        if($sopen == MS_FAILURE){
1131
                                                return "erro";
1132
                                        }
1133
                                        if ($layer->getResult(0) !== FALSE)
1134
                                        {
1135
                                                if($this->v >= 6)
1136
                                                {
1137
                                                        $shape = $layer->getShape($layer->getResult(0));
1138
                                                }
1139
                                                else{
1140
                                                        $result = $layer->getResult(0);
1141
                                                        $shp_index  = $result->shapeindex;
1142
                                                        $shape = $layer->getfeature($shp_index,-1);
1143
                                                }
1144
                                                foreach ($itens as $item)
1145
                                                {
1146
                                                        $p = $this->truncaS($shape->values[$item]);
1147
                                                        if(empty($p))
1148
                                                        {
1149
                                                                $p = "-";
1150
                                                        }
1151
                                                        $reg[] = $p;
1152
                                                }
1153
                                        }
1154
                                        else
1155
                                        {
1156
                                                foreach ($itens as $item)
1157
                                                {
1158
                                                        $reg[] = "???";
1159
                                                }
1160
                                        }
1161
                                }
1162
                                else
1163
                                {
1164
                                        foreach ($itens as $item)
1165
                                        {
1166
                                                $reg[] = "???";
1167
                                        }
1168
                                }
1169
                                $layer->close();
1170
                        }
1171
                        if($this->dbaseExiste == false)
1172
                                xbase_add_record($db,$reg);
1173
                        else
1174
                                dbase_add_record($db,$reg);
1175
                        $reg = array();
1176
                }
1177
                if($this->dbaseExiste == false)
1178
                        xbase_close($db);
1179
                else
1180
                        dbase_close($db);
1181
                $novolayer = ms_newLayerObj($this->mapa, $layerPt);
1182
                $novolayer->set("data",$nomeshp.".shp");
1183
                $novolayer->set("name",$nomefinal);
1184
                $novolayer->setmetadata("TEMA","Cruzamento (".$nomefinal.")");
1185
                $novolayer->setmetadata("TEMALOCAL","SIM");
1186
                $novolayer->setmetadata("DOWNLOAD","SIM");
1187
                $novolayer->setmetadata("ITENS","");
1188
                $novolayer->setmetadata("ITENSDESC","");
1189
                $novolayer->setmetadata("CACHE","");
1190
                if(ms_GetVersionInt() > 50201)
1191
                {
1192
                        $novolayer->setconnectiontype(MS_SHAPEFILE);
1193
                }
1194
                else
1195
                {$novolayer->set("connectiontype",MS_SHAPEFILE);
1196
                }
1197
                if (file_exists($this->qyfile))
1198
                {
1199
                        unlink ($this->qyfile);
1200
                }
1201
                return(implode(" ",$nomesitens));
1202
        }
1203
        /*
1204
         function: distanciaptpt
1205

1206
        Calcula a distancia entre um ponto de origem e os pontos em um tema.
1207

1208
        S&atilde;o considerados apenas os pontos dentro de um tema de overlay.
1209

1210
        parameters:
1211

1212
        temaorigem - nome do layer com o ponto de origem
1213

1214
        temadestino - nome do tema com os pontos de destino
1215

1216
        temaoverlay - tema que ser&aacute; utilizado para selecionar o tema de destino
1217

1218
        locapli - endere&ccedil;o da aplica&ccedil;&atilde;o i3geo
1219

1220
        itemorigem - nome do item na tabela de atributos do tema de origem que ser&aacute; acrescentado ao tema que ser&aacute; criado
1221

1222
        itemdestino - nome do item na tabela de atributos do tema de origem que ser&aacute; acrescentado ao tema que ser&aacute; criado
1223

1224
        */
1225
        function distanciaptpt($temaorigem,$temadestino,$temaoverlay,$locaplic,$itemorigem="",$itemdestino="")
1226
        {
1227
                //error_reporting(0);
1228
                set_time_limit(180);
1229
                //para manipular dbf
1230
                if($this->dbaseExiste == false){
1231
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1232
                }
1233
                //define o nome do novo shapefile que ser&aacute; criado
1234
                $nomefinal = nomeRandomico();
1235
                $nomeshp = $this->diretorio."/".$nomefinal;
1236

    
1237
                $existesel = carregaquery2($this->arquivo,$this->layer,$this->mapa);
1238
                if ($existesel == "nao")
1239
                {
1240
                        return "errox";
1241
                }
1242

    
1243
                $layerorigem = $this->mapa->getlayerbyname($temaorigem);
1244
                $layerdestino = $this->mapa->getlayerbyname($temadestino);
1245
                $layeroverlay = $this->mapa->getlayerbyname($temaoverlay);
1246

    
1247
                $shapesorigem = retornaShapesSelecionados($layerorigem,$this->arquivo,$this->mapa);
1248
                if(count($shapesorigem) == 0){
1249
                        return "erro";
1250
                }
1251
                $layeroverlay->set("tolerance",0);
1252
                $layerdestino->set("tolerance",0);
1253
                $layeroverlay->queryByrect($this->mapa->extent);
1254
                $layerdestino->queryByFeatures($layeroverlay->index);
1255

    
1256
                $sopen = $layerdestino->open();
1257
                if($sopen == MS_FAILURE){
1258
                        return "erro";
1259
                }
1260
                $res_count = $layerdestino->getNumresults();
1261

    
1262
                for ($i = 0; $i < $res_count; ++$i)
1263
                {
1264
                        if($this->v >= 6)
1265
                        {
1266
                                $shapesdestino[] = $layerdestino->getShape($layerdestino->getResult($i));
1267
                        }
1268
                        else{
1269
                                $result = $layerdestino->getResult($i);
1270
                                $shp_index  = $result->shapeindex;
1271
                                $shapesdestino[] = $layerdestino->getshape(-1, $shp_index);
1272
                        }
1273
                }
1274
                $layerdestino->close();
1275
                $rect = $this->mapa->extent;
1276
                $projInObj = $layerorigem->getProjection();
1277
                if ($projInObj == ""){
1278
                        $projInObj = ms_newprojectionobj("proj=longlat,ellps=WGS84,datum=WGS84,no_defs");
1279
                }
1280
                $projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000");
1281
                $origemdestino = array();
1282
                if (count($shapesorigem)==0){
1283
                        return "erro";
1284
                }
1285
                if (count($shapesdestino)==0){
1286
                        return "erro";
1287
                }
1288
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_ARC);
1289
                // cria o dbf
1290
                $def[] = array("dist_m","N","10","2");
1291
                $def[] = array("origem","C","255");
1292
                $def[] = array("destino","C","255");
1293
                if($this->dbaseExiste == false){
1294
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1295
                }
1296
                else{
1297
                        $db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1298
                }
1299
                //acrescenta os pontos no novo shapefile
1300
                $dbname = $nomeshp.".dbf";
1301
                if($this->dbaseExiste == false)
1302
                        $db=xbase_open($dbname,2);
1303
                else
1304
                        $db=dbase_open($dbname,2);
1305
                foreach ($shapesorigem as $sorigem){
1306
                        if($itemorigem != ""){
1307
                                $valororigem = $sorigem->values[$itemorigem];
1308
                        }
1309
                        else{
1310
                                $valororigem = "";
1311
                        }
1312
                        foreach ($shapesdestino as $sdestino)
1313
                        {
1314
                                $linha = ms_newLineObj();
1315
                                $linha->add($sorigem->getCentroid());
1316
                                $linha->add($sdestino->getCentroid());
1317
                                if($itemdestino != ""){
1318
                                        $valordestino = $sdestino->values[$itemdestino];
1319
                                }
1320
                                else{
1321
                                        $valordestino = "";
1322
                                }
1323
                                $ShapeObj = ms_newShapeObj(MS_SHAPE_LINE);
1324
                                $ShapeObj->add($linha);
1325
                                $novoshpf->addShape($ShapeObj);
1326
                                $ShapeObj->project($projInObj, $projOutObj);
1327
                                $distancia = $ShapeObj->getLength();
1328
                                $registro = array($distancia,$valororigem,$valordestino);
1329
                                if($this->dbaseExiste == false)
1330
                                        xbase_add_record($db,$registro);
1331
                                else
1332
                                        dbase_add_record($db,$registro);
1333
                        }
1334
                }
1335
                if($this->dbaseExiste == false)
1336
                        xbase_close($db);
1337
                else
1338
                        dbase_close($db);
1339
                //adiciona no mapa atual o novo tema
1340
                $novolayer = criaLayer($this->mapa,MS_LAYER_LINE,MS_DEFAULT,("Distancias (".$nomefinal.")"),$metaClasse="SIM");
1341
                $novolayer->set("data",$nomeshp.".shp");
1342
                $novolayer->setmetadata("DOWNLOAD","SIM");
1343
                $novolayer->set("template","none.htm");
1344
                $classe = $novolayer->getclass(0);
1345
                $estilo = $classe->getstyle(0);
1346
                $estilo->set("symbolname","linha");
1347
                $estilo->set("size",4);
1348
                $cor = $estilo->color;
1349
                $cor->setrgb(255,210,0);
1350
                //limpa selecao
1351
                if (file_exists($this->qyfile))
1352
                {
1353
                        unlink ($this->qyfile);
1354
                }
1355
                return($nomeshp.".shp");
1356
        }
1357
        /*
1358
         Function: criaBuffer
1359

1360
        Gera entorno (buffer) nos elementos selecionados de um tema.
1361

1362
        Salva o mapa acrescentando um novo layer com o buffer.
1363

1364
        Parametros:
1365

1366
        $distancia - Dist&acirc;ncia em metros.
1367

1368
        $locaplic - Localiza&ccedil;&atilde;o do I3geo.
1369

1370
        $unir - sim|nao indica se os elementos selecionados dever&atilde;o ser unidos em um s� antes do buffer ser criado
1371

1372
        $wkt - (opcional) elemento no formato wkt para o qual o buffer ser&aacute; gerado. S� de ve ser definido se $this->nome for vazio, ou seja
1373
        se o par&acirc;metro "tema" n&atilde;o tiver sido fornecido ao construtor da classe
1374

1375
        $multiplicar - (opcional) multiplicar os valores por
1376

1377
        $itemdistancia - (opcional) coluna com os valores
1378

1379
        return:
1380

1381
        nome do layer criado com o buffer.
1382
        */
1383
        function criaBuffer($distancia,$locaplic,$unir="nao",$wkt="",$multiplicar=1,$itemdistancia=""){
1384
                set_time_limit(180);
1385
                error_reporting(0);
1386
                if($this->nome != ""){
1387
                        $items = pegaItens($this->layer);
1388
                }
1389
                else{
1390
                        $items = array();
1391
                }
1392
                //para manipular dbf
1393
                if($this->dbaseExiste == false){
1394
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1395
                }
1396
                $nomebuffer = nomeRandomico();
1397
                $nomeshp = $this->diretorio."/".$nomebuffer;
1398
                $listaShapes = array();
1399
                if($this->nome != ""){
1400
                        $listaShapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
1401
                }
1402
                else{
1403
                        $s = ms_shapeObjFromWkt($wkt);
1404
                        $s->values["ID"] = 0;
1405
                        $items[] = "ID";
1406
                        $listaShapes[] = $s;
1407
                }
1408
                foreach($listaShapes as $shape){
1409
                        //calcula a extens&atilde;o geografica
1410
                        $rect = $shape->bounds;
1411
                        //proj=longlat,ellps=WGS84,datum=WGS84,no_defs
1412
                        //proj=latlong
1413
                        $projInObj = ms_newprojectionobj("proj=longlat,ellps=WGS84,datum=WGS84,no_defs");
1414
                        $projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000");
1415
                        $poPoint = ms_newpointobj();
1416
                        $poPoint->setXY($rect->minx, $rect->miny);
1417
                        $dd1 = ms_newpointobj();
1418
                        $dd1->setXY($rect->minx, $rect->miny);
1419
                        $poPoint->project($projInObj, $projOutObj);
1420
                        $dd2 = ms_newpointobj();
1421
                        if($itemdistancia != ""){
1422
                                $distancia = $shape->values[$itemdistancia];
1423
                        }
1424
                        if(is_numeric($distancia)){
1425
                                $dd2->setXY(($poPoint->x) + ($distancia * $multiplicar), $poPoint->y);
1426
                                $dd2->project($projOutObj,$projInObj);
1427
                                $d = $dd1->distanceToPoint($dd2);
1428
                                if ($distancia < 0){
1429
                                        $d = $d * -1;
1430
                                }
1431
                                //calcula a distancia 29100
1432
                                //gera o buffer
1433
                                $buffers[] = $shape->buffer($d);
1434
                                $shapes[] = $shape;
1435
                        }
1436
                }
1437
                //faz a uni&atilde;o dos elementos se necess&aacute;rio
1438
                if($unir == "sim"){
1439
                        $ns = $buffers[0];
1440
                        for($s=1;$s < count($buffers);$s++){
1441
                                $ns = $ns->union($buffers[$s]);
1442
                        }
1443
                        $buffers = array($ns);
1444
                        $shapes = array($shapes[0]);
1445
                }
1446
                //gera o novo arquivo shape file
1447
                // cria o shapefile
1448
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
1449
                // cria o dbf
1450
                $def = $this->criaDefDb($items);
1451
                $def[] = array("i3geo","C","254");
1452
                if($this->dbaseExiste == false){
1453
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1454
                }
1455
                else{
1456
                        $db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1457
                }
1458
                //acrescenta os pontos no novo shapefile
1459
                $dbname = $nomeshp.".dbf";
1460
                if($this->dbaseExiste == false)
1461
                        $db=xbase_open($dbname,2);
1462
                else
1463
                        $db=dbase_open($dbname,2);
1464
                for($i = 0;$i < count($buffers);++$i){
1465
                        foreach ($items as $ni){
1466
                                if(!empty($shapes[$i]->values[$ni])){
1467
                                        $reg[] = $this->truncaS($shapes[$i]->values[$ni]);
1468
                                }
1469
                                else{
1470
                                        $reg[] = "";
1471
                                }
1472
                        }
1473
                        $reg[] = $i;
1474
                        $novoshpf->addShape($buffers[$i]);
1475
                        if($this->dbaseExiste == false)
1476
                                xbase_add_record($db,$reg);
1477
                        else
1478
                                dbase_add_record($db,$reg);
1479

    
1480
                        $reg = array();
1481
                }
1482
                if($this->dbaseExiste == false)
1483
                        xbase_close($db);
1484
                else
1485
                        dbase_close($db);
1486
                //adiciona no mapa atual o novo tema
1487
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Buffer (".$nomebuffer.")"),$metaClasse="SIM",false);
1488
                $novolayer->set("data",$nomeshp.".shp");
1489
                $novolayer->setmetadata("DOWNLOAD","SIM");
1490
                $novolayer->set("template","none.htm");
1491
                $classe = $novolayer->getclass(0);
1492
                $estilo = $classe->getstyle(0);
1493
                $estilo->set("symbolname","p4");
1494
                $estilo->set("size",5);
1495
                $cor = $estilo->color;
1496
                $cor->setrgb(255,0,0);
1497
                $coro = $estilo->outlinecolor;
1498
                $coro->setrgb(255,0,0);
1499
                return($novolayer->name);
1500
        }
1501
        /*
1502
         function: centroMassa
1503

1504
        Calcula o centro m&eacute;dio.
1505

1506
        Se "item" for diferente de vazio, calcula o centro m&eacute;dio ponderado baseado no item
1507

1508
        Parametros:
1509

1510
        $item {string} - (opcional) Item q ser&aacute; utilizado para ponderar os valores.
1511
        */
1512
        function centroMassa($item="")
1513
        {
1514
                if(!$this->layer){
1515
                        return "erro";
1516
                }
1517
                set_time_limit(180);
1518
                //para manipular dbf
1519
                if($this->dbaseExiste == false){
1520
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1521
                }
1522
                //error_reporting(0);
1523
                $nomeCentro = nomeRandomico();
1524
                $nomeshp = $this->diretorio."/".$nomeCentro;
1525
                //pega os shapes selecionados
1526
                $lshapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
1527
                if(count($lshapes) == 0){
1528
                        $lshapes = retornaShapesMapext($this->layer,$this->mapa);
1529
                }
1530
                $pondera = 1;
1531
                $xs = 0;
1532
                $ys = 0;
1533
                foreach($lshapes as $shape){
1534
                        if($item != "")
1535
                        {
1536
                                $pondera = $shape->values[$item];
1537
                        }
1538
                        $pt = $shape->line(0)->point(0);
1539
                        $xs += ($pt->x * $pondera);
1540
                        $ys += ($pt->y * $pondera);
1541
                }
1542
                //gera o novo arquivo shape file
1543
                // cria o shapefile
1544
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
1545
                // cria o dbf
1546
                $def[] = array("id","C","254");
1547
                if($this->dbaseExiste == false)
1548
                {
1549
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1550
                }
1551
                else
1552
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1553
                }
1554
                //acrescenta os pontos no novo shapefile
1555
                $dbname = $nomeshp.".dbf";
1556
                if($this->dbaseExiste == false)
1557
                        $db=xbase_open($dbname,2);
1558
                else
1559
                        $db=dbase_open($dbname,2);
1560
                $reg[] = "";
1561
                $res_count = count($lshapes);
1562
                $shp = ms_newShapeObj(MS_SHP_POINT);
1563
                $linha = ms_newLineObj();
1564
                $linha->addXY(($xs / $res_count),($ys / $res_count));
1565
                $shp->add($linha);
1566

    
1567
                $novoshpf->addShape($shp);
1568
                if($this->dbaseExiste == false)
1569
                        xbase_add_record($db,$reg);
1570
                else
1571
                        dbase_add_record($db,$reg);
1572
                if($this->dbaseExiste == false)
1573
                        xbase_close($db);
1574
                else
1575
                        dbase_close($db);
1576
                //adiciona no mapa atual o novo tema
1577
                $novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Centr�ide (".$nomeCentro.")"),$metaClasse="SIM");
1578
                $novolayer->set("data",$nomeshp.".shp");
1579
                $novolayer->setmetadata("DOWNLOAD","SIM");
1580
                $novolayer->set("template","none.htm");
1581
                $novolayer->setmetadata("TEMALOCAL","SIM");
1582
                $classe = $novolayer->getclass(0);
1583
                $estilo = $classe->getstyle(0);
1584
                $estilo->set("size","14");
1585
                //limpa selecao
1586
                if (file_exists($this->qyfile))
1587
                {
1588
                        unlink ($this->qyfile);
1589
                }
1590
                return("ok");
1591
        }
1592
        /*
1593
         function: criaCentroide
1594

1595
        Gera centroide dos elementos selecionados de um tema.
1596

1597
        Salva o mapa acrescentando um novo layer com os pontos.
1598

1599
        Parametros:
1600

1601
        $locaplic - Localiza&ccedil;&atilde;o do I3geo.
1602
        */
1603
        function criaCentroide($locaplic)
1604
        {
1605
                if(!$this->layer){
1606
                        return "erro";
1607
                }
1608
                $items = pegaItens($this->layer);
1609
                set_time_limit(180);
1610
                //para manipular dbf
1611
                if($this->dbaseExiste == false){
1612
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1613
                }
1614
                $nomeCentroides = nomeRandomico();
1615
                $nomeshp = $this->diretorio."/".$nomeCentroides;
1616
                $shapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
1617

    
1618
                //$shapes = $shape[0];
1619
                foreach($shapes as $shape){
1620
                        $LineObj = ms_newLineObj();
1621
                        $LineObj->add($shape->getCentroid());
1622
                        $ShapeObj = ms_newShapeObj(MS_SHAPE_POINT);
1623
                        $ShapeObj->add($LineObj);
1624
                        $centroides[] = $ShapeObj;
1625
                }
1626
                //gera o novo arquivo shape file
1627
                // cria o shapefile
1628
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
1629
                // cria o dbf
1630
                $def = $this->criaDefDb($items);
1631
                if($this->dbaseExiste == false)
1632
                {
1633
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1634
                }
1635
                else
1636
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1637
                }
1638
                //acrescenta os pontos no novo shapefile
1639
                $dbname = $nomeshp.".dbf";
1640
                if($this->dbaseExiste == false)
1641
                        $db=xbase_open($dbname,2);
1642
                else
1643
                        $db=dbase_open($dbname,2);
1644
                for($i = 0;$i < count($centroides);++$i)
1645
                {
1646
                        foreach ($items as $ni)
1647
                        {
1648
                                $reg[] = $this->truncaS($shapes[$i]->values[$ni]);
1649
                        }
1650
                        $novoshpf->addShape($centroides[$i]);
1651
                        if($this->dbaseExiste == false)
1652
                                xbase_add_record($db,$reg);
1653
                        else
1654
                                dbase_add_record($db,$reg);
1655
                        $reg = array();
1656
                }
1657
                if($this->dbaseExiste == false)
1658
                        xbase_close($db);
1659
                else
1660
                        dbase_close($db);
1661
                //adiciona no mapa atual o novo tema
1662
                $novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Centroide (".$nomeCentroides.")"),$metaClasse="SIM");
1663
                $novolayer->set("data",$nomeshp.".shp");
1664
                $novolayer->setmetadata("DOWNLOAD","SIM");
1665
                $novolayer->set("template","none.htm");
1666
                $novolayer->setmetadata("TEMALOCAL","SIM");
1667
                //limpa selecao
1668
                if (file_exists($this->qyfile))
1669
                {
1670
                        unlink ($this->qyfile);
1671
                }
1672
                return("ok");
1673
        }
1674

    
1675
        /*
1676
         function: gradeDePontos
1677

1678
        Gera uma grade de pontos com espa&ccedil;amento regular definido em d&eacute;cimos de grau.
1679

1680
        Salva o mapa acrescentando um novo layer com a grade de coordenadas.
1681

1682
        $ddx - Espa&ccedil;amento em x.
1683

1684
        $ddy - Espa&ccedil;amento em y.
1685

1686
        $px - X do primeiro ponto (superior esquerdo)
1687

1688
        $py - Y do primeiro ponto.
1689

1690
        $locaplic - Endere&ccedil;o da aplica&ccedil;&atilde;o.
1691

1692
        $nptx - N&uacute;mero de pontos em X (opcional)
1693

1694
        $npty - N&uacute;mero de pontos em Y (opcional)
1695
        */
1696
        function gradeDePontos($xdd,$ydd,$px,$py,$locaplic,$nptx,$npty,$proj=false)
1697
        {
1698
                set_time_limit(180);
1699
                //para manipular dbf
1700
                if($this->dbaseExiste == false){
1701
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1702
                }
1703
                $nomegrade = nomeRandomico();
1704
                $nomeshp = $this->diretorio."/".$nomegrade;
1705
                $this->mapa->preparequery();
1706
                $r = $this->mapa->extent;
1707
                $ext = ms_newRectObj();
1708
                $ext->setextent($r->minx,$r->miny,$r->maxx,$r->maxy);
1709
                if($proj == true){
1710
                        //caso precise projetar
1711
                        $projInObj = ms_newprojectionobj("proj=latlong,a=6378137,b=6378137");
1712
                        $projOutObj = ms_newprojectionobj("proj=merc,a=6378137,b=6378137,lat_ts=0.0,lon_0=0.0,x_0=0.0,y_0=0,k=1.0,units=m");
1713

    
1714
                        $ext->project($projInObj, $projOutObj);
1715

    
1716
                        $pt = ms_newpointobj();
1717
                        $pt->setXY($px,$py);
1718

    
1719
                        $pt->project($projInObj, $projOutObj);
1720

    
1721
                        $px = $pt->x;
1722
                        $py = $pt->y;
1723
                }
1724

    
1725
                $fx = $ext->maxx;
1726
                $fy = $ext->miny;
1727
                //calcula a dist&acirc;ncia entre os pontos em dd
1728
                $distx = $fx - $px;
1729
                $disty = $fy - $py;
1730
                if ($distx < 0){
1731
                        $distx = $distx * -1;
1732
                }
1733
                if ($disty < 0){
1734
                        $disty = $disty * -1;
1735
                }
1736
                if ($nptx == "")
1737
                {
1738
                        $nptx = round(($distx / $xdd),0);
1739
                }
1740
                if ($npty == "")
1741
                {
1742
                        $npty = round(($disty / $ydd),0);
1743
                }
1744
                // cria o shapefile
1745
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POINT);
1746
                $def = array();
1747
                $def[] = array("x","C","20");
1748
                $def[] = array("y","C","20");
1749
                if($this->dbaseExiste == false)
1750
                {
1751
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1752
                }
1753
                else
1754
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1755
                }
1756
                //acrescenta os pontos no novo shapefile
1757
                $dbname = $nomeshp.".dbf";
1758
                if($this->dbaseExiste == false)
1759
                        $db=xbase_open($dbname,2);
1760
                else
1761
                        $db=dbase_open($dbname,2);
1762
                $reg = array();
1763
                $valorcoluna = $px;
1764
                for ($coluna = 0; $coluna < $nptx; $coluna++)
1765
                {
1766
                        $x = $valorcoluna;
1767
                        $valorlinha = $py;
1768
                        for ($linha = 0; $linha < $npty; $linha++)
1769
                        {
1770
                                $y = $valorlinha;
1771
                                $valorlinha = $valorlinha - $ydd;
1772
                                $poPoint = ms_newpointobj();
1773
                                $poPoint->setXY($x,$y);
1774
                                if($proj == true){
1775
                                        $poPoint->project($projOutObj,$projInObj);
1776
                                }
1777
                                $novoshpf->addpoint($poPoint);
1778
                                $reg[] = $x;
1779
                                $reg[] = $y;
1780
                                if($this->dbaseExiste == false)
1781
                                        xbase_add_record($db,$reg);
1782
                                else
1783
                                        dbase_add_record($db,$reg);
1784
                                $reg = array();
1785
                        }
1786
                        $valorcoluna = $valorcoluna + $xdd;
1787
                }
1788
                if($this->dbaseExiste == false)
1789
                        xbase_close($db);
1790
                else
1791
                        dbase_close($db);
1792
                //adiciona o novo tema no mapa
1793
                $novolayer = criaLayer($this->mapa,MS_LAYER_POINT,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
1794
                $novolayer->set("data",$nomeshp.".shp");
1795
                $novolayer->setmetadata("DOWNLOAD","SIM");
1796
                $novolayer->setmetadata("TEMALOCAL","SIM");
1797
                if (file_exists($this->qyfile))
1798
                {
1799
                        unlink ($this->qyfile);
1800
                }
1801
                return("ok");
1802
        }
1803
        /*
1804
         function: gradeDePol
1805

1806
        Gera uma grade de pol&iacute;gonos com espa&ccedil;amento regular definido em d&eacute;cimos de grau.
1807

1808
        Salva o mapa acrescentando um novo layer com a grade.
1809

1810
        parameters:
1811

1812
        $xdd - Espa&ccedil;amento em x.
1813

1814
        $ydd - Espa&ccedil;amento em y.
1815

1816
        $x - X do primeiro ponto (superior esquerdo)
1817

1818
        $y - Y do primeiro ponto.
1819

1820
        $locaplic - Endere&ccedil;o da aplica&ccedil;&atilde;o.
1821

1822
        $nptx - N&uacute;mero de pontos em X (opcional)
1823

1824
        $npty - N&uacute;mero de pontos em Y (opcional)
1825
        */
1826
        function gradeDePol($xdd,$ydd,$px,$py,$locaplic,$nptx,$npty,$proj=false)
1827
        {
1828
                set_time_limit(180);
1829
                //para manipular dbf
1830
                if($this->dbaseExiste == false){
1831
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1832
                }
1833
                $nomegrade = nomeRandomico();
1834
                $nomeshp = $this->diretorio."/".$nomegrade;
1835
                //pega a extens&atilde;o geogr&aacute;fica do mapa
1836
                $this->mapa->preparequery();
1837
                $r = $this->mapa->extent;
1838
                $ext = ms_newRectObj();
1839
                $ext->setextent($r->minx,$r->miny,$r->maxx,$r->maxy);
1840
                if($proj == true){
1841
                        //caso precise projetar
1842
                        $projInObj = ms_newprojectionobj("proj=latlong,a=6378137,b=6378137");
1843
                        $projOutObj = ms_newprojectionobj("proj=merc,a=6378137,b=6378137,lat_ts=0.0,lon_0=0.0,x_0=0.0,y_0=0,k=1.0,units=m");
1844

    
1845
                        $ext->project($projInObj, $projOutObj);
1846

    
1847
                        $pt = ms_newpointobj();
1848
                        $pt->setXY($px,$py);
1849

    
1850
                        $pt->project($projInObj, $projOutObj);
1851

    
1852
                        $px = $pt->x;
1853
                        $py = $pt->y;
1854
                }
1855
                $fx = $ext->maxx;
1856
                $fy = $ext->miny;
1857
                //calcula a dist&acirc;ncia entre os pontos em dd
1858
                $distx = $fx - $px;
1859
                $disty = $fy - $py;
1860
                if ($distx < 0){
1861
                        $distx = $distx * -1;
1862
                }
1863
                if ($disty < 0){
1864
                        $disty = $disty * -1;
1865
                }
1866
                if ($nptx == "")
1867
                {
1868
                        $nptx = round(($distx / $xdd),0);
1869
                }
1870
                if ($npty == "")
1871
                {
1872
                        $npty = round(($disty / $ydd),0);
1873
                }
1874
                // cria o shapefile
1875
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
1876
                $def = array();
1877
                $def[] = array("id","C","20");
1878
                if($this->dbaseExiste == false)
1879
                {
1880
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
1881
                }
1882
                else
1883
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
1884
                }
1885
                //acrescenta os pontos no novo shapefile
1886
                $dbname = $nomeshp.".dbf";
1887
                if($this->dbaseExiste == false)
1888
                        $db=xbase_open($dbname,2);
1889
                else
1890
                        $db=dbase_open($dbname,2);
1891
                $reg = array();
1892
                $valorcoluna = $px;
1893
                for ($coluna = 0; $coluna < $nptx; $coluna++){
1894
                        $x = $valorcoluna;
1895
                        $valorlinha = $py;
1896
                        for ($linha = 0; $linha < $npty; $linha++){
1897
                                $y = $valorlinha;
1898
                                $valorlinha = $valorlinha - $ydd;
1899
                                $poPoint1 = ms_newpointobj();
1900
                                $poPoint2 = ms_newpointobj();
1901
                                $poPoint3 = ms_newpointobj();
1902
                                $poPoint4 = ms_newpointobj();
1903
                                $poPoint1->setXY($x,$y);
1904
                                $poPoint2->setXY(($x + $xdd),$y);
1905
                                $poPoint3->setXY(($x + $xdd),($y - $ydd));
1906
                                $poPoint4->setXY($x,($y - $ydd));
1907

    
1908
                                if($proj == true){
1909
                                        $poPoint1->project($projOutObj,$projInObj);
1910
                                        $poPoint2->project($projOutObj,$projInObj);
1911
                                        $poPoint3->project($projOutObj,$projInObj);
1912
                                        $poPoint4->project($projOutObj,$projInObj);
1913
                                }
1914

    
1915
                                $linhas = ms_newLineObj();
1916
                                $linhas->add($poPoint1);
1917
                                $linhas->add($poPoint2);
1918
                                $linhas->add($poPoint3);
1919
                                $linhas->add($poPoint4);
1920
                                $linhas->add($poPoint1);
1921
                                $shapen = ms_newShapeObj(MS_SHP_POLYGON);
1922
                                $shapen->add($linhas);
1923
                                $novoshpf->addShape($shapen);
1924
                                $reg[] = $linha."-".$coluna;
1925
                                if($this->dbaseExiste == false)
1926
                                        xbase_add_record($db,$reg);
1927
                                else
1928
                                        dbase_add_record($db,$reg);
1929
                                $reg = array();
1930
                        }
1931
                        $valorcoluna = $valorcoluna + $xdd;
1932
                }
1933
                if($this->dbaseExiste == false)
1934
                        xbase_close($db);
1935
                else
1936
                        dbase_close($db);
1937
                //adiciona o novo tema no mapa
1938
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
1939
                $novolayer->set("data",$nomeshp.".shp");
1940
                $novolayer->setmetadata("DOWNLOAD","SIM");
1941
                $novolayer->setmetadata("TEMALOCAL","SIM");
1942
                $novolayer->set("opacity","50");
1943
                if (file_exists($this->qyfile))
1944
                {
1945
                        unlink ($this->qyfile);
1946
                }
1947
                return("ok");
1948
        }
1949
        /*
1950
         function: gradeDeHex
1951

1952
        Gera uma grade de pol&iacute;gonos hexagonais regulares definido em d&eacute;cimos de grau.
1953

1954
        Salva o mapa acrescentando um novo layer com a grade.
1955

1956
        parameters:
1957

1958
        $dd - Comprimento dos lados (em metros se $proj=true)
1959

1960
        $px - X do primeiro ponto (superior esquerdo)
1961

1962
        $py - Y do primeiro ponto.
1963

1964
        $locaplic - Endere&ccedil;o da aplica&ccedil;&atilde;o.
1965

1966
        $nptx - N&uacute;mero de pontos em X (opcional)
1967

1968
        $npty - N&uacute;mero de pontos em Y (opcional)
1969

1970
        $proj - A grade deve ser gerada em unidades metricas e projetada para geografica
1971
        */
1972
        function gradeDeHex($dd,$px,$py,$locaplic,$nptx,$npty,$proj=false){
1973
                set_time_limit(180);
1974
                //http://gmc.yoyogames.com/index.php?showtopic=336183
1975
                $hh = (sin(deg2rad(30)) * $dd);
1976
                $rr = (cos(deg2rad(30)) * $dd);
1977
                //para manipular dbf
1978
                if($this->dbaseExiste == false){
1979
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
1980
                }
1981
                $nomegrade = nomeRandomico();
1982
                $nomeshp = $this->diretorio."/".$nomegrade;
1983
                //pega a extens&atilde;o geogr&aacute;fica do mapa
1984
                $this->mapa->preparequery();
1985
                $r = $this->mapa->extent;
1986
                $ext = ms_newRectObj();
1987
                $ext->setextent($r->minx,$r->miny,$r->maxx,$r->maxy);
1988
                if($proj == true){
1989
                        //caso precise projetar
1990
                        $projInObj = ms_newprojectionobj("proj=latlong,a=6378137,b=6378137");
1991
                        $projOutObj = ms_newprojectionobj("proj=merc,a=6378137,b=6378137,lat_ts=0.0,lon_0=0.0,x_0=0.0,y_0=0,k=1.0,units=m");
1992

    
1993
                        $ext->project($projInObj, $projOutObj);
1994

    
1995
                        $pt = ms_newpointobj();
1996
                        $pt->setXY($px,$py);
1997

    
1998
                        $pt->project($projInObj, $projOutObj);
1999

    
2000
                        $px = $pt->x;
2001
                        $py = $pt->y;
2002
                }
2003

    
2004
                $fx = $ext->maxx;
2005
                $fy = $ext->miny;
2006

    
2007
                //calcula a dist&acirc;ncia entre os pontos em dd se nao tiver sido especificada ou for 0
2008
                $distx = $fx - $px;
2009
                $disty = $fy - $py;
2010
                if ($distx < 0){
2011
                        $distx = $distx * -1;
2012
                }
2013
                if ($disty < 0){
2014
                        $disty = $disty * -1;
2015
                }
2016
                if ($nptx == "")
2017
                {
2018
                        $nptx = round(($distx / $dd),0);
2019
                }
2020
                if ($npty == "")
2021
                {
2022
                        $npty = round(($disty / $dd),0);
2023
                }
2024
                // cria o shapefile
2025
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
2026
                $def = array();
2027
                $def[] = array("id","C","20");
2028
                if($this->dbaseExiste == false)
2029
                {
2030
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
2031
                }
2032
                else
2033
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
2034
                }
2035
                //acrescenta os pontos no novo shapefile
2036
                $dbname = $nomeshp.".dbf";
2037
                if($this->dbaseExiste == false)
2038
                        $db=xbase_open($dbname,2);
2039
                else
2040
                        $db=dbase_open($dbname,2);
2041
                $reg = array();
2042
                $w = $this->mapa->width;
2043
                $h = $this->mapa->height;
2044

    
2045
                $valorcoluna = $px;
2046
                $par = false;
2047
                for ($coluna = 0; $coluna < $nptx; $coluna++){
2048
                        $x = $valorcoluna;
2049
                        $valorlinha = $py;
2050

    
2051
                        if ($par == true){
2052
                                $valorlinha = $valorlinha - $rr;
2053
                                $par = false;
2054
                        }
2055
                        else{
2056
                                //$y = $y + $hh;
2057
                                $par = true;
2058
                        }
2059

    
2060
                        for ($linha = 0; $linha < $npty; $linha++){
2061
                                $y = $valorlinha;
2062
                                $valorlinha = $valorlinha - (2 * $rr);
2063

    
2064
                                $poPoint1 = ms_newpointobj();
2065
                                $poPoint2 = ms_newpointobj();
2066
                                $poPoint3 = ms_newpointobj();
2067
                                $poPoint4 = ms_newpointobj();
2068
                                $poPoint5 = ms_newpointobj();
2069
                                $poPoint6 = ms_newpointobj();
2070

    
2071
                                //Point 0: $x, $y
2072
                                //Point 1: x + s, y
2073
                                //Point 2: x + s + h, y + r
2074
                                //Point 3: x + s, y + r + r
2075
                                //Point 4: x, y + r + r
2076
                                //Point 5: x - h, y + r
2077
                                $poPoint1->setXY($x,$y);
2078
                                $poPoint2->setXY(($x + $dd),$y);
2079
                                $poPoint3->setXY($x + $dd + $hh,$y - $rr);
2080
                                $poPoint4->setXY($x + $dd, $y - $rr - $rr);
2081
                                $poPoint5->setXY($x,$y - $rr - $rr);
2082
                                $poPoint6->setXY($x - $hh,$y - $rr);
2083

    
2084
                                if($proj == true){
2085
                                        $poPoint1->project($projOutObj,$projInObj);
2086
                                        $poPoint2->project($projOutObj,$projInObj);
2087
                                        $poPoint3->project($projOutObj,$projInObj);
2088
                                        $poPoint4->project($projOutObj,$projInObj);
2089
                                        $poPoint5->project($projOutObj,$projInObj);
2090
                                        $poPoint6->project($projOutObj,$projInObj);
2091
                                }
2092

    
2093

    
2094
                                $linhas = ms_newLineObj();
2095
                                $linhas->add($poPoint1);
2096
                                $linhas->add($poPoint2);
2097
                                $linhas->add($poPoint3);
2098
                                $linhas->add($poPoint4);
2099
                                $linhas->add($poPoint5);
2100
                                $linhas->add($poPoint6);
2101
                                $linhas->add($poPoint1);
2102
                                $shapen = ms_newShapeObj(MS_SHP_POLYGON);
2103
                                $shapen->add($linhas);
2104
                                $novoshpf->addShape($shapen);
2105
                                $reg[] = $linha."-".$coluna;
2106
                                if($this->dbaseExiste == false)
2107
                                        xbase_add_record($db,$reg);
2108
                                else
2109
                                        dbase_add_record($db,$reg);
2110
                                $reg = array();
2111
                        }
2112
                        $valorcoluna = $valorcoluna + $dd + $hh;
2113
                }
2114
                if($this->dbaseExiste == false)
2115
                        xbase_close($db);
2116
                else
2117
                        dbase_close($db);
2118
                //adiciona o novo tema no mapa
2119

    
2120
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Grade (".$nomegrade.")"),$metaClasse="SIM");
2121
                $novolayer->set("data",$nomeshp.".shp");
2122
                $novolayer->setmetadata("DOWNLOAD","SIM");
2123
                $novolayer->setmetadata("TEMALOCAL","SIM");
2124
                $novolayer->set("opacity","50");
2125
                if (file_exists($this->qyfile))
2126
                {
2127
                        unlink ($this->qyfile);
2128
                }
2129
                return("ok");
2130
        }
2131
        /*
2132
         function: nptPol
2133

2134
        Conta o n&uacute;mero de pontos em pol&iacute;gono cruzando dois temas.
2135

2136
        Salva o mapa acrescentando um novo layer com o resultado.
2137

2138
        parameters:
2139
        $temaPt - Tema de pontos.
2140

2141
        $temaPo - Tema poligonal.
2142

2143
        $locaplic - Localiza&ccedil;&atilde;o do I3geo
2144
        */
2145
        function nptPol($temaPt,$temaPo,$locaplic,$somaritem="")
2146
        {
2147
                //error_reporting(0);
2148
                set_time_limit(180);
2149
                //para manipular dbf
2150
                if($this->dbaseExiste == false){
2151
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
2152
                }
2153
                $layerPt = $this->mapa->getlayerbyname($temaPt);
2154
                $layerPt->set("template","none.htm");
2155
                $layerPt->set("tolerance",0);
2156
                $layerPo = $this->mapa->getlayerbyname($temaPo);
2157
                $layerPo->set("template","none.htm");
2158
                //define o nome do novo shapefile que ser&aacute; criado
2159
                $nomefinal = nomeRandomico();
2160
                $nomeshp = $this->diretorio."/".$nomefinal;
2161
                $itenspo = pegaItens($layerPo);
2162
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
2163
                // cria o dbf
2164
                $def = array();
2165
                foreach ($itenspo as $ni){
2166
                        $def[] = array(substr($ni, 0, 10),"C","254");
2167
                }
2168
                $def[] = array("npontos","N","10","0");
2169
                $def[] = array("soma","N","10","0");
2170
                $def[] = array("media","N","10","0");
2171
                if($this->dbaseExiste == false){
2172
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
2173
                }
2174
                else{
2175
                        $db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
2176
                }
2177
                //acrescenta os pontos no novo shapefile
2178
                $dbname = $nomeshp.".dbf";
2179
                if($this->dbaseExiste == false){
2180
                        $db=xbase_open($dbname,2);
2181
                }
2182
                else{
2183
                        $db=dbase_open($dbname,2);
2184
                }
2185
                $shapes = retornaShapesMapext($layerPo,$this->mapa);
2186
                foreach($shapes as $shape){
2187
                        $novoreg = array();
2188
                        foreach($itenspo as $ipo){
2189
                                $novoreg[] = $shape->values[$ipo];
2190
                        }
2191
                        $layerPt->querybyshape($shape);
2192
                        if($somaritem != ""){
2193
                                $soma = 0;
2194
                                $layerPt->open();
2195
                                $res_count = $layerPt->getNumresults();
2196
                                for ($i = 0; $i < $res_count; ++$i){
2197
                                        if($this->v >= 6){
2198
                                                $s = $layerPt->getShape($layerPt->getResult($i));
2199
                                        }
2200
                                        else{
2201
                                                $result = $layerPt->getResult($i);
2202
                                                $shp_index  = $result->shapeindex;
2203
                                                $s = $layerPt->getfeature($shp_index,-1);
2204
                                        }
2205
                                        $soma += $s->values[$somaritem];
2206
                                }
2207
                                $fechou = $layerPt->close();
2208
                                $novoreg[] = $res_count;
2209
                                $novoreg[] = $soma;
2210
                                $novoreg[] = $soma / $res_count;
2211
                        }
2212
                        else{
2213
                                $novoreg[] = $layerPt->getNumresults();
2214
                                $novoreg[] = 0;
2215
                                $novoreg[] = 0;
2216
                        }
2217
                        $novoshpf->addShape($shape);
2218
                        if($this->dbaseExiste == false){
2219
                                xbase_add_record($db,$novoreg);
2220
                        }
2221
                        else{
2222
                                dbase_add_record($db,$novoreg);
2223
                        }
2224
                }
2225
                if($this->dbaseExiste == false){
2226
                        xbase_close($db);
2227
                }
2228
                else{
2229
                        dbase_close($db);
2230
                }
2231
                //adiciona o novo tema no mapa
2232
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,"N pontos",$metaClasse="SIM",false);
2233
                $novolayer->set("data",$nomeshp.".shp");
2234
                $novolayer->setmetadata("DOWNLOAD","SIM");
2235
                $novolayer->setmetadata("TEMALOCAL","SIM");
2236
                $novolayer->set("opacity","80");
2237
                if (file_exists($this->qyfile)){
2238
                        unlink ($this->qyfile);
2239
                }
2240
                return("ok");
2241
        }
2242
        /*
2243
         Function: agrupaElementos
2244

2245
        Agrupa elementos em um pol&iacute;gono.
2246

2247
        Salva o mapa acrescentando um novo layer com o resultado.
2248
        */
2249
        function agrupaElementos($item,$locaplic)
2250
        {
2251
                if(!$this->layer){
2252
                        return "erro";
2253
                }
2254
                set_time_limit(180);
2255
                //para manipular dbf
2256
                if(!isset($item)){
2257
                        $item="";
2258
                }
2259
                if($this->dbaseExiste == false){
2260
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
2261
                }
2262
                $shapes =retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
2263
                $indices = array();
2264
                foreach($shapes as $shape){
2265
                        if($item != "")
2266
                        {
2267
                                $valor = $shape->values[$item];
2268
                        }
2269
                        else
2270
                        {$valor = "nenhum";
2271
                        }
2272
                        if(!isset($indices[$valor])){
2273
                                $indices[$valor] = array($shape);
2274
                        }
2275
                        else
2276
                                $indices[$valor] = array_merge($indices[$valor],array($shape));
2277
                }
2278
                $dissolve=array();
2279
                foreach($indices as $shapes)
2280
                {
2281
                        foreach($shapes as $shape){
2282
                                if($item != "")
2283
                                        $valor = $shape->values[$item];
2284
                                else
2285
                                        $valor = "nenhum";
2286
                                if (!isset($dissolve[$valor]))
2287
                                {
2288
                                        $dissolve[$valor] = $shape;
2289
                                }
2290
                                else
2291
                                {
2292
                                        $tipo = $shape->type;
2293
                                        if($tipo==2)
2294
                                        {
2295
                                                for($l=0;$l<($shape->numlines);$l++)
2296
                                                {
2297
                                                        $shape1 = $dissolve[$valor];
2298
                                                        $linha = $shape->line($l);
2299
                                                        $shape1->add($linha);
2300
                                                }
2301
                                                $dissolve[$valor] = $shape1;
2302
                                        }
2303
                                        else
2304
                                        {
2305
                                                $dissolve[$valor] = $shape->union($dissolve[$valor]);
2306
                                        }
2307
                                }
2308
                        }
2309
                }
2310
                //
2311
                //cria o novo shapefile
2312
                //
2313
                $nomefinal = nomeRandomico();
2314
                $nomeshp = $this->diretorio."/".$nomefinal;
2315
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
2316
                // cria o dbf
2317
                $def = array();
2318
                if($item==""){
2319
                        $item="nenhum";
2320
                }
2321
                $def[] = array($item,"C","254");
2322
                if($this->dbaseExiste == false)
2323
                {
2324
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
2325
                }
2326
                else
2327
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
2328
                }
2329
                //acrescenta os pontos no novo shapefile
2330
                $dbname = $nomeshp.".dbf";
2331
                if($this->dbaseExiste == false)
2332
                        $db=xbase_open($dbname,2);
2333
                else
2334
                        $db=dbase_open($dbname,2);
2335
                $classes = array_keys($dissolve);
2336
                foreach ($classes as $classe)
2337
                {
2338
                        $novoshpf->addShape($dissolve[$classe]->convexhull());
2339
                        if($this->dbaseExiste == false)
2340
                                xbase_add_record($db,array($classe));
2341
                        else
2342
                                dbase_add_record($db,array($classe));
2343
                }
2344
                if($this->dbaseExiste == false)
2345
                        xbase_close($db);
2346
                else
2347
                        dbase_close($db);
2348
                //
2349
                //adiciona o novo layer no mapa
2350
                //
2351
                $n = pegaNome($this->layer);
2352
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Agrupamento de ".$n),$metaClasse="SIM",false);
2353
                $novolayer->set("data",$nomeshp.".shp");
2354
                $novolayer->setmetadata("DOWNLOAD","SIM");
2355
                $novolayer->setmetadata("TEMALOCAL","SIM");
2356
                return("ok");
2357
        }
2358

    
2359
        /*
2360
         function: dissolvePoligono
2361

2362
        Dissolve as bordas entre pol&iacute;gonos com o mesmo atributo.
2363

2364
        Salva o mapa acrescentando um novo layer com o resultado.
2365

2366
        $item - item utilizado para agregar os pol&iacute;gonos
2367

2368
        $locaplic - Localiza&ccedil;&atilde;o do I3geo
2369
        */
2370
        function dissolvePoligono($item,$locaplic)
2371
        {
2372
                if(!$this->layer){
2373
                        return "erro";
2374
                }
2375
                set_time_limit(180);
2376
                //para manipular dbf
2377
                if(!isset($item)){
2378
                        $item="";
2379
                }
2380
                if($this->dbaseExiste == false){
2381
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
2382
                }
2383
                $shapes = retornaShapesSelecionados($this->layer,$this->arquivo,$this->mapa);
2384
                $indices = array();
2385
                foreach($shapes as $shape){
2386
                        if($item != "")
2387
                        {
2388
                                $valor = $shape->values[$item];
2389
                        }
2390
                        else
2391
                        {$valor = "nenhum";
2392
                        }
2393
                        if(!isset($indices[$valor])){
2394
                                $indices[$valor] = array($shape);
2395
                        }
2396
                        else
2397
                                $indices[$valor] = array_merge($indices[$valor],array($shape));
2398
                }
2399
                $dissolve=array();
2400
                foreach($indices as $shapes)
2401
                {
2402
                        foreach($shapes as $shape){
2403
                                if($item != "")
2404
                                        $valor = $shape->values[$item];
2405
                                else
2406
                                        $valor = "nenhum";
2407
                                if (!isset($dissolve[$valor]))
2408
                                {
2409
                                        $dissolve[$valor] = $shape;
2410
                                }
2411
                                else
2412
                                {
2413
                                        if($shape->type != MS_SHAPE_POLYGON)
2414
                                        {
2415
                                                for($l=0;$l<($shape->numlines);$l++)
2416
                                                {
2417
                                                        $shape1 = $dissolve[$valor];
2418
                                                        $linha = $shape->line($l);
2419
                                                        $shape1->add($linha);
2420
                                                }
2421
                                                $dissolve[$valor] = $shape1;
2422
                                        }
2423
                                        else
2424
                                        {
2425
                                                $dissolve[$valor] = $shape->union($dissolve[$valor]);
2426
                                        }
2427
                                }
2428
                        }
2429
                }
2430
                //
2431
                //cria o novo shapefile
2432
                //
2433
                $nomefinal = nomeRandomico();
2434
                $nomeshp = $this->diretorio."/".$nomefinal;
2435
                $novoshpf = ms_newShapefileObj($nomeshp, MS_SHP_POLYGON);
2436
                // cria o dbf
2437
                $def = array();
2438
                if($item==""){
2439
                        $item="nenhum";
2440
                }
2441
                $def[] = array($item,"C","254");
2442
                if($this->dbaseExiste == false)
2443
                {
2444
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
2445
                }
2446
                else
2447
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
2448
                }
2449
                //acrescenta os pontos no novo shapefile
2450
                $dbname = $nomeshp.".dbf";
2451
                if($this->dbaseExiste == false)
2452
                        $db=xbase_open($dbname,2);
2453
                else
2454
                        $db=dbase_open($dbname,2);
2455
                $classes = array_keys($dissolve);
2456
                foreach ($classes as $classe)
2457
                {
2458
                        $novoshpf->addShape($dissolve[$classe]);
2459
                        if($this->dbaseExiste == false)
2460
                                xbase_add_record($db,array($classe));
2461
                        else
2462
                                dbase_add_record($db,array($classe));
2463
                }
2464
                if($this->dbaseExiste == false)
2465
                        xbase_close($db);
2466
                else
2467
                        dbase_close($db);
2468
                //
2469
                //adiciona o novo layer no mapa
2470
                //
2471
                $n = pegaNome($this->layer);
2472
                $novolayer = criaLayer($this->mapa,MS_LAYER_POLYGON,MS_DEFAULT,("Dissolve de ".$n),$metaClasse="SIM");
2473
                $novolayer->set("data",$nomeshp.".shp");
2474
                $novolayer->setmetadata("DOWNLOAD","SIM");
2475
                $novolayer->setmetadata("TEMALOCAL","SIM");
2476
                if (file_exists($this->qyfile))
2477
                {
2478
                        unlink ($this->qyfile);
2479
                }
2480

    
2481
                return("ok");
2482
        }
2483
        /*
2484
         Function aplicaFuncaoListaWKT
2485

2486
        Aplica uma fun&ccedil;&atilde;o do Mapserver � uma lista de geometrias no formato WKT
2487

2488
        Parametros:
2489

2490
        $geometrias {Array} - lista de WKT
2491

2492
        $operacao {String} - opera&ccedil;&atilde;o suportada pelo Mapserver, por exemplo, union, intersects, etc. converteSHP ir&aacute; converter as geometrias em um tema e adicion&aacute;-lo ao mapa
2493

2494
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver. Utilizado apenas se $operacao = "converteSHP"
2495

2496
        $imgdir - Diret&oacute;rio das imagens do mapa atual. Utilizado apenas se $operacao = "converteSHP"
2497

2498
        Return:
2499

2500
        {string wkt}
2501
        */
2502
        function aplicaFuncaoListaWKT($geometrias,$operacao,$dir_tmp="",$imgdir=""){
2503
                if($operacao === "converteSHP"){
2504
                        $nomelayer = $this->incmapageometrias($dir_tmp,$imgdir,$geometrias,$tipoLista="arraywkt");
2505
                        return $nomelayer;
2506
                }
2507
                $geos = array();
2508
                foreach ($geometrias as $geo){
2509
                        $geos[] = ms_shapeObjFromWkt($geo);
2510
                }
2511
                $n = count($geos);
2512
                if ($n == 1)
2513
                {
2514
                        eval("\$nShape = \$geos[0]->".$operacao."();");
2515
                        return $nShape->toWkt();
2516
                }
2517
                if ($n == 2)
2518
                {
2519
                        eval("\$nShape = \$geos[0]->".$operacao."(\$geos[1]);");
2520
                        return $nShape->toWkt();
2521
                }
2522
                if ($n > 2)
2523
                {
2524
                        $geoc = $geos[0];
2525
                        for($i=1;$i<$n;++$i)
2526
                        {
2527
                                eval("\$geoc = \$geoc->".$operacao."(\$geos[\$i]);");
2528
                        }
2529
                        return $geoc->toWkt();
2530
                }
2531
        }
2532
        /*
2533
         function: funcoesGeometrias
2534

2535
        Fun&ccedil;&otilde;es de an&aacute;lise de geometrias da ferramenta Geometrias.
2536

2537
        parameters:
2538
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver
2539

2540
        $imgdir - Diret&oacute;rio das imagens do mapa atual
2541

2542
        $lista - String com a lista de nomes dos arquivos serializados que cont&eacute;m as geometrias
2543

2544
        $operacao - Tipo de an&aacute;lise.
2545
        */
2546
        function funcoesGeometrias($dir_tmp,$imgdir,$lista,$operacao)
2547
        {
2548
                $lista = explode(",",$lista);
2549
                $dir = $dir_tmp."/".$imgdir."/";
2550
                $geometrias = array();
2551
                $valoresoriginais = array();
2552
                $calculo = array();
2553
                foreach ($lista as $l)
2554
                {
2555
                        $geos = $this->unserializeGeo($dir.$l);
2556
                        foreach ($geos["dados"] as $geo)
2557
                        {
2558
                                $geometrias[] = $geo["wkt"];
2559
                                $valoresoriginais = array_merge($valoresoriginais,$geo["valores"]);
2560
                        }
2561
                }
2562
                $calculo[]["gwkt"] = $this->aplicaFuncaoListaWKT($geometrias,$operacao);
2563
                $nomegeo = "";
2564
                if (count($calculo)>0)
2565
                {
2566
                        $final["layer"] = $operacao." ".(implode(" ",$lista));
2567
                        $final["dados"][] = array("id"=>"0","wkt"=>($calculo[0]["gwkt"]),"valores"=>$valoresoriginais,"imagem"=>"");
2568
                        $nomegeo = $dir.(nomerandomico(10))."keo";
2569
                        $this->serializeGeo($nomegeo,$final);
2570
                        $ext = $this->mapa->extent;
2571
                        $minx = $ext->minx;
2572
                        $miny = $ext->miny;
2573
                        $maxx = $ext->maxx;
2574
                        $maxy = $ext->maxy;
2575
                        $h = $this->mapa->height;
2576
                        $w = $this->mapa->width;
2577
                        $nomelayer = $this->incmapageometrias($dir_tmp,$imgdir,basename($nomegeo));
2578
                        if ($nomelayer != "erro")
2579
                        {
2580

    
2581
                                $nlayer = $this->mapa->getlayerbyname($nomelayer);
2582
                                $bounds = $nlayer->getExtent();
2583
                                $this->mapa->setsize(30,30);
2584
                                $sb = $this->mapa->scalebar;
2585
                                $statusoriginal = $sb->status;
2586
                                $sb->set("status",MS_OFF);
2587
                                $ext->setextent(($bounds->minx),($bounds->miny),($bounds->maxx),($bounds->maxy));
2588
                                $imagem = gravaImagemMapa($this->mapa);
2589
                                $this->mapa->setsize($w,$h);
2590
                                $ext->setextent($minx,$miny,$maxx,$maxy);
2591
                                $nlayer->set("status",MS_DELETE);
2592
                                $sb->set("status",$statusoriginal);
2593
                                $this->salva();
2594
                                $final = array();
2595
                                $final["layer"] = $operacao." ".(implode(" ",$lista));
2596
                                $final["dados"][] = array("id"=>"0","wkt"=>($calculo[0]["gwkt"]),"valores"=>$valoresoriginais,"imagem"=>($imagem["url"]));
2597
                                $this->serializeGeo($nomegeo,$final);
2598
                        }
2599
                }
2600
                return($nomegeo);
2601
        }
2602

    
2603
        /*
2604
         function: calculaGeometrias
2605

2606
        Fun&ccedil;&otilde;es de c&aacute;lculo de geometrias da ferramenta Geometrias.
2607

2608
        parameters:
2609

2610
        $dir_tmp - Diret&oacute;rio tempor&aacute;rio do mapserver
2611

2612
        $imgdir - Diret&oacute;rio das imagens do mapa atual
2613

2614
        $lista - Arquivos com as geometrias
2615

2616
        $operacao - Tipo de an&aacute;lise.
2617
        */
2618
        function calculaGeometrias($dir_tmp,$imgdir,$lista,$operacao)
2619
        {
2620
                //error_reporting(0);
2621
                $lista = explode(",",$lista);
2622
                $dir = $dir_tmp."/".$imgdir."/";
2623
                foreach ($lista as $l)
2624
                {
2625
                        $geos = $this->unserializeGeo($dir.$l);
2626
                        //
2627
                        //verifica a vers&atilde;o do mapserver
2628
                        //se for anterior a 5, utiliza a conex&atilde;o com o postgis para fazer o processamento dos daods
2629
                        //
2630
                        $v = versao();
2631
                        if (($v["principal"] < 5))
2632
                        {
2633
                                return ("erro. E necessario uma vers&atilde;o maior que 5.0 do Mapserver.");
2634
                        }
2635
                        foreach ($geos["dados"] as &$geo)
2636
                        {
2637
                                $g = $geo["wkt"];
2638
                                switch ($operacao)
2639
                                {
2640
                                        case "perimetro":
2641
                                                $shape = ms_shapeObjFromWkt($g);
2642
                                                $rect = $shape->bounds;
2643
                                                $projInObj = ms_newprojectionobj("proj=longlat,ellps=WGS84,datum=WGS84,no_defs");
2644
                                                $projOutObj = ms_newprojectionobj("proj=poly,ellps=GRS67,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=5000000,y_0=10000000,units=m");
2645
                                                $shape->project($projInObj, $projOutObj);
2646
                                                $s = $shape->towkt();
2647
                                                $shape = ms_shapeObjFromWkt($s);
2648
                                                $area = $shape->getLength();
2649
                                                $geo["valores"][] = array("item"=>"P_perim_metros","valor"=>$area);
2650
                                                break;
2651
                                        case "area":
2652
                                                $shape = ms_shapeObjFromWkt($g);
2653
                                                $rect = $shape->bounds;
2654
                                                $projInObj = ms_newprojectionobj("proj=longlat,ellps=WGS84,datum=WGS84,no_defs");
2655
                                                $projOutObj = ms_newprojectionobj("proj=laea,lat_0=".$rect->miny.",lon_0=".$rect->minx.",x_0=500000,y_0=10000000,ellps=GRS67,units=m,no_defs");
2656
                                                $shape->project($projInObj, $projOutObj);
2657
                                                $s = $shape->towkt();
2658
                                                $shape = ms_shapeObjFromWkt($s);
2659
                                                $area = $shape->getArea();
2660
                                                $geo["valores"][] = array("item"=>"P_area_metros","valor"=>$area);
2661
                                                break;
2662
                                        case "comprimento":
2663
                                                break;
2664
                                }
2665
                        }
2666
                        $this->serializeGeo($dir.$l,$geos);
2667
                }
2668
                return("ok");
2669
        }
2670
        /*
2671
         Function: incmapageometrias
2672

2673
        Insere geometrias como tema no mapa.
2674

2675
        parameters:
2676

2677
        $dir_tmp - Diretorio tempor&aacute;rio do mapserver
2678

2679
        $imgdir - Diretorio das imagens do mapa atual
2680

2681
        $lista - Nomes, sem o caminho, dos arquivos com as geometrias, separados por v&iacute;rgula.
2682

2683
        $tipoLista - tipo de valores que s&atilde;o passados em $lista stringArquivos|arraywkt. O default &eacute; stringArquivos
2684
        */
2685
        function incmapageometrias($dir_tmp,$imgdir,$lista,$tipoLista="stringArquivos")
2686
        {
2687
                $dir = $dir_tmp."/".$imgdir."/";
2688
                $tituloTema = " geometria";
2689
                if($tipoLista == "stringArquivos"){
2690
                        $lista = explode(",",$lista);
2691
                        $shapes = array();
2692
                        $valoresoriginais = array();
2693
                        foreach ($lista as $l)
2694
                        {
2695
                                $geos = $this->unserializeGeo($dir.$l);
2696
                                //pega todas as geometrias
2697
                                foreach ($geos["dados"] as $geo)
2698
                                {
2699
                                        //echo $geo["wkt"]."<br>";
2700
                                        $shapes[] = ms_shapeObjFromWkt(str_replace("'","",$geo["wkt"]));
2701
                                        foreach ($geo["valores"] as $v)
2702
                                        {
2703
                                                $valorestemp[] = $v["item"]."=".$v["valor"];
2704
                                        }
2705
                                        $valoresoriginais[] = implode(" ",$valorestemp);
2706
                                }
2707
                        }
2708
                }
2709
                if($tipoLista == "arraywkt"){
2710
                        $shapes = array();
2711
                        $valoresoriginais = array();
2712
                        foreach ($lista as $l){
2713
                                $shapes[] = ms_shapeObjFromWkt($l);
2714
                        }
2715
                }
2716
                if($tipoLista == "marcadores"){
2717
                        $shapes = array();
2718
                        $valoresoriginais = array();
2719
                        foreach ($lista as $l){
2720
                                $valoresoriginais[] = $l["nome"];
2721
                                $p = explode(" ",$l["ext"]);
2722
                                $l = "POLYGON ((".$p[0]." ".$p[1].",".$p[0]." ".$p[3].",".$p[2]." ".$p[3].",".$p[2]." ".$p[1].",".$p[0]." ".$p[1]."))";
2723
                                $shapes[] = ms_shapeObjFromWkt($l);
2724
                        }
2725
                        $tituloTema = " marcadores";
2726
                }
2727
                //verifica o tipo
2728
                if (count($shapes) == 0){
2729
                        return("erro.");
2730
                }
2731
                $tiposhape = $shapes[0]->type;
2732
                $tiposhapefile = MS_SHP_POLYGON;
2733
                if ($tiposhape == 0){
2734
                        $tiposhapefile = MS_SHP_MULTIPOINT;
2735
                }
2736
                if ($tiposhape == 1){
2737
                        $tiposhapefile = MS_SHP_ARC;
2738
                }
2739
                //cria o shapefile
2740
                if($this->dbaseExiste == false){
2741
                        include_once dirname(__FILE__)."/../pacotes/phpxbase/api_conversion.php";
2742
                }
2743
                $diretorio = dirname($this->arquivo);
2744
                $novonomelayer = nomeRandomico();
2745
                $nomeshp = $diretorio."/".$novonomelayer;
2746
                $l = criaLayer($this->mapa,$tiposhape,MS_DEFAULT,"Ins","SIM");
2747
                $novoshpf = ms_newShapefileObj($nomeshp, $tiposhapefile);
2748
                $def[] = array("ID","C","250");
2749
                if($this->dbaseExiste == false)
2750
                {
2751
                        $db = xbase_create($nomeshp.".dbf", $def);xbase_close($db);
2752
                }
2753
                else
2754
                {$db = dbase_create($nomeshp.".dbf", $def);dbase_close($db);
2755
                }
2756
                //acrescenta os pontos no novo shapefile
2757
                $dbname = $nomeshp.".dbf";
2758
                if($this->dbaseExiste == false)
2759
                        $db=xbase_open($dbname,2);
2760
                else
2761
                        $db=dbase_open($dbname,2);
2762
                $conta = 0;
2763
                foreach ($shapes as $s)
2764
                {
2765
                        $reg = array();
2766
                        $reg[] = $valoresoriginais[$conta];
2767
                        if($this->dbaseExiste == false)
2768
                                xbase_add_record($db,$reg);
2769
                        else
2770
                                dbase_add_record($db,$reg);
2771
                        $novoshpf->addshape($s);
2772
                        $conta = $conta + 1;
2773
                }
2774
                if($this->dbaseExiste == false)
2775
                        xbase_close($db);
2776
                else
2777
                        dbase_close($db);
2778
                $l->set("opacity",80);
2779
                $l->setmetadata("tema",$novonomelayer.$tituloTema);
2780
                $l->setmetadata("TEMALOCAL","SIM");
2781
                $l->setmetadata("DOWNLOAD","sim");
2782
                $l->set("data",$nomeshp);
2783
                $l->set("name",$novonomelayer);
2784
                $classe = $l->getclass(0);
2785
                $estilo = $classe->getstyle(0);
2786
                if ($tiposhape == 0)
2787
                {
2788
                        $estilo->set("symbolname","ponto");
2789
                        $estilo->set("size",6);
2790
                }
2791
                $cor = $estilo->color;
2792
                $cor->setrgb(255,210,0);
2793
                $cor = $estilo->outlinecolor;
2794
                $cor->setrgb(255,0,0);
2795
                $this->salva();
2796
                return($novonomelayer);
2797
        }
2798
        /*
2799
         function: gravaCoordenadasPt
2800

2801
        L&ecirc; as coordenadas de um tema pontual e grava em arquivos.
2802

2803
        Essa fun&ccedil;&atilde;o &eacute; utilizada nas op&ccedil;&otilde;es que utilizam o R para c&aacute;lculos e necessitam ler as coordenadas dos pontos.
2804

2805
        Parametros:
2806

2807
        tema - nome do tema com os pontos
2808

2809
        limitepontos - FALSE para considerar a extens&atilde;o geogr&aacute;fica do mapa atual e TRUE para considerar como limite as ocorr&ecirc;ncias pontuais do tema
2810

2811
        extendelimite - percentual utilizado para extender o limite da &aacute;rea resultante
2812

2813
        item - item com os valors de peso (opcional)
2814

2815
        return:
2816

2817
        array com as dimens&otilde;es em x e y e nome dos arquivos com x e y gerados.
2818
        */
2819
        function gravaCoordenadasPt($tema,$limitepontos="TRUE",$extendelimite,$item=""){
2820
                $prjMapa = $this->mapa->getProjection();
2821
                $layerPt = $this->mapa->getlayerbyname($tema);
2822
                $prjTema = $layerPt->getProjection();
2823
                $layerPt->set("tolerance",0);
2824
                $layerPt->set("template","none.htm");
2825
                $nomefinal = nomeRandomico();
2826
                $nomearq = $this->diretorio."/".$nomefinal;
2827

    
2828
                $itemspt = pegaItens($layerPt);
2829
                $shapes = retornaShapesSelecionados($layerPt,$this->arquivo,$this->mapa);
2830
                if(count($shapes) == 0){
2831
                        $shapes = retornaShapesMapext($layerPt,$this->mapa);
2832
                }
2833
                $pontos = array();
2834
                $pontosz = array();
2835
                if (($prjTema != "") && ($prjMapa != $prjTema)){
2836
                        $projInObj = ms_newprojectionobj($prjTema);
2837
                        $projOutObj = ms_newprojectionobj($prjMapa);
2838
                }
2839
                foreach($shapes as $shape){
2840
                        $pt = $shape->getCentroid();
2841
                        if (($prjTema != "") && ($prjMapa != $prjTema)){
2842
                                $pt->project($projInObj, $projOutObj);
2843
                        }
2844
                        $pontos[] = $pt->x."  ".$pt->y."\n";
2845
                        $pontosx[] = $pt->x;
2846
                        $pontosy[] = $pt->y;
2847
                        if($item != ""){
2848
                                $pontosz[] = trim($shape->values[$item]);
2849
                        }
2850
                }
2851
                $layerPt->close();
2852
                //grava o arquivo com os pontos em x
2853
                $f = fopen($nomearq."x","w");
2854
                foreach ($pontosx as $pt){
2855
                        fwrite($f,$pt."\n");
2856
                }
2857
                fclose($f);
2858
                //grava o arquivo com os pontos em y
2859
                $f = fopen($nomearq."y","w");
2860
                foreach ($pontosy as $pt){
2861
                        fwrite($f,$pt."\n");
2862
                }
2863
                fclose($f);
2864
                //grava o arquivo com os pontos em z
2865
                $f = fopen($nomearq."z","w");
2866
                foreach ($pontosz as $pt){
2867
                        fwrite($f,$pt."\n");
2868
                }
2869
                fclose($f);
2870
                if ($limitepontos == "TRUE"){
2871
                        $xi = (min($pontosx));
2872
                        $xf = (max($pontosx));
2873
                        $yi = (min($pontosy));
2874
                        $yf = (max($pontosy));
2875
                }
2876
                else{
2877
                        $ext = $this->mapa->extent;
2878
                        $xi = $ext->minx;
2879
                        $xf = $ext->maxx;
2880
                        $yi = $ext->miny;
2881
                        $yf = $ext->maxy;
2882
                }
2883
                if($extendelimite > 0){
2884
                        $dx = $xf - $xi;
2885
                        $dy = $yf - $yi;
2886
                        $maisx = ($dx * $extendelimite) / 100;
2887
                        $maisy = ($dy * $extendelimite) / 100;
2888
                        $xi = $xi - $maisx;
2889
                        $xf = $xf + $maisx;
2890
                        $yi = $yi - $maisy;
2891
                        $yf = $yf + $maisy;
2892
                }
2893
                $dimx = "c(".$xi.",".$xf.")";
2894
                $dimy = "c(".$yi.",".$yf.")";
2895
                return array("dimx"=>$dimx,"dimy"=>$dimy,"arqx"=>($nomearq."x"),"arqy"=>($nomearq."y"),"arqz"=>($nomearq."z"),"prefixoarquivo"=>$nomearq);
2896
        }
2897
        /*
2898
         function unserializeGeo
2899

2900
        Deserializa um arquivo de geometrias.
2901

2902
        Parametros:
2903
        $arquivo - arquivo que ser&aacute; processado
2904
        */
2905
        public function unserializeGeo($arq)
2906
        {
2907
                $handle = fopen ($arq, "r");
2908
                $conteudo = fread ($handle, filesize ($arq));
2909
                fclose ($handle);
2910
                return(unserialize($conteudo));
2911
        }
2912
        /*
2913
         function serializeGeo
2914

2915
        Deserializa um arquivo de geometrias.
2916

2917
        Parametros:
2918
        $arquivo - arquivo que ser&aacute; processado
2919

2920
        $geos - array com os dados
2921
        */
2922
        public function serializeGeo($arq,$geos)
2923
        {
2924
                if (file_exists($arq))
2925
                {
2926
                        unlink($arq);
2927
                }
2928
                $fp = fopen($arq,"w");
2929
                $r = serialize($geos);
2930
                fwrite($fp,$r);
2931
                fclose($fp);
2932
        }
2933
        /*
2934
         Function: classesRasterI
2935

2936
        Gera par&acirc;metros para classifica&ccedil;&atilde;o de imagens.
2937

2938
        Gera a express&atilde;o e as cores para uso em classes com intervalos iguais para representa&ccedil;&atilde;o de imagens raster.
2939

2940
        Parametros:
2941

2942
        $minvalor {numeric} - Menor valor existente na s&eacute;rie
2943

2944
        $maxvalor {numeric} - Maior valor
2945

2946
        $nclasses {numeric} - N&uacute;mero de classes
2947

2948
        $cores {array} - Cores. Array de array de cores cores[0] = array(r,g,b)
2949

2950
        Retorno:
2951

2952
        (start code)
2953
        array(
2954
                        array(
2955
                                        "nomeclasse"=>,
2956
                                        "expressao"=>,
2957
                                        "cores"=>
2958
                        )
2959
        )
2960
        (end)
2961
        */
2962
        //error_reporting(0);
2963
        function classesRasterI($minvalor,$maxvalor,$nclasses,$cores)
2964
        {
2965
                $resultado = array();
2966
                $intervalo = intval(250 / $nclasses);
2967
                $trans = 250 / ($maxvalor - $minvalor);
2968
                $intervalo = (($maxvalor*$trans) - ($minvalor*$trans)) / $nclasses;
2969
                $conta = 0;
2970
                for ($i=0; $i < $nclasses; ++$i)
2971
                {
2972
                        $expressao = "([pixel]>=".$conta." and [pixel]<".($conta+$intervalo).")";
2973
                        $nomeclasse = ">= ".($conta/$trans)." e < que ".(($conta + $intervalo)/$trans);
2974
                        $resultado[] = array("nomeclasse"=>$nomeclasse,"expressao"=>$expressao,"cores"=>$cores[$i]);
2975
                        $conta = $conta + $intervalo;
2976
                }
2977
                return $resultado;
2978
        }
2979
        function executaR($rcode,$dir_tmp,$R_path,$gfile_name="")
2980
        {
2981
                $R_options = "--slave --no-save";
2982
                $r_name = nomeRandomico(20);
2983
                $r_input = $dir_tmp."/".$r_name.".R";
2984
                $r_output = $dir_tmp."/".$r_name.".Rout";
2985
                gravaDados($rcode,$r_input);
2986
                $command = $R_path." $R_options < $r_input > $r_output";
2987
                $result = "";
2988
                $error = "";
2989
                $exec_result = exec($command,$result,$error);
2990
                //corta a imagem final
2991
                //include_once("classe_imagem.php");
2992
                //$m = new Imagem($dir_tmp."/".$gfile_name.".png");
2993
                //$i = $m->cortaBorda();
2994
                //imagepng($i,$dir_tmp."/".$gfile_name.".png");
2995
                return($r_input);
2996
        }
2997
        /*
2998
         Function: criaImagemR
2999

3000
        Cria uma imagem png a partir de dados armazenados em disco.
3001

3002
        Utilizado para gerar uma imagem com base nos resultados de comandos R.
3003

3004
        O nome da imagem criada ser&aacute; o mesmo nome de $nomearq, por&eacute;m com extens&atilde;o .png
3005

3006
        Parametros:
3007

3008
        $nomearq {string} - Nome do arquivo no servidor que ser&aacute; utilizado para gerar a imagem.
3009

3010
        Retorno:
3011

3012
        {array($minpixel,$maxpixel)} - tamanho da imagem gerada.
3013
        */
3014
        function criaImagemR($nomearq)
3015
        {
3016
                if (!file_exists($nomearq."img"))
3017
                {
3018
                        return "erro";
3019
                }
3020
                //pega os parametros
3021
                $abre = fopen($nomearq."h", "r");
3022
                while (!feof($abre))
3023
                {
3024
                        $buffer = fgets($abre);
3025
                        $pararray[] = $buffer;
3026
                }
3027
                fclose($abre);
3028

    
3029
                $xsize = $pararray[0];
3030
                $ysize = $pararray[1];
3031
                $xdim = $pararray[2];
3032
                $ydim = $pararray[3];
3033
                $wh = explode(" ",$pararray[4]);
3034
                // pega os valores dos pixels
3035
                $abre = fopen($nomearq."img", "r");
3036
                $buffer = fgets($abre);
3037
                fclose($abre);
3038
                $pixelimg = explode(" ",$buffer);
3039
                $minpixel = min($pixelimg);
3040
                $maxpixel = max($pixelimg);
3041
                $trans = 250 / ($maxpixel - $minpixel);
3042
                $img = imagecreatetruecolor($wh[0],$wh[1]);
3043
                $celula = 0;
3044
                for ($x = 0; $x < $wh[0]; ++$x)
3045
                {
3046
                        for ($y = ($wh[1] - 1); $y >= 0; $y--)
3047
                        {
3048
                                $cor = imagecolorresolve($img,$pixelimg[$celula] * $trans, $pixelimg[$celula] * $trans, $pixelimg[$celula] * $trans);
3049
                                imagesetpixel($img, $x, $y,$cor);
3050
                                $celula = $celula + 1;
3051
                        }
3052
                }
3053

    
3054
                Imagepng($img,$nomearq.".png");
3055
                ImageDestroy($nomearq.".png");
3056
                $dadosw[] = trim($xsize);
3057
                $dadosw[] = 0;
3058
                $dadosw[] = 0;
3059
                $dadosw[] = trim($ysize * -1);
3060
                $temp = explode(" ",$xdim);
3061
                $dadosw[] = trim($temp[0]);
3062
                $temp = explode(" ",$ydim);
3063
                $dadosw[] = trim($temp[1]);
3064
                $fp = fopen($nomearq.".wld","w");
3065
                foreach ($dadosw as $dado)
3066
                {
3067
                        fwrite($fp,$dado."\n");
3068
                }
3069
                fclose($fp);
3070
                $retorno = array($minpixel,$maxpixel);
3071
                return $retorno;
3072
        }
3073
}
3074
?>