wmswfs.php 29.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
<?php
/*
Title: wmswfs.php

Funções de uso geral para realizar a leitura e o processamento de Web Services nos padrões OGC.
Atualmente, processa apenas serviços no padrão WMS.

Licenca:

GPL2


i3Geo Interface Integrada de Ferramentas de Geoprocessamento para Internet

Direitos Autorais Reservados (c) 2006 Ministério do Meio Ambiente Brasil
Desenvolvedor: Edmar Moretti edmar.moretti@mma.gov.br

Este programa é software livre; você pode redistribuí-lo
e/ou modificá-lo sob os termos da Licença Pública Geral
GNU conforme publicada pela Free Software Foundation;

Este programa é distribuído na expectativa de que seja útil,
porém, SEM NENHUMA GARANTIA; nem mesmo a garantia implícita
de COMERCIABILIDADE OU ADEQUAÇÃO A UMA FINALIDADE ESPECÍFICA.
Consulte a Licença Pública Geral do GNU para mais detalhes.
Você deve ter recebido uma cópia da Licença Pública Geral do
GNU junto com este programa; se não, escreva para a
Free Software Foundation, Inc., no endereço
59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.

Arquivo:

i3geo/classesphp/wmswfs.php
*/
/*
Function: gravaCacheWMS

Lê o getcapabilities de um WMS e salva em disco se o mesmo não tiver sido salvo antes

O arquivo é gravado no diretório temporário

Parametros:

$servico {string} - endereço do WMS

Global:

$dir_tmp {string} - (opcional) endereço do diretório temporário onde o cache será armazenado. Se não for definido, tenta obter das variáveis de configuração existentes em i3geo/ms_configura.php

Return:

{string} - Nome do arquivo criado. Retorna a palavra "erro" se tiver ocorrido um erro.
*/
function gravaCacheWMS($servico)
{
	global $dir_tmp;
	if($dir_tmp == "")
	{include("../ms_configura.php");}
	error_reporting(0);
	try{
		$teste = explode("=",$servico);
		if ( count($teste) > 1 )
		{$servico = $servico."&";}
		else
		{
			$teste = explode("?",$servico);
			if ( count($teste) == 1 ){$servico = $servico."?";}
		}
		$wms_service_request = $servico . "REQUEST=GetCapabilities&SERVICE=WMS";
		$teste = explode("version",strtolower($wms_service_request));
		if(count($teste) == 1)
		{$wms_service_request .= "&VERSION=1.1.1";}
		$nome = $dir_tmp."/wms".md5($servico).".xml";
		if(!file_exists($nome))
		{
			$wms_capabilities = file($wms_service_request);
			if( !$wms_capabilities )
			{return "erro";}
			else
			{
				$fp = fopen($nome, 'w');
				fwrite($fp, implode("",$wms_capabilities));
				fclose($fp);	
			}
		}
		return $nome;
	}
	catch(Exception $e){return "erro";}
}
/*
Function: existeTemaWFS

Verifica se existe um tema em um servico WFS.

Globais:

$wfs {string} - endereço do serviço

$tema {string} - tema (layer) que será verificado

Retorno:

{string} - sim|nao
*/
function existeTemaWFS()
{
	global $wfs,$tema;
	$capabilities = implode("",$wfs);
	$dom = new DomDocument();
	$dom->loadXML($capabilities);
	$xpath = new DOMXPath($dom);
	$query = '//WFS_Capabilities/FeatureTypeList/FeatureType';
	$entries = $xpath->query($query);
	foreach($entries as $e)
	{
		$e->getElementsByTagName("Name");
		$n = $e->nodeValue;
		if ($n == $tema)
		{return "sim";}
	}
	return "nao";
}
/*
Function: existeWFS

Verifica se existe um servico WFS invocando o getcapabilities.

Global:

$servico {string} - endereço do serviço

Retorno:

{string} - nao|true
*/
function existeWFS()
{
	global $servico;
	$teste = explode("=",$servico);
	if ( count($teste) > 1 ){$servico = $servico."&";}
	$wms_service_request = $servico . "REQUEST=GetCapabilities&SERVICE=WFS";
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	if( !($wfs_capabilities = file($wms_service_request)) ) {
		# Cannot download the capabilities file.
		return "nao";
	}
	else
	{return $wfs_capabilities;}
}
/*
Function: getcapabilities

Chama a função getcapabilities e retorna o resultado.

Global:

$servico {string} - Endereço do web service.

Retorno:

{string}
*/
function getcapabilities()
{
	global $servico;
	$teste = explode("=",$servico);
	if ( count($teste) > 1 ){$servico = $servico."&";}
	$wms_service_request = $servico . "REQUEST=GetCapabilities&SERVICE=WMS&version=1.1.0";
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	if( !($wms_capabilities = file($wms_service_request)) ) {
		# Cannot download the capabilities file.
		$cp->set_data("Erro de acesso");
		return;
	}
	$wms_capabilities = implode("",$wms_capabilities);
	return(xml2html($wms_capabilities));
}
/*
function: getcapabilities2

Chama a função getcapabilities e retorna o resultado pré-formatado (WMS).

Global:

$servico {string} - Endereço do web service.

Retorno:

{string}
*/
function getcapabilities2()
{
	global $servico;
	$teste = explode("=",$servico);
	if ( count($teste) > 1 ){$servico = $servico."&";}
	$wms_service_request = $servico . "REQUEST=GetCapabilities&SERVICE=WMS";
	$teste = explode("version",strtolower($wms_service_request));
	if(count($teste) == 1)
	{$wms_service_request .= "&VERSION=1.1.1";}
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	if( !($wms_capabilities = file($wms_service_request)) ) {
		# Cannot download the capabilities file.
		$cp->set_data("Erro de acesso");
		return;
	}
	$wms_capabilities = implode("",$wms_capabilities);
	$dom = new DomDocument();
	$dom->loadXML($wms_capabilities);
	$xpath = new DOMXPath($dom);
	$retorno = "";
	$query = '//WMT_MS_Capabilities/Service/Name';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$rn = $xpath->registerNamespace("tag", "http://www.opengis.net/wms");
		$entries = $xpath->query('/tag:WMS_Capabilities/tag:Service/tag:Name');
	}	
	
	$temp = "";
	foreach ($entries as $entry){$temp .= $entry->nodeValue;}
	$retorno .= "<b>Nome: </b>".$temp;

	$query = '//WMT_MS_Capabilities/Service/Title';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$entries = $xpath->query('/tag:WMS_Capabilities/tag:Service/tag:Title');
	}	
	$temp = "";
	foreach ($entries as $entry){$temp .= $entry->nodeValue;}
	$retorno .= "<br><br><b>T&iacute;tulo: </b>".$temp;

	$query = '//WMT_MS_Capabilities/Service/Abstract';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$entries = $xpath->query('/tag:WMS_Capabilities/tag:Service/tag:Abstract');
	}	
	$temp = "";
	foreach ($entries as $entry){$temp .= $entry->nodeValue;}
	$retorno .= "<br><br><b>Resumo: </b>".$temp;

	$query = '//WMT_MS_Capabilities/Service/KeywordList';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$entries = $xpath->query('/tag:WMS_Capabilities/tag:Service/tag:KeywordList');
	}	
	$temp = "";
	foreach ($entries as $entry){$temp .= $entry->nodeValue.".";}
	$retorno .= "<br><br><b>Palavras-chave: </b>".$temp;

	$query = '//WMT_MS_Capabilities/Service/ContactInformation';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$entries = $xpath->query('/tag:WMS_Capabilities/tag:Service/tag:ContactInformation');
	}	
	$temp = "";
	foreach ($entries as $entry){$temp .= $entry->nodeValue.".";}
	$retorno .= "<br><br><b>Contato: </b>".$temp;

	return($retorno);
}
/*
getcapabilities3

Chama a função getcapabilities e retorna o resultado formatado (WFS).

Global:

$servico {string} - Endereço do web service.


*/
function getcapabilities3()
{
	global $servico;
	$teste = explode("=",$servico);
	if ( count($teste) > 1 ){$servico = $servico."&";}
	$wms_service_request = $servico . "request=getcapabilities&service=wfs&version=1.0.0";
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	if( !($wms_capabilities = file($wms_service_request)) ) {
		# Cannot download the capabilities file.
		$cp->set_data("Erro de acesso");
		return;
	}
	$wms_capabilities = implode("",$wms_capabilities);
	$dom = new DomDocument();
	$dom->loadXML($wms_capabilities);
	$retorno = "";
	$services = $dom->getElementsByTagName("Service");
	foreach ($services as $service)
	{
		$vs = $service->getElementsByTagName("Name");
		$temp = "";
		foreach ($vs as $v)
		{$temp .= $v->nodeValue;}
		$retorno .= "<b>Nome: </b>".$temp;
		$vs = $service->getElementsByTagName("Title");
		$temp = "";
		foreach ($vs as $v)
		{$temp .= $v->nodeValue;}
		$retorno .= "<br><br><b>T&iacute;tulo: </b>".$temp;
	}
	return($retorno);
}
/*
Function: temaswms

Lista os temas de um web service WMS.

Globais:

$servico {string} - Endereço do web service.

$id_ws {string} - (opcional) id do serviço registrado no sistema de administração do i3geo. Se definido, é feito o registro de tentativa de acesso ao serviço no sistema de administração

Retorno:

{html} - htaml formatado para permitir a escolha de uma camada
*/
function temaswms()
{
	global $servico,$id_ws;

	$wms_service_request = gravaCacheWMS($servico);
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	//$wms_service_request = "c://temp//teste.xml";
	include_once("../admin/php/admin.php");
	include_once("../admin/php/webservices.php");
	
	//error_reporting(E_ALL);
	if($wms_service_request == "erro") {
		# Cannot download the capabilities file.
		//registra a tentativa de acesso
		if(isset($id_ws))
		{
			adicionaAcesso($id_ws,false);
		}
		$cp->set_data("Erro de acesso");
		return;
	}
	elseif(isset($id_ws))
	{
		if($id_ws != "")
		adicionaAcesso($id_ws,true);
	}
	$handle = fopen ($wms_service_request, "r");
	$wms_capabilities = fread($handle, filesize($wms_service_request));
	fclose ($handle); 

	$dom = new DomDocument();
	$dom->loadXML($wms_capabilities);

	//var_dump($dom);exit;
	//$layers = wms_layers($dom);
	$xpath = new DOMXPath($dom);
	//verifica sld
	$suporta = "nao";
	$query = '//WMT_MS_Capabilities/Capability/UserDefinedSymbolization';
	$entries = $xpath->query($query);
	if($entries->length == 0){
		$suporta = "sim";	
	}
	else{
		foreach($entries as $e)
		{$n = $e->getAttribute("SupportSLD");}
		if ($n == 1){$suporta = "sim";}
	}
	$xpath = new DOMXPath($dom);
	//var_dump($xpath);exit;
	$q = '//WMT_MS_Capabilities/Capability';
	$query = $q.'/Layer';
	$layers = $xpath->query($query);
	if($layers == FALSE || $layers->length == 0){
		$teste = $xpath->registerNamespace("tag", "http://www.opengis.net/wms");
		$q = '/tag:WMS_Capabilities/tag:Capability';
		$query = $q.'/tag:Layer';
		$layers = $xpath->query($query);
	}
	//var_dump($layers);exit;
	$retorna = array();
	foreach ($layers as $layer)
	{
		$layers1 = $xpath->query('/Layer',$layer);
		if($layers1->length == 0) //v 1.3.0
		{$layers1 = $layers;}
		else{
			$r = pegaTag($layer);
			$retorna = imprimeTag($r,$retorna);		
		}
		foreach ($layers1 as $layer1)
		{
			$layers2 = $xpath->query('Layer',$layer1);
			$r1 = pegaTag($layer1);
			$camada1 = $r1["nome"];
			$titulocamada1 = $r1["titulo"];
			$retorna = imprimeTag($r1,$retorna);
			if($r1["estilos"])
			{$retorna = imprimeEstilos($r1["estilos"],$suporta,$retorna,$camada1,$titulocamada1);}
			else
			{
				if($layers2->length == 0)
				$retorna[] = "<input style='cursor:pointer' type=radio NAME='checks' onClick='seltema(\"tema\",\"" . $camada1 . "\",\"\",\"default\",\"".$camada1." ".$titulocamada1."\",\"".$suporta."\")' value='" . $camada1 . "'/> default<i>".$titulocamada1."</i></span><br>";
			}
			foreach ($layers2 as $layer2)
			{
				$layers3 = $xpath->query('Layer',$layer2);
				$r2 = pegaTag($layer2);
				$camada2 = $r2["nome"];
				$titulocamada2 = $r2["titulo"];
				$retorna = imprimeTag($r2,$retorna);
				if($r2["estilos"])
				{$retorna = imprimeEstilos($r2["estilos"],$suporta,$retorna,$camada2,$titulocamada2);}
				else
				{
					if($layers3->length == 0)
					$retorna[] = "<input style='cursor:pointer' type=radio NAME='checks' onClick='seltema(\"tema\",\"" . $camada2 . "\",\"\",\"default\",\"".$camada2." ".$titulocamada2."\",\"".$suporta."\")' value='" . $camada2 . "'/> default <i>".$titulocamada2."</i></span><br>";
				}
				foreach ($layers3 as $layer3)
				{
					$r3 = pegaTag($layer3);
					$camada3 = $r3["nome"];
					$titulocamada3 = $r3["titulo"];
					$retorna = imprimeTag($r3,$retorna);
					if($r3["estilos"])
					{$retorna = imprimeEstilos($r3["estilos"],$suporta,$retorna,$camada3,$titulocamada3);}
					else
					{
						$retorna[] = "<input style='cursor:pointer' type=radio NAME='checks' onClick='seltema(\"tema\",\"" . $camada3 . "\",\"\",\"default\",\"".$camada3." ".$titulocamada3."\",\"".$suporta."\")' value='" . $camada3 . "'/> default <i>".$titulocamada3."</i></span><br>";
					}
				}
			}
			if(count($layers2) == 1){$retorna[] = "<hr>";}
		}
	}	
	$retorna[] = "<br>Proj.:<input size=30 id=proj type=text class=digitar value='".implode(",",wms_srs($dom))."'/><br>";
	$retorna[] = "<br>Formatos imagem:<input size=30 id=formatos type=text class=digitar value='".implode(",",wms_formats($dom))."'/><br><br>";
	$retorna[] = "<br>Formatos info:<input size=30 id=formatosinfo type=text class=digitar value='".implode(",",wms_formatsinfo($dom))."'/><br><br>";
	$retorna[] = "<br>Versao:<input size=30 id=versao type=text class=digitar value='".(wms_version($dom))."'/><br><br>";
	$retorna[] = "<br>Suporta SLD:<input size=30 id=suportasld type=text class=digitar value='".$suporta."'/><br><br><br>";
	return(implode($retorna));
}
/*
Function: listaLayersWMS

Lista os temas de um web service WMS e retorna o resultado como um array.

Globais:

$servico {string} - Endereço do web service.

$nivel - nível do layer na hierarquia existente no getcapabilities

$nomelayer - nome do layer que contém os próximos layers

Retorno:

{array}
*/
function listaLayersWMS()
{
	global $servico,$nivel,$id_ws,$nomelayer;
	if(!isset($nomelayer)){$nomelayer = "undefined";}
	$wms_service_request = gravaCacheWMS($servico);
	include_once("../admin/php/admin.php");
	include_once("../admin/php/webservices.php");
	error_reporting(0);
	
	if($nivel < 2){
		if($wms_service_request == "erro") {
			//registra a tentativa de acesso
			if(isset($id_ws))
			{
				adicionaAcesso($id_ws,false);
			}
			$cp->set_data("Erro de acesso");
			return;
		}
		elseif(isset($id_ws))
		{
			adicionaAcesso($id_ws,true);
		}	
	}
	$handle = fopen ($wms_service_request, "r");
	$wms_capabilities = fread ($handle, filesize ($wms_service_request));
	fclose ($handle); 
	$dom = new DomDocument();
	$dom->loadXML($wms_capabilities);
	$xpath = new DOMXPath($dom);
	$q = '//WMT_MS_Capabilities/Capability';
	$res = array();
	
	if($nomelayer != "undefined")
	{
		for($i=0; $i < $nivel-1 ; ++$i)
		$q .= "/Layer";
		$layersanteriores = $xpath->query($q);
		foreach ($layersanteriores as $layeranterior)
		{
			$r1 = pegaTag($layeranterior);
			if($r1["nome"] == $nomelayer || $r1["titulo"] == $nomelayer)
			{
				$layers = $xpath->query('Layer',$layeranterior);
				foreach ($layers as $layer)
				{
					$r = pegaTag($layer);
					if(!$r["nome"]){$r["nome"] = $r["titulo"];}
					$res[] = array("nome"=>$r["nome"],"titulo"=>$r["titulo"],"estilos"=>$r["estilos"],"srs"=>wms_srs($dom),"formats"=>wms_formats($dom),"version"=>wms_version($dom),"formatsinfo"=>wms_formatsinfo($dom));
				}
				if($layers->length == 0)
				{
					$res[] = array("nome"=>$r1["nome"],"titulo"=>$r1["titulo"],"estilos"=>(array(array("nome"=>"default","titulo"=>"default"))),"srs"=>wms_srs($dom),"formats"=>wms_formats($dom),"version"=>wms_version($dom),"formatsinfo"=>wms_formatsinfo($dom));
				}
			}
		}
	}
	else
	{
		//
		//pega os layers no primeiro nível
		//
		$q .= "/Layer";
		$layers = $xpath->query($q);	
		$res = array();
		foreach ($layers as $layer)
		{
			$r = pegaTag($layer);
			//echo $r["nome"]."\n";
			if(!$r["nome"]){$r["nome"] = $r["titulo"];}
			if(array_search("Style",$r["tags"]) || array_search("Layer",$r["tags"]))
			{$res[] = array("nome"=>$r["nome"],"titulo"=>$r["titulo"],"estilos"=>$r["estilos"],"srs"=>wms_srs($dom),"formats"=>wms_formats($dom),"version"=>wms_version($dom),"formatsinfo"=>wms_formatsinfo($dom));}
		}
	}
	return($res);
}

function imprimeEstilos($es,$suporta,$retorna,$tval,$tituloalternativo)
{
	foreach($es as $e)
	{
		//$tval = $e["titulo"];
		$nomeestilo = $e["nome"];
		$nomecamada = $e["titulo"];
		//if($nomecamada == "default" || $nomecamada == "")
		//{$nomecamada = $tituloalternativo;}
		$tituloestilo = $e["titulo"];
		$retorna[] = "<input style='cursor:pointer' type=radio NAME='checks' onClick='seltema(\"estilo\",\"" . $tval . "\",\"\",\"" . $nomeestilo . "\",\"".$tituloalternativo." ".$nomecamada." ".$tituloestilo."\",\"".$suporta."\")' value='" . $nomeestilo . "'/><span style=color:blue >" . $nomeestilo." <i>".$tituloestilo."</i></span><br>";	
	}
	return $retorna;
}
function imprimeTag($r,$retorna)
{
	if(!$r["nome"])
	{$retorna[] =  "<br><span style='color:brown;font-size:14pt' ><b>".$r["titulo"]."</b></span><br>";}
	else
	{
		$retorna[] =  "<hr>";
		$retorna[] =  "<br><span style='color:brown;font-size:12pt' ><b>".$r["nome"]."</b></span><br>";
		$retorna[] =  "<br><span style='color:black;font-size:12pt' ><b>".$r["titulo"]."</b></span><br>";
		$retorna[] =  "<br><span style='color:gray;font-size:9pt' >".$r["resumo"]."</span><br>";
	}
	return $retorna;
}
function pegaTag($layer)
{
	error_reporting(0);
	$noslayer = $layer->childNodes;
	$resultado = array();
	for ($i = 0; $i < $noslayer->length; ++$i)
	{
		$tnome = $noslayer->item($i)->tagName;
		$tvalor = $noslayer->item($i)->nodeValue;
		if($tnome)
		{
			if ($tnome == "Title")
			{$resultado["titulo"] = $tvalor;}
			if ($tnome == "Name")
			{$resultado["nome"] = $tvalor;}
			if ($tnome == "Abstract")
			{$resultado["resumo"] = $tvalor;}
			if ($tnome == "Style")
			{
				$ss = $noslayer->item($i)->childNodes;
				$ssl = $ss->length;
				for ($s = 0; $s < $ssl; $s++)
				{
					$snome = $ss->item($s)->tagName;
					$svalor = $ss->item($s)->nodeValue;
					if($snome)
					{
						if ($snome == "Title")
						{$t=$svalor;}
						if ($snome == "Name")
						{$n=$svalor;}
					}
				}
				$resultado["estilos"][] = array("nome"=>$n,"titulo"=>$t);
			}
			$resultado["tags"][] = $tnome;
		}
	}
	return $resultado;
}


/*
temaswfs

Lista os temas de um web service WFS.

parameters:
$servico - Endereço do web service.

$cp - Objeto CPAINT.
*/
function temaswfs()
{
	global $servico,$cp;
	$teste = explode("=",$servico);
	if ( count($teste) > 1 ){$servico = $servico."&";}
	$wms_service_request = $servico . "REQUEST=GetCapabilities&SERVICE=WFS";
	# -------------------------------------------------------------
	# Test that the capabilites file has successfully downloaded.
	#
	if( !($wms_capabilities = file($wms_service_request)) ) {
		# Cannot download the capabilities file.
		$cp->set_data("Erro de acesso");
		return;
	}
	$wms_capabilities = implode("",$wms_capabilities);
	$dom = new DomDocument();
	$dom->loadXML($wms_capabilities);
	$services = $dom->getElementsByTagName("Service");
	foreach ($services as $service)
	{
		$vs = $service->getElementsByTagName("Name");
		$serv = "";
		foreach ($vs as $v)
		{$serv .= $v->nodeValue;}
	}	
	$layers = $dom->getElementsByTagName("FeatureType");
	foreach ($layers as $layer)
	{
		$vs = $layer->getElementsByTagName("Title");
		$temp1 = "";
		foreach ($vs as $v)
		{$temp1 .= $v->nodeValue;}
		
		$vs = $layer->getElementsByTagName("Abstract");
		$temp2 = "";
		foreach ($vs as $v)
		{$temp2 .= $v->nodeValue;}
		
		$vs = $layer->getElementsByTagName("SRS");
		$temp3 = array();
		foreach ($vs as $v)
		{$temp3[] = $v->nodeValue;}
		$temp3 = implode("#",$temp3);

		$vs = $layer->getElementsByTagName("Name");
		$temp = "";
		foreach ($vs as $v)
		{$temp .= $v->nodeValue;}
		$temp = "<input style='cursor:pointer' type=radio NAME='checks' onClick='seltema(\"" . $temp . "\",\"" .$temp1. "\",\"" . $temp3 . "\",\"" . $serv ."\")' /><span style=color:red >" . $temp . "</span><br>";		
		$retorno .= "<br>".$temp.$temp1."<br>".$temp2."<hr>";
	}
	$cp->set_data($retorno);
}
/*
Function: xml2html

Converte caracteres XML em HTML.

Parametro:

$str {string} - Xml que será convertido

Retorno:

{string}
*/
function xml2html ( $str )
{
	$str = ereg_replace("&","&amp;",$str);
	$str = ereg_replace("<","&lt;",$str);
	$str = ereg_replace(">","&gt;<BR>",$str);
	return $str;
}
/*
wms_descricao

Retorna a descrição de um serviço (nó).
*/
function wms_descricao ( $dom,$xp )
{
	$xpath = new DOMXPath($dom);
	$query = $xp;
	$entries = $xpath->query($query);
	$n = "";
	foreach ($entries as $entry)
	{
		$n = $entry->nodeValue;
	}
	return $n;
}
/*
wms_descricaov

Retorna a descrição de um serviço (atributo).
*/
function wms_descricaov ( $dom,$xp,$attrib )
{
	$xpath = new DOMXPath($dom);
	$query = $xp;
	$entries = $xpath->query($query);
	$n = "";
	foreach ($entries as $entry)
	{
		$n = $entry->getAttribute($attrib);
	}
	return $n;
}
/*
wms_descricaon

Retorna a descrição de um serviço (filho de um nó).
*/
function wms_descricaon ( $dom,$xp,$n ) {
	$ctx = xpath_new_context($dom);
	$xpnode = xpath_eval($ctx,$xp);
	$dtnode = $xpnode->nodeset[$n]->first_child();
	return $dtnode->content;
}
/*
wms_title

Retorna o título de um WMS.
*/
function wms_title ( $dom ) {
	#
	# Read the WMS service title and return it as text.
	#
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Service/Title';
	$entries = $xpath->query($query);
	foreach ($entries as $entry){$nomeserv = $entry->nodeValue;}
	return $nomeserv;
}
/*
wms_onlineresource

Retorna o recurso on-line de um WMS.
*/
function wms_onlineresource ( $dom ) {
	#
	# Read the WMS online resource URL and return it as text.
	#
	$xp = "/WMT_MS_Capabilities/Service/OnlineResource";
	$ctx = xpath_new_context($dom);
	$xpnode = xpath_eval($ctx,$xp);
	return $xpnode->nodeset[0]->get_attribute("href");
}
/*
wms_formats

Retorna os formatos de imagem de um WMS.
*/
function wms_formats ( $dom )
{
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Capability/Request/GetMap/Format';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$teste = $xpath->registerNamespace("tag", "http://www.opengis.net/wms");
		$q = '/tag:WMS_Capabilities/tag:Capability/tag:Request/tag:GetMap/tag:Format';
		$entries = $xpath->query($q);
	}	
	$arr = array();
	foreach ($entries as $entry)
	{
		$arr[] = $entry->nodeValue;
	}
	return $arr;
}
/*
wms_formatsinfo

Retorna os formatos existentes de retorno da opção getfeatureinfo.
*/
function wms_formatsinfo ( $dom )
{
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Capability/Request/GetFeatureInfo/Format';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$teste = $xpath->registerNamespace("tag", "http://www.opengis.net/wms");
		$q = '/tag:WMS_Capabilities/tag:Capability/tag:Request/tag:GetCapabilities/tag:Format';
		$entries = $xpath->query($q);
	}	
	$arr = array();
	foreach ($entries as $entry)
	{
		$arr[] = $entry->nodeValue;
	}
	return $arr;
}
/*
wms_estilos

Retorna os estilos de um WMS.
*/
function wms_estilos ( $dom ) {
	#
	# Read the WMS image formats and return them as an array.
	#
	//$xp = "/Style";
	//$ctx = xpath_new_context($dom);
	//$xpnode = xpath_eval($ctx,$xp);
	//return $xpnode->nodeset;
	$return = $dom->getElementsByTagName("Style");

}
/*
wms_exceptions

Retorna as exceptions de um WMS.
*/
function wms_exceptions ( $dom ) {
	#
	# Read the WMS exception formats and return them as an array.
	#
	$xp = "/WMT_MS_Capabilities/Capability/Exception/Format";
	$ctx = xpath_new_context($dom);
	$xpnode = xpath_eval($ctx,$xp);
	$arr = array();
	for( $i = 0; $i < sizeof($xpnode->nodeset); ++$i ) {
		$dtnode = $xpnode->nodeset[0]->first_child();
		array_push($arr,$dtnode->content);
	}
	return $arr;
}
/*
wms_version

Retorna a versao.
*/
function wms_version ( $dom )
{
	$n = $dom->getElementsByTagName('WMT_MS_Capabilities');
	$params = $dom->getElementsByTagName('*');

	foreach ($params as $param) {
		$v = $param -> getAttribute('version');
		break;
	}
	return $v;
}
/*
wms_layers

Retorna os layers de um WMS.
*/
function wms_layers ( $dom ) {
	#
	# Read the WMS first level layers and return an
	# array of nodes.
	#
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Capability/Layer/Layer/Layer';
	$entries = $xpath->query($query);
	if ($entries->length == 0)
	{
		$query = '//WMT_MS_Capabilities/Capability/Layer';
		$entries = $xpath->query($query);		
	}
	else
	{
		$query = '//WMT_MS_Capabilities/Capability/Layer/Layer';
		$entries = $xpath->query($query);		
	}
	return $entries;
}
/*
wms_xpnode2content

Read the content child node of an element tag node WMS.
*/
function wms_xpnode2content( $xp_node ) {
	#
	# Read the content child node of an element tag
	# node.
	#
	$content = "";
	if( $xp_node->nodeset[0] ) {
		$node = $xp_node->nodeset[0]->first_child();
		$content = $node->content;
	}
	return $content;
}
/*
wms_srs

Retorna os SRSs WMS.
*/
function wms_srs( $dom )
{
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Capability/Layer/SRS';
	$entries = $xpath->query($query);
	if($entries == FALSE || $entries->length == 0){
		$teste = $xpath->registerNamespace("tag", "http://www.opengis.net/wms");
		$q = '/tag:WMS_Capabilities/tag:Capability/tag:Layer/tag:CRS';
		$entries = $xpath->query($q);
	}

	$srs = "";
	//utiliza apenas os epsg do Brasil
	$single = array();
	foreach ($entries as $entry)
	{
		$arr[] = $entry->nodeValue;
		if ($entry->nodeValue == "CRS:84")
		{$single[] = "CRS:84";}
		if ($entry->nodeValue == "EPSG:4326")
		{$single[] = "EPSG:4326";}
		if ($entry->nodeValue == "EPSG:4291")
		{$single[] = "EPSG:4291";}
	}
	if (count($single) > 0)
	{$arr = $single;}
	return $arr;
}
/*
wms_bbox

Retorna o BBOX de um WMS.
*/
function wms_bbox( $dom )
{
	$xpath = new DOMXPath($dom);
	$query = '//WMT_MS_Capabilities/Capability/Layer/LatLonBoundingBox';
	$entries = $xpath->query($query);
	foreach ($entries as $entry){$bbox = $entry->nodeValue;}
	if ($bbox == '-1,-1,-1,-1')
	{return '-180,-90,180,90';}
	else
	{return wms_bbox2txt($bbox);}
}
/*
wms_bbox2txt

Convert a BoundingBox node into a text string de um wms.
*/
function wms_bbox2txt( $node ) {
	#
	# Convert a BoundingBox node into a text string.
	#
	if( $node ) {
		$txt .= 1 * $node->get_attribute("minx");
		$txt .= ",";
		$txt .= 1 * $node->get_attribute("miny");
		$txt .= ",";
		$txt .= 1 * $node->get_attribute("maxx");
		$txt .= ",";
		$txt .= 1 * $node->get_attribute("maxy");
	}
	else {
		$txt = "-180,-90,180,90";
	}
	return $txt;
}
/*
wms_layer2html

Convert a Layer node into an HTML representation wms.
*/
function wms_layer2html( $node, $tipo , $layer ) {
	#
	# Convert a Layer node into an HTML representation.
	#
	$ctx = xpath_new_context($node);
	$xp_title  = xpath_eval($ctx,"/Title");
	$xp_name   = xpath_eval($ctx,"/Name");
	if (wms_xpnode2content($xp_name) == ""){$xp_name = xpath_eval($ctx,"/name");}
	$xp_srs    = xpath_eval($ctx,"/SRS");
	$xp_llbbox = xpath_eval($ctx,"/LatLonBoundingBox");
	$xp_bbox   = xpath_eval($ctx,"/BoundingBox");
	$txt_title = wms_xpnode2content($xp_title);
	$txt_name  = wms_xpnode2content($xp_name);
	$txt_srs   = strtoupper(wms_xpnode2content($xp_srs));
	$node_llbbox = $xp_llbbox->nodeset[0];
	$node_bbox   = $xp_bbox->nodeset[0];
	$queryable = 0;
	if ( $node->get_attribute("queryable") ) {
		$queryable = 1;
	}
	$opaque = 0;
	if ( $node->get_attribute("opaque") ) {
		$opaque = 1;
	}
	//legenda
	$xp_legenda   = xpath_eval($ctx,"/LegendURL/OnlineResource");
	$nodelegenda = $xp_legenda->nodeset[0];
	if($nodelegenda)
	{  $legenda = $nodelegenda->get_attribute("href");}

	$html  = "<INPUT TYPE='radio' NAME='checks' VALUE='$txt_name' onClick='toggle(event,\"$tipo\",\"$layer\",\"$legenda\",\"$txt_title\")'>";
	$html .= "&nbsp;&nbsp;";
	$html .= $txt_title . "\n";
	$html .= wms_hidden("bbox_$txt_name", wms_bbox2txt($node_bbox));
	$html .= wms_hidden("llbox_$txt_name", wms_bbox2txt($node_llbbox));
	$html .= wms_hidden("srs_$txt_name", $txt_srs);
	$html .= wms_hidden("query_$txt_name", $queryable );
	$html .= wms_hidden("opaque_$txt_name", $opaque );
	$html .= "<BR>";
	return $html;
}
/*
wms_layer3html

Convert a Layer node into an HTML representation sem radio.
*/
function wms_layer3html( $node ) {
	#
	# Convert a Layer node into an HTML representation sem radio.
	#
	$ctx = xpath_new_context($node);
	$xp_title  = xpath_eval($ctx,"/Title");
	$xp_abs  = xpath_eval($ctx,"/Abstract");
	$txt_title = wms_xpnode2content($xp_title);
	$txt_abs = wms_xpnode2content($xp_abs);
	$html .= "<b>".$txt_title . "</b><i style='color:gray'>" . "-" . $txt_abs . "</i>\n";
	$html .= "<BR>";
	return $html;
}
/*
wms_layer4html

Convert a Layer into an HTML WMS.
*/
function wms_layer4html( $layer ) {
	$estilos = wms_estilos($layer);
	if (count($estilos) > 0)
	{
		$ctxl = xpath_new_context($layer);
		$xp_namel   = xpath_eval($ctxl,"/Name");
		if (wms_xpnode2content($xp_namel) == ""){$xp_namel = xpath_eval($ctxl,"/name");}
		$txt_namel  = wms_xpnode2content($xp_namel);
		$html .= wms_layer3html($layer);
		foreach ($estilos as $estilo)
		{
			$html .= wms_layer2html($estilo,"estilo",$txt_namel);
		}
	}
	else
	{
		$html .= wms_layer2html($layer,"tema","");
	}
	return $html;
}

?>