Commit a42cf08bc5b8bcb7b8dfae3f6aa8099095bd978a

Authored by Edmar Moretti
1 parent 4ae358d7

Correção na geração de KMZ para visualização de vetores no Google Earth

pacotes/kmlmapserver/classes/layerserver.class.php
1 <?php 1 <?php
2 /** 2 /**
3 -* Mapserver wrapper to KML/KMZ data  
4 -*  
5 -* Returns KML or KMZ representation of common OGC requests  
6 -*  
7 -* <pre>  
8 -* accepted parameters (case insensitive):  
9 -* - request = string - request type (OGC WFS like), can be kml (default), kmz, icon  
10 -* - map = string - path to mapfile  
11 -* - typename = string - (can be a csv list) - layer name(s)  
12 -* - filter = string - filter encoding  
13 -* - bbox = string - (csv) - bounding box csv  
14 -* - encoding = string - data and mapfile encoding, defaults to ISO-8859-1  
15 -*  
16 -*  
17 -* </pre>  
18 -*  
19 -* @author Alessandro Pasotti  
20 -* @copyright 2007 ItOpen.it - All rights reserved  
21 -* @package KMLMAPSERVER  
22 -  
23 -This file is part of KMLMAPSERVER.  
24 -  
25 - KMLMAPSERVER is free software; you can redistribute it and/or modify  
26 - it under the terms of the GNU Lesser General Public License as published by  
27 - the Free Software Foundation; either version 3 of the License, or  
28 - (at your option) any later version.  
29 -  
30 - KMLMAPSERVER is distributed in the hope that it will be useful,  
31 - but WITHOUT ANY WARRANTY; without even the implied warranty of  
32 - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
33 - GNU Lesser General Public License for more details.  
34 -  
35 - You should have received a copy of the GNU Lesser General Public License  
36 - along with KMLMAPSERVER; if not, write to the Free Software  
37 - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA  
38 -  
39 -*/  
40 -  
41 -  
42 -/** Fix a GE bug for filled polygons */ 3 + * Mapserver wrapper to KML/KMZ data
  4 + *
  5 + * Returns KML or KMZ representation of common OGC requests
  6 + *
  7 + * <pre>
  8 + * accepted parameters (case insensitive):
  9 + * - request = string - request type (OGC WFS like), can be kml (default), kmz, icon
  10 + * - map = string - path to mapfile
  11 + * - typename = string - (can be a csv list) - layer name(s)
  12 + * - filter = string - filter encoding
  13 + * - bbox = string - (csv) - bounding box csv
  14 + * - encoding = string - data and mapfile encoding, defaults to ISO-8859-1
  15 + *
  16 + *
  17 + * </pre>
  18 + *
  19 + * @author Alessandro Pasotti
  20 + * @copyright 2007 ItOpen.it - All rights reserved
  21 + * @package KMLMAPSERVER
  22 +
  23 + This file is part of KMLMAPSERVER.
  24 +
  25 + KMLMAPSERVER is free software; you can redistribute it and/or modify
  26 + it under the terms of the GNU Lesser General Public License as published by
  27 + the Free Software Foundation; either version 3 of the License, or
  28 + (at your option) any later version.
  29 +
  30 + KMLMAPSERVER is distributed in the hope that it will be useful,
  31 + but WITHOUT ANY WARRANTY; without even the implied warranty of
  32 + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33 + GNU Lesser General Public License for more details.
  34 +
  35 + You should have received a copy of the GNU Lesser General Public License
  36 + along with KMLMAPSERVER; if not, write to the Free Software
  37 + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  38 +
  39 + */
  40 +
  41 +/**
  42 + * Fix a GE bug for filled polygons
  43 + */
43 define('TREAT_POLY_AS_LINE', false); 44 define('TREAT_POLY_AS_LINE', false);
44 45
45 -/** Enable cache */ 46 +/**
  47 + * Enable cache
  48 + */
46 define('ENABLE_CACHE', true); 49 define('ENABLE_CACHE', true);
47 -if(function_exists("dl")){  
48 - if (!function_exists('ms_GetVersion'))  
49 - {dl( 'php_mapscript.'.PHP_SHLIB_SUFFIX );}  
50 - if (!extension_loaded('php_mbstring'))  
51 - {dl( 'php_mbstring.' . PHP_SHLIB_SUFFIX );} 50 +if (function_exists("dl")) {
  51 + if (! function_exists('ms_GetVersion')) {
  52 + dl('php_mapscript.' . PHP_SHLIB_SUFFIX);
  53 + }
  54 + if (! extension_loaded('php_mbstring')) {
  55 + dl('php_mbstring.' . PHP_SHLIB_SUFFIX);
  56 + }
52 } 57 }
53 -if (!function_exists('ms_GetVersion'))  
54 -{echo "Nao foi possivel carregar php_mapscript";}  
55 -/**  
56 -* Main server class  
57 -*/  
58 -class LayerServer {  
59 -  
60 - /** map file path */  
61 - var $map;  
62 -  
63 - /** request */  
64 - var $request;  
65 -  
66 - /** map instance */  
67 - var $map_object;  
68 -  
69 - /** layer name(s) passed on the request */  
70 - var $typename;  
71 -  
72 - /** array of requested layer objects (hash with layer name as key) */  
73 - var $layers;  
74 -  
75 - /** filters */  
76 - var $filter;  
77 -  
78 - /** bounding box */  
79 - var $bbox;  
80 -  
81 - /** error messages */  
82 - var $errors;  
83 -  
84 - /** send zipped data */  
85 - var $_zipped = false;  
86 -  
87 - /** internal XML buffer */  
88 - var $_xml;  
89 -  
90 - /** input projection */  
91 - var $in_proj;  
92 -  
93 - /** output projection */  
94 - var $out_proj;  
95 -  
96 - /** debug flag */  
97 - var $_debug = false;  
98 -  
99 - /** end point */  
100 - var $endpoint;  
101 -  
102 - /** custom style counter */  
103 - var $style_counter = 0;  
104 -  
105 - /**  
106 - * Mapfile and data encoding encoding  
107 - * XMl output must be UTF-8, attributes and METADATA based strings  
108 - * must be converted to UTF-8, encoding defaults to ISO-8859-1, if  
109 - * your encoding is different, you can set it through CGI style parameters  
110 - */  
111 - var $encoding;  
112 - /**  
113 - * send networklink  
114 - * wether folder should contain networklinks instead of real geometries  
115 - * it is automatically set when all layers are requested  
116 - */  
117 - var $_networklink;  
118 - /**  
119 - * Initialize  
120 - *  
121 - */  
122 - function LayerServer(){  
123 - $this->errors = array();  
124 - // Load request parameters  
125 - $this->get_request();  
126 - $this->style_counter = 0;  
127 - // Load map  
128 - if(!$this->has_error()) {  
129 - $this->load_map();  
130 - }  
131 - }  
132 - /**  
133 - * Run the server and sends data  
134 - * @return string or void  
135 - */  
136 - function run(){  
137 - // Check cache  
138 - if(ENABLE_CACHE){  
139 - $cache_file = $this->get_cache_file_name();  
140 - if(file_exists($cache_file)){  
141 - $this->send_header();  
142 - readfile($cache_file);  
143 - exit;  
144 - }  
145 - }  
146 - // If not layer are requested, send all as networklinks  
147 - if(!$this->typename){  
148 - $this->_networklink = true;  
149 - $this->typename = $this->get_layer_list();  
150 - } else {  
151 - $this->_networklink = false;  
152 - }  
153 - if($this->_networklink == false){  
154 - //desliga todos os layers  
155 - for($i = 0; $i < $this->map_object->numlayers; $i++){  
156 - $l = $this->map_object->getLayer($i);  
157 - $l->set("status",MS_OFF);  
158 - }  
159 - //ajusta a legenda  
160 - $nomesl = explode(',', $this->typename);  
161 - foreach ($nomesl as $nomel){  
162 - $layer = $this->map_object->getlayerbyname($nomel);  
163 - if($layer){  
164 - $layer->set("status",MS_DEFAULT);  
165 - if ($layer->numclasses > 0){  
166 - $classe = $layer->getclass(0);  
167 - if (($classe->name == "") || ($classe->name == " ")){  
168 - $classe->set("name",$layer->getmetadata("tema"));  
169 - }  
170 - //corrige o titulo da legenda  
171 - $nclass = $layer->numclasses;  
172 - for($j=0;$j<$nclass;$j++){  
173 - $classe = $layer->getclass($j);  
174 - if($classe->title === ""){  
175 - $classe->title = $classe->name;  
176 - }  
177 - }  
178 - }  
179 - }  
180 - }  
181 - }  
182 - $imageObj = $this->map_object->drawlegend();  
183 - $url = $imageObj->saveWebImage();  
184 - $protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);  
185 - $url = strtolower($protocolo[0]."://".$_SERVER['HTTP_HOST']).$url;  
186 - $legenda = " <ScreenOverlay>" . PHP_EOL  
187 - . " <name>Legenda</name>" . PHP_EOL  
188 - . " <Icon>" . PHP_EOL  
189 - . " <href>".$url."</href>" . PHP_EOL  
190 - . " </Icon>" . PHP_EOL  
191 - . " <overlayXY x='0.01' y='0.14' xunits='fraction' yunits='fraction'/>" . PHP_EOL  
192 - . " <screenXY x='0.01' y='0.14' xunits='fraction' yunits='fraction'/>" . PHP_EOL  
193 - . " <size x='-1' y='-1' xunits='pixels' yunits='pixels'/>" . PHP_EOL  
194 - . " </ScreenOverlay>" . PHP_EOL;  
195 - if($this->_networklink == false){  
196 - $this->_xml = new SimpleXMLElement('<kml xmlns="http://earth.google.com/kml/2.0"><Document >'.$legenda.'</Document></kml>');  
197 - }  
198 - else{  
199 - $this->_xml = new SimpleXMLElement('<kml xmlns="http://earth.google.com/kml/2.0"><Document ></Document></kml>');  
200 - }  
201 - // Prepare projection  
202 - $this->in_proj = ms_newProjectionObj($this->map_object->getProjection());  
203 - // Set projection to GOOGLE earth's projection  
204 - $this->out_proj = ms_newProjectionObj("init=epsg:4326");  
205 - // Set endpoint  
206 - //die($_SERVER['REQUEST_URI']);  
207 -  
208 - $protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);  
209 - $protocolo = strtolower($protocolo[0]);  
210 - $this->endpoint = $protocolo . '://'.$_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] ? ':'.$_SERVER['SERVER_PORT'] : '') . $_SERVER['PHP_SELF'];  
211 - // Process request  
212 - if(!$this->has_error()) {  
213 - $this->process_request();  
214 - }  
215 - if($this->has_error()){  
216 - $this->add_errors();  
217 - }  
218 - return $this->send_stream($this->get_kml());  
219 - }  
220 -  
221 - /**  
222 - * Set debug flag  
223 - * @param boolean $value  
224 - */  
225 - function set_debug($value){  
226 - $this->_debug = $value;  
227 - }  
228 -  
229 - /**  
230 - * Get all request parameters  
231 - */  
232 - function get_request(){  
233 - $this->map = $this->load_parm('map');  
234 - $this->bbox = $this->load_parm('bbox');  
235 - $this->filter = $this->load_parm('filter');  
236 - $this->typename = $this->load_parm('typename');  
237 - $this->encoding = $this->load_parm('encoding', 'ISO-8859-1');  
238 - $this->request = $this->load_parm('request', 'kml');  
239 - if($this->request == 'kmz') {  
240 - $this->_zipped = true;  
241 - }  
242 - if(!$this->map){  
243 - $this->set_error('No mapfile specified');  
244 - }  
245 - }  
246 -  
247 - /**  
248 - * Apply filter  
249 - * @return array  
250 - */  
251 - function apply_filter(&$layer, &$filter){  
252 - if($layer->connectiontype == MS_POSTGIS){  
253 - if($filter->PropertyIsEqualTo){  
254 - $searchstring = '"'.$filter->PropertyIsEqualTo->PropertyName . ' = ' . '\''.addslashes($filter->PropertyIsEqualTo->Literal).'\''.'"';  
255 - $searchfield = $filter->PropertyIsEqualTo->PropertyName;  
256 - } elseif($filter->PropertyIsLike){  
257 - $searchfield = $filter->PropertyIsLike->PropertyName;  
258 - $searchstring ='"'.$filter->PropertyIsLike->PropertyName . ' LIKE \'%' . addslashes($filter->PropertyIsLike->Literal) . '%\''.'"';  
259 - }  
260 - } elseif($layer->connectiontype == MS_SHAPEFILE || $layer->connectiontype == MS_OGR){  
261 - if($filter->PropertyIsEqualTo){  
262 - $searchstring = $filter->PropertyIsEqualTo->Literal;  
263 - $searchfield = $filter->PropertyIsEqualTo->PropertyName;  
264 - } elseif($filter->PropertyIsLike){  
265 - $searchstring = $filter->PropertyIsLike->Literal;  
266 - $searchfield = $filter->PropertyIsLike->PropertyName;  
267 - }  
268 - }  
269 - return array($searchfield, $searchstring);  
270 - }  
271 - /**  
272 - * Process request  
273 - */  
274 - function process_request(){  
275 - // Get layer(s)  
276 - $layers = explode(',', $this->typename);  
277 - if($this->_networklink){  
278 - foreach($layers as $layer){  
279 - $this->add_networklink($layer);  
280 - }  
281 - } else {  
282 - foreach($layers as $layer){  
283 - //echo "Oi";exit;  
284 - $this->process_layer_request($layer);  
285 - }  
286 - }  
287 - }  
288 - /**  
289 - * Add a networklink  
290 - */  
291 - function add_networklink(&$layer_name){  
292 - $nl =& $this->_xml->Document->addChild('NetworkLink');  
293 - $layer = @$this->map_object->getLayerByName($layer_name);  
294 - if(!$layer)  
295 - {$layer = $this->map_object->getlayer(0);}  
296 - $nl->addChild('name', $this->get_layer_description($layer));  
297 - $nl->addChild('visibility', 0);  
298 - $link =& $nl->addChild('Link');  
299 - $link->addChild('href', $this->endpoint . '?map=' . $this->map . '&amp;typename=' . urlencode($layer_name) . '&amp;request=' . ($this->_zipped ? 'kmz' : 'kml'));  
300 - }  
301 -  
302 -  
303 - /**  
304 - * Process a single layer  
305 - * @return boolean false on error  
306 - */  
307 - function process_layer_request(&$layer_name){  
308 - error_reporting(0);  
309 - $v = "5.0.0";  
310 - $vs = explode(" ",ms_GetVersion());  
311 - $cvs = count($vs);  
312 - for ($i=0;$i<$cvs;++$i) {  
313 - if(trim(strtolower($vs[$i])) == "version")  
314 - {$v = $vs[$i+1];}  
315 - }  
316 - $v = explode(".",$v);  
317 - $versao = $v[0];  
318 -  
319 - $layer = @$this->map_object->getLayerByName($layer_name);  
320 - if(!$layer)  
321 - {$layer = $this->map_object->getlayer(0);}  
322 - if(!$layer){  
323 - $this->set_error('Nenhum layer com esse nome foi encontrado no mapfile ' . $layer_name, $layer_name);  
324 - return false;  
325 - }  
326 - // Add to layer list  
327 - $this->layers[$layer_name] =& $layer;  
328 - // Get custom template if any  
329 - $description_template = $layer->getMetadata('DESCRIPTION_TEMPLATE');  
330 - // Set on  
331 - $layer->set( 'status', MS_DEFAULT );  
332 - // Set kml title from layer description (default to layer name)  
333 - $layer_desc = $this->get_layer_description($layer);  
334 -  
335 - // Now switch raster layers  
336 - //var_dump($layer->type == MS_LAYER_RASTER);  
337 - if($layer->type == MS_LAYER_RASTER){  
338 - // Check if wms_onlineresource metadata is set  
339 - $wms_link = $this->map_object->getMetadata('wms_onlineresource');  
340 - if(!$wms_link){  
341 - $wms_link = $this->map_object->getMetadata('ows_onlineresource');  
342 - }  
343 - if(!$wms_link){  
344 - $this->set_error('No WMS server available for ' . $layer_name, $layer_name);  
345 - return false;  
346 - }  
347 - // Add parameters to OGC server call  
348 - // Fix &  
349 - $wms_link = preg_replace('/&/', '&amp;', $wms_link);  
350 - $wms_link .= 'VERSION=1.1.1&amp;REQUEST=GetMap&amp;SRS=EPSG:4618&amp;STYLES=&amp;FORMAT=image/png&amp;TRANSPARENT=TRUE&amp;';  
351 - // Link ok, create folder  
352 - //$folder =& $this->_xml->Document->addChild('GroundOverlay');  
353 - $folder =& $this->simplexml_addChild($this->_xml->Document,'GroundOverlay');  
354 - //simplexml_addChild($parent, $name, $value='')  
355 - //$folder->addChild('description', $this->get_layer_description($layer));  
356 - $this->simplexml_addChild($folder,'name',$layer_desc);  
357 -  
358 - //$folder->addChild('name', $layer_desc);  
359 - $this->add_wms_link($folder, $layer, $wms_link);  
360 - } else {  
361 - // Apply filter  
362 - if($this->filter){  
363 - // Try loading as XML  
364 - try {  
365 - $filter = @new SimpleXMLElement($this->filter);  
366 - list($searchfield, $searchstring) = $this->apply_filter($layer, $filter);  
367 - if(! ($searchfield && $searchstring)){  
368 - $this->set_error('Error parsing filter', $layer_name);  
369 - return false;  
370 - }  
371 - } catch (Exception $e) {  
372 - $this->set_error('Wrong XML filter', $layer_name);  
373 - $this->filter = null;  
374 - return false;  
375 - }  
376 - }  
377 -  
378 - // Get results  
379 - if(MS_SUCCESS == $layer->open()){  
380 - // Search which column to use to identify the feature  
381 - $namecol = $layer->getMetadata("itens");  
382 - if($namecol == ""){  
383 - $cols = array_values($layer->getItems());  
384 - $namecol = $cols[0];  
385 - }  
386 - else  
387 - {$namecol = explode(",",$namecol);$namecol = $namecol[0];}  
388 - // Add classes  
389 - $folder =& $this->_xml->Document->addChild('Folder');  
390 -  
391 - $class_list = $this->parse_classes($layer, $folder, $namecol, $title_field, $description_template);  
392 -  
393 - //die(print_r($class_list, true));  
394 - $folder->addChild('description', $this->get_layer_description($layer));  
395 - $folder->addChild('name', $layer_desc);  
396 -  
397 - //print("$searchfield && $searchstring");  
398 - if(!isset($searchfield)){$searchfield = false;}  
399 - if(!isset($searchstring)){$searchstring = false;}  
400 -  
401 - if($searchfield && $searchstring){  
402 - if(@$layer->queryByAttributes($searchfield, $searchstring, MS_MULTIPLE) == MS_SUCCESS){  
403 - $layer->open();  
404 - //var_dump($layer->getItems()); die();  
405 - for ($j=0; $j < $layer->getNumResults(); $j++)  
406 - {  
407 - // get next shape row  
408 - if($versao >= 6)  
409 - {$shape = $layer->getShape($layer->getResult($j));}  
410 - else{  
411 - $result = $layer->getResult($j);  
412 - $shape = $layer->getFeature($result->shapeindex,$result->tileindex);  
413 - }  
414 - $this->process_shape($layer, $shape, $class_list, $folder, $namecol);  
415 - // end for loop  
416 - }  
417 - } else {  
418 - $this->set_error('Query returned no data', $layer_name);  
419 - return false;  
420 - }  
421 - } else { // Get all shapes  
422 - $layer->set("template","none.htm");  
423 - $layer->queryByrect($this->map_object->extent);  
424 - $layer->open();  
425 - $n = $layer->getNumResults();  
426 - for ($j=0; $j < $n; $j++)  
427 - {  
428 - // get next shape row  
429 - if($versao >= 6)  
430 - {  
431 - $result = $layer->getResult($j);  
432 - $shape = $layer->getShape($result);  
433 - }  
434 - else{  
435 - $result = $layer->getResult($j);  
436 - $shape = $layer->getFeature($result->shapeindex,$result->tileindex);  
437 - }  
438 - $shape->classindex = $result->classindex;  
439 - $this->process_shape($layer, $shape, $class_list, $folder, $namecol);  
440 - }  
441 - if($n == 0) {  
442 - $this->set_error('QueryByRect returned no data', $layer_name);  
443 - return false;  
444 - }  
445 - }  
446 - $layer->close();  
447 - } else {  
448 - $this->set_error('Layer cannot be opened', $layer_name);  
449 - return false;  
450 - }  
451 - }  
452 - return true;  
453 - }  
454 -  
455 - /**  
456 - * Process the shape  
457 - */  
458 - function process_shape(&$layer, &$shape, &$class_list, &$folder, &$namecol){  
459 - $permite = $layer->getmetadata("permitekmz");  
460 - if(strtolower($permite) == "nao"){return;}  
461 - $itens = $layer->getmetadata("itens");  
462 - $itensdesc = $layer->getmetadata("itensdesc");  
463 - $shape->project($this->in_proj, $this->out_proj);  
464 - // Assign style  
465 - if($layer->classitem){  
466 - //$style_id = $this->get_shape_class($layer->classitem, $shape->values, $class_list);  
467 - }  
468 - if(!isset($style_id)){  
469 - // Get first class  
470 - $class_keys = array_keys($class_list);  
471 - $indice = $shape->classindex;  
472 - $classe = $layer->getclass($indice);  
473 - $nome= $classe->name;  
474 - $style_id = preg_replace('/[^A-z0-9]/', '_', $layer->name . $nome);  
475 - }  
476 - // Add the feature  
477 - if(array_key_exists('folder', $class_list[$style_id])) {  
478 - $feature_folder =& $class_list[$style_id]['folder'];  
479 - } else {  
480 - //die('missing folder for ' . $style_id);  
481 - $feature_folder =& $folder;  
482 - }  
483 - if(!is_object($feature_folder)){  
484 - $folder_name = $feature_folder;  
485 - $feature_folder =& $folder ->addChild('Folder');  
486 - $feature_folder->addChild('name', $folder_name);  
487 - }  
488 - // Add style class  
489 - $style_url =& $this->add_style($layer, $feature_folder, $style_id, $class_list[$style_id], $namecol, $shape->values);  
490 - $wkt = $shape->toWkt();  
491 - $description_template = $layer->getMetadata('DESCRIPTION_TEMPLATE');//false;  
492 - if($description_template == "")  
493 - {$description_template = false;}  
494 - $placemark =& $this->add_feature($feature_folder, $wkt, $shape->values[$namecol], $shape->values, $description_template, $class_list[$style_id],$itens,$itensdesc);  
495 -  
496 - $placemark->addChild('styleUrl', '#'. $style_url);  
497 -  
498 - }  
499 - /**  
500 - * Add the feature to the result set  
501 - * @return reference to placemark object  
502 - */  
503 - function &add_feature(&$folder, &$wkt, $featurename, $attributes, $description_template, $style_data,$itens,$itensdesc){  
504 - $pm = $folder->addChild('Placemark');  
505 - $fname = mb_convert_encoding($featurename,"UTF-8",mb_detect_encoding($featurename,'UTF-8, UTF-7, ASCII, ISO-8859-1'));  
506 - $pm->addChild('name',$fname);  
507 - $pm->addChild('description', $this->get_feature_description($fname, $attributes, $description_template,$itens,$itensdesc));  
508 - // Now parse the wkt  
509 - if(strpos($wkt, 'MULTILINESTRING') !== false){  
510 - $this->add_multilinestring($wkt, $pm, $featurename, $style_data['icon']);  
511 - } elseif(strpos($wkt, 'LINESTRING') !== false){  
512 - $this->add_linestring($wkt, $pm, $featurename, $style_data['icon']);  
513 - } elseif(strpos($wkt, 'POINT') !== false){  
514 - $this->add_point($wkt, $pm, $featurename);  
515 - } elseif(strpos($wkt, 'MULTIPOLYGON') !== false){  
516 - if(TREAT_POLY_AS_LINE){  
517 - $ml = $pm->addChild('MultiGeometry');  
518 - foreach(split('\), \(', $wkt) as $line){  
519 - $this->add_multilinestring($line, $ml, $featurename );  
520 - }  
521 - } else {  
522 - $this->add_multipolygon($wkt, $pm, $featurename);  
523 - }  
524 - } elseif(strpos($wkt, 'POLYGON') !== false){  
525 - if(TREAT_POLY_AS_LINE){  
526 - $this->add_multilinestring($wkt, $pm, $featurename);  
527 - } else {  
528 - $this->add_polygon($wkt, $pm, $featurename);  
529 - }  
530 - } else {  
531 - // Error?  
532 - }  
533 - return $pm;  
534 - }  
535 -  
536 - /**  
537 - * Add a linestring  
538 - */  
539 - function add_linestring(&$wkt, &$element, $featurename, $add_points){  
540 - preg_match('/(\d+[^\(\)]*\d)/', $wkt, $data);  
541 - $data = str_replace(', ', '#', $data[1]);  
542 - $data = str_replace(' ', ',', $data);  
543 - $data = str_replace('#', ' ', $data);  
544 - if($add_points){  
545 - preg_match('/^(\d+\.\d+,\d+\.\d+).*(\d+\.\d+,\d+\.\d+)$/', $data, $points);  
546 - if(count($points) == 3){  
547 - $mg = $element->addChild('MultiGeometry');  
548 - $ls = $mg->addChild('LineString');  
549 - $pt1 = $mg->addChild('Point');  
550 - $pt1->addChild('coordinates', $points[1]);  
551 - $pt2 = $mg->addChild('Point');  
552 - $pt2->addChild('coordinates', $points[2]);  
553 - } else {  
554 - die('errore');  
555 - $ls = $element->addChild('LineString');  
556 - }  
557 - //print_r($points);die();  
558 - } else {  
559 - $ls = $element->addChild('LineString');  
560 - }  
561 - $ls->addChild('coordinates', $data);  
562 - }  
563 -  
564 - /**  
565 - * Add a multilinestring  
566 - */  
567 - function add_multilinestring(&$wkt, &$element, $featurename, $add_points){  
568 - $ml = $element->addChild('MultiGeometry');  
569 - foreach(split('\), \(', $wkt) as $line){  
570 - $this->add_linestring($line, $ml, $featurename, $add_points );  
571 - }  
572 - }  
573 -  
574 - /**  
575 - * Add a point  
576 - */  
577 - function add_point(&$wkt, &$element, $featurename){  
578 - $pt = $element->addChild('Point');  
579 - /*  
580 - preg_match('/(\d\.?\d+\s\d+\.?\d+)/', $wkt, $data);  
581 - //var_dump($data);exit;  
582 - $data = str_replace(' ', ',', $data[1]);  
583 - */  
584 - $data = str_replace("(","",$wkt);  
585 - $data = str_replace(")","",$data);  
586 - $data = str_replace("POINT","",$data);  
587 - $data = str_replace(" ",",",trim($data));  
588 - //echo $data;exit;  
589 - $pt->addChild('coordinates', $data);  
590 - }  
591 -  
592 -  
593 - /**  
594 - * Add a polygon  
595 - */  
596 - function add_polygon(&$wkt, &$element, $featurename){  
597 - $ml = $element->addChild('Polygon');  
598 - foreach(split('\), \(', $wkt) as $line){  
599 - preg_match('/(\d+[^\(\)]*\d)/', $wkt, $data);  
600 - $data = str_replace(', ', '#', $data[1]);  
601 - $data = str_replace(' ', ',', $data);  
602 - // Add 1 meter height  
603 - $data = str_replace('#', ',1 ', $data) . ',1';  
604 - $ml->addChild('tessellate', 1);  
605 - //$element->addChild('altitudeMode', 'relativeToGround');  
606 - $element->addChild('altitudeMode', 'clampToGround');  
607 - $ob = $ml->addChild('outerBoundaryIs');  
608 - $ls = $ob->addChild('LinearRing');  
609 - $ls->addChild('coordinates', $data);  
610 - }  
611 - }  
612 -  
613 -  
614 - /**  
615 - * Add a multipolygon  
616 - * fixme: untested, should take holes into account  
617 - */  
618 - function add_multipolygon(&$wkt, &$element, $featurename){  
619 - $ml = $element->addChild('MultiGeometry');  
620 - foreach(split('\), \(', $wkt) as $line){  
621 - $this->add_polygon($line, $ml, $featurename );  
622 - }  
623 - }  
624 -  
625 -  
626 - /**  
627 - * Get the feature description  
628 - */  
629 - function get_feature_description($featurename, $attributes, $description_template,$itens,$itensdesc){  
630 - // Compute hyperlink  
631 - //var_dump($attributes);exit;  
632 - //if($description_template != ""){return $description_template;}  
633 - $n = "";  
634 - if($description_template != "")  
635 - {  
636 - foreach($attributes as $k => $val)  
637 - {$description_template = str_replace("%".$k."%",$attributes[$k],$description_template);}  
638 - $n = $description_template;  
639 - }  
640 - else  
641 - {  
642 - if($itens == "")  
643 - {  
644 - foreach($attributes as $k => $val){  
645 - $n .= $k." - ".$attributes[$k]."\n";  
646 - }  
647 - }  
648 - else  
649 - {  
650 - $itens = explode(",",$itens);  
651 - $itensdesc = explode(",",$itensdesc);  
652 - for($i=0;$i<count($itens);$i++)  
653 - {$n .= $itensdesc[$i]." - ".$attributes[$itens[$i]]."\n";}  
654 - }  
655 - }  
656 - $description = mb_convert_encoding($n,"UTF-8",mb_detect_encoding($n,"UTF-8,ISO-8859-1"));  
657 - return $description;  
658 - }  
659 - /**  
660 - * Parse classes  
661 - * @return array hash of 'style_id' => style_data)  
662 - */  
663 - function parse_classes(&$layer, &$folder, &$namecol, &$title_field, &$description_template ){  
664 - $style_ar = array();  
665 - $numclasses = $layer->numclasses;  
666 - $versao = $this->versao();  
667 - $vi = $versao["inteiro"];  
668 - for($i = 0; $i < $numclasses; $i++){  
669 - $class = $layer->getClass($i);  
670 - if($vi >= 60200){  
671 - if($class->numlabels > 0)  
672 - $label = $class->getLabel(0);  
673 - }  
674 - else{  
675 - $label = $class->label;  
676 - }  
677 - if($label){  
678 - $style['label_color'] = $label->color;  
679 - $style['label_size'] = $label->size;  
680 - }  
681 - // Get styles  
682 - for($j = 0; $j < $class->numstyles; $j++){  
683 - $_style = $class->getStyle($j);  
684 - $style['color'] = $_style->color;  
685 - $style['outlinecolor'] = $_style->outlinecolor;  
686 - $style['width'] = $_style->size; // Lines  
687 - $style['backgroundcolor'] = $_style->backgroundcolor;  
688 - if($layer->type == MS_LAYER_POINT)  
689 - $style['icon'] = $this->get_icon_url($layer, $class->name,$i);  
690 - $style['icon_width'] = $_style->size; // Points  
691 - }  
692 - $style['expression'] = $class->getExpressionString();  
693 - // Set description_template if any  
694 - $style['description_template'] = $description_template;  
695 - // Get icon for lines if any  
696 - if($icon = $layer->getMetadata('KML_ADD_POINT')){  
697 - $style['icon'] = $icon;  
698 - $style['icon_width'] = 32;  
699 - }  
700 - // Create style element  
701 - $style_id = preg_replace('/[^A-z0-9]/', '_', $layer->name . $class->name);  
702 - $this->add_style($layer, $folder, $style_id, $style, $namecol, $title_field );  
703 - // create folder if more than one class  
704 - if($numclasses > 1){  
705 - //$style['folder'] =& $class->name;  
706 - //$folder->addChild('Folder');  
707 - //$style['folder']->addChild('name', $class->name);  
708 - }  
709 - $style_ar[$style_id] = $style;  
710 - }  
711 - return $style_ar;  
712 - }  
713 -  
714 - /**  
715 - * Return a CSV list of all layer names in the mapfile  
716 - * fixme: filter out ANNOTATIONS and other "strange" layers  
717 - */  
718 - function get_layer_list(){  
719 - $layer_list = array();  
720 - for($i = 0; $i < $this->map_object->numlayers; $i++){  
721 - $layer =& $this->map_object->getLayer($i);  
722 - $kml_skip = $layer->getMetadata('KML_SKIP');  
723 - if(strtolower($kml_skip) !== 'true'){  
724 - $layer_list[] = $layer->name;  
725 - }  
726 - }  
727 - return join(',', $layer_list);  
728 - }  
729 -  
730 -  
731 - /**  
732 - * Return the class for the shape, default to last class if not match  
733 - */  
734 - function get_shape_class(&$classitem, &$values, &$class_list){  
735 - //var_dump($class_list); die();  
736 - foreach($class_list as $style_id => $style_data){  
737 - if($style_data['expression'] && preg_match($style_data['expression'], $values[$classitem])){  
738 - //print "get_shape_class($classitem) ".$values[$classitem]." matches<br>";  
739 - return $style_id;  
740 - }  
741 - }  
742 - //print "get_shape_class($classitem) ".$values[$classitem]." no matches<br>";  
743 - return $style_id;  
744 - }  
745 -  
746 - /**  
747 - * Add the style  
748 - * @return the style URL  
749 - */  
750 - function add_style(&$layer, &$folder, $style_id, &$style_data){  
751 - // Calculare style URL  
752 -  
753 - if($style_data['description_template']){  
754 - $this->style_counter++;  
755 - $style_id .= '_'.$this->style_counter;  
756 - $balloon_data = $this->get_feature_description($attributes[$namecol], $attributes, $style_data['description_template']);  
757 - }  
758 -  
759 - // Check if the style already exists  
760 - $expr = '//*[@id=\''.$style_id.'\']';  
761 - if($folder->xpath($expr)) {  
762 - return $style_id;  
763 - }  
764 - $new_style =& $folder->addChild('Style');  
765 - $new_style['id'] = $style_id;  
766 - // Switch layer type  
767 - switch($layer->type){  
768 - case MS_LAYER_POINT:  
769 - $this->add_style_point($new_style, $style_data);  
770 - break;  
771 - case MS_LAYER_POLYGON:  
772 - $this->add_style_polygon($new_style, $style_data);  
773 - break;  
774 - case MS_LAYER_LINE:  
775 - $this->add_style_line($new_style, $style_data);  
776 - // Add KML_ADD_POINT icon  
777 - if($style_data['icon']){  
778 - $this->add_style_point($new_style, $style_data);  
779 - }  
780 - break;  
781 - }  
782 - return $style_id;  
783 - }  
784 -  
785 - /**  
786 - * Add style for lines  
787 - */  
788 - function add_style_line(&$new_style, &$style_data){  
789 - if($style_data['outlinecolor']->red != -1){  
790 - $st =& $new_style->addChild('LineStyle');  
791 - $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['outlinecolor']->blue, $style_data['outlinecolor']->green, $style_data['outlinecolor']->red));  
792 - if($width) {  
793 - $st->addChild('width', $width);  
794 - }  
795 - } elseif($style_data['color']->red != -1){  
796 - $st =& $new_style->addChild('LineStyle');  
797 - $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['color']->blue, $style_data['color']->green, $style_data['color']->red));  
798 - if($width) {  
799 - $st->addChild('width', $width);  
800 - }  
801 - }  
802 - }  
803 -  
804 - /**  
805 - * Add style for points  
806 - */  
807 - function add_style_point(&$new_style, &$style_data){  
808 - if($style_data['icon']){  
809 - $st =& $new_style->addChild('IconStyle');  
810 - if($style_data['width'] && $style_data['icon_width'] != 32){  
811 - /**  
812 - *  
813 - */  
814 - //$st->addChild('scale', $style_data['icon_width'] / 32);  
815 - $st->addChild('scale', 1);  
816 - }  
817 - else  
818 - {$st->addChild('scale', 1);}  
819 - $icon =& $st->addChild('Icon');  
820 - $icon->addChild('href', htmlentities($style_data['icon']));  
821 -  
822 - }  
823 - $ls =& $new_style->addChild('LabelStyle');  
824 - $ls->addChild('scale', $style_data['label_size'] / 32);  
825 - // Add the balloon style if description_template is set  
826 - /*  
827 - if($style_data['description_template']){  
828 - $this->add_balloon_style($new_style, $balloon_data);  
829 - }  
830 - */  
831 - // Label size and color  
832 - /*  
833 - if($style_data['label_size'] || $style_data['label_color']){  
834 - $ls =& $new_style->addChild('LabelStyle');  
835 - if($style_data['label_size'] != -1 && $style_data['label_size'] != 32){  
836 - $ls->addChild('scale', $style_data['label_size'] / 32);  
837 - }  
838 - if($style_data['label_color']->red != -1){  
839 - $ls->addChild('color', sprintf('FF%02X%02X%02X', $style_data['label_color']->blue, $style_data['label_color']->green, $style_data['label_color']->red));  
840 - }  
841 - }  
842 - */  
843 - }  
844 -  
845 - /**  
846 - * Add style for polygons  
847 - */  
848 - function add_style_polygon(&$new_style, &$style_data){  
849 - // Get also outline styles  
850 - $this->add_style_line($new_style, $style_data);  
851 - $st =& $new_style->addChild('PolyStyle');  
852 - //die(print_r($backgroundcolor, true));  
853 - if($style_data['color']->red != -1){  
854 - $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['color']->blue, $style_data['color']->green, $style_data['color']->red));  
855 - $st->addChild('fill', 1);  
856 - } else {  
857 - $st->addChild('fill', 0);  
858 - }  
859 - $st->addChild('outline', 1);  
860 - }  
861 -  
862 - /**  
863 - * Add a WMS raster link  
864 - */  
865 - function add_wms_link(&$folder, &$layer, &$link){  
866 - // Build up the KML response document.  
867 - //$icon =& $folder->addChild('Icon');  
868 - $icon =& $this->simplexml_addChild($folder,'Icon');  
869 - //$icon->addChild('href', $link . 'layers=' . $layer->name);  
870 - $this->simplexml_addChild($icon,'href', $link . 'layers=' . $layer->name);  
871 - //$icon->addChild('viewRefreshMode', 'onStop');  
872 - $this->simplexml_addChild($icon,'viewRefreshMode', 'onStop');  
873 - //$llbox =& $folder->addChild('LatLonBox');  
874 - $llbox =& $this->simplexml_addChild($folder,'LatLonBox');  
875 - $ext = $this->map_object->extent;  
876 - $ext->project($this->in_proj, $this->out_proj);  
877 - //$llbox->north = $ext->maxy;  
878 - $this->simplexml_addChild($llbox,'north', $ext->maxy);  
879 - //$llbox->south = $ext->miny;  
880 - $this->simplexml_addChild($llbox,'south', $ext->miny);  
881 - //$llbox->east = $ext->maxx;  
882 - $this->simplexml_addChild($llbox,'east', $ext->maxx);  
883 - //$llbox->west = $ext->minx;  
884 - $this->simplexml_addChild($llbox,'west', $ext->minx);  
885 - // Reset original projection  
886 - $ext->project($this->out_proj, $this->in_proj);  
887 - }  
888 -  
889 - /**  
890 - * Get the url for a point icon  
891 - */  
892 - function get_icon_url($layer, $classname, $classindex){  
893 - $classe = $layer->getclass($classindex);  
894 - $estilo = $classe->getstyle(0);  
895 - $url = "";  
896 - $imageObj = $classe->createLegendIcon(30,30);  
897 - if($imageObj)  
898 - {  
899 - $url = $imageObj->saveWebImage();  
900 - $protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);  
901 - $url = strtolower($protocolo[0]."://".$_SERVER['HTTP_HOST']).$url;  
902 - $nome = $imageObj->imagepath . basename($url);  
903 -  
904 - $img = imagecreatefrompng($nome);  
905 - $index = imagecolorexact($img, 255, 255, 255);  
906 - imagecolortransparent($img, $index);  
907 - imagepng($img, $nome);  
908 - }  
909 - return $url; //$this->endpoint . '?service=icon&map=' . $this->map . '&typename=' . urlencode($layer->name) . '&classname=' . urlencode($classname);  
910 - }  
911 -  
912 - /**  
913 - * Get the layer description  
914 - */  
915 - function get_layer_description(&$layer){  
916 - $description = $layer->getMetadata('DESCRIPTION');  
917 - if(!$description){  
918 - $description = $layer->getMetadata('OWS_TITLE');  
919 - }  
920 - if(!$description){  
921 - $description = $layer->getMetadata('WFS_TITLE');  
922 - }  
923 - if(!$description){  
924 - $description = $layer->getMetadata('WMS_TITLE');  
925 - }  
926 - if(!$description){  
927 - $description = $layer->getMetadata('TEMA');  
928 - }  
929 - if(!$description){  
930 - $description = $layer->name;  
931 - }  
932 - $description = mb_convert_encoding($description,"UTF-8",mb_detect_encoding($description,"UTF-8,ISO-8859-1"));  
933 - return $description;  
934 - }  
935 -  
936 -  
937 -  
938 - /**  
939 - * Add style for balloon  
940 - * @param string style XML id  
941 - * @param string column name for title  
942 - */  
943 - function add_balloon_style(&$style, $balloon_data){  
944 - $balloon =& $style->addChild('BalloonStyle');  
945 - $balloon->addChild('text', htmlentities($balloon_data));  
946 - }  
947 -  
948 -  
949 - /**  
950 - * Get a request parameter  
951 - * @param string $name  
952 - * @param string $default parameter optional  
953 - * @return string the parameter value or empty string if null  
954 - */  
955 - function load_parm($name, $default = ''){  
956 - if(!isset($_REQUEST[$name])) return $default;  
957 - $value = $_REQUEST[$name];  
958 - if(get_magic_quotes_gpc() != 1) $value = addslashes($value);  
959 - //$value = escapeshellcmd($value);  
960 - return $value;  
961 - }  
962 -  
963 - /**  
964 - * Set error message  
965 - * @param string $message  
966 - * @param string $layer name  
967 - */  
968 - function set_error($message, $layer = 'Error'){  
969 - $this->errors[$layer][] = $message;  
970 - }  
971 - /**  
972 - * Load the map and create the map instance  
973 - */  
974 - function load_map(){  
975 - if(!file_exists($this->map) && is_readable($this->map)){  
976 - $this->set_error('Cannot read mapfile '. $this->map);  
977 - } else {  
978 - $protocolo = explode("/",$_SERVER['SERVER_PROTOCOL']);  
979 - $servidor = strtolower($protocolo[0])."://".$_SERVER['HTTP_HOST'];  
980 - $temp = $this->map;  
981 - if(file_exists(dirname(__FILE__)."/../../../ms_configura.php")){  
982 - include(dirname(__FILE__)."/../../../ms_configura.php");  
983 - } else {  
984 - include(dirname(__FILE__)."/../../ms_configura.php");  
985 - }  
986 - if(!file_exists($this->map)){  
987 - $maptemp = ms_newMapObj($locaplic."/temas/".$this->map.".map");  
988 - //if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))  
989 - //{$this->map = $locaplic."/aplicmap/geral1windows.map";}  
990 - //else  
991 - //{$this->map = $locaplic."/aplicmap/geral1.map";}  
992 -  
993 - $versao = $this->versao();  
994 - $versao = $versao["principal"];  
995 - if(!isset($base) || $base == "")  
996 - {  
997 - if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))  
998 - {$base = $locaplic."/aplicmap/geral1windowsv".$versao.".map";}  
999 - else  
1000 - {  
1001 - if($base == "" && file_exists('/var/www/i3geo/aplicmap/geral1debianv'.$versao.'.map')){  
1002 - $base = "/var/www/i3geo/aplicmap/geral1debianv".$versao.".map";  
1003 - }  
1004 - if($base == "" && file_exists('/var/www/html/i3geo/aplicmap/geral1fedorav'.$versao.'.map')){  
1005 - $base = "/var/www/html/i3geo/aplicmap/geral1fedorav".$versao.".map";  
1006 - }  
1007 - if($base == "" && file_exists('/opt/www/html/i3geo/aplicmap/geral1fedorav'.$versao.'.map')){  
1008 - $base = "/opt/www/html/i3geo/aplicmap/geral1v".$versao.".map";  
1009 - }  
1010 - if($base == "")  
1011 - {$base = $locaplic."/aplicmap/geral1v".$versao.".map";}  
1012 - }  
1013 - }  
1014 - $this->map = $base;  
1015 -  
1016 - $this->map_object = ms_newMapObj($this->map);  
1017 - if(!$this->_zipped){  
1018 - $this->map_object->setmetadata('wms_onlineresource',$servidor.":80/i3geo/ogc.php?tema=".$temp."&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");  
1019 - $this->map_object->setmetadata("ows_enable_request","*");  
1020 - }  
1021 - $n = $this->map_object->numlayers;  
1022 - for ($i=0;$i < $n;$i++)  
1023 - {  
1024 - $l = $this->map_object->getlayer($i);  
1025 - $l->set("status",MS_DELETE);  
1026 - $l->set("name","");  
1027 - }  
1028 - for ($i=0;$i < ($maptemp->numlayers);$i++)  
1029 - {  
1030 - $l = $maptemp->getlayer($i);  
1031 - $l->set("status",MS_DEFAULT);  
1032 - if(!$this->_zipped)  
1033 - {  
1034 - $l->set("type",MS_LAYER_RASTER);  
1035 - $l->setmetadata('wms_onlineresource',"../../ogc.php?tema=".$temp."&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");  
1036 - $l->setmetadata("ows_enable_request","*");  
1037 - }  
1038 - ms_newLayerObj($this->map_object, $l);  
1039 - }  
1040 - }  
1041 - else{  
1042 - $this->map_object = ms_newMapObj($this->map);  
1043 - //$w = $this->map_object->web;  
1044 - //$w->set("template","none.htm");  
1045 -  
1046 - if(!$this->_zipped){  
1047 - //$this->map_object->setmetadata('wms_onlineresource',$servidor.":80".$locmapserv."?map=".$temp."&width=1500&height=1500&");  
1048 - $this->map_object->setmetadata('wms_onlineresource',"../../ogc.php?tema=".$temp."&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");  
1049 - $this->map_object->setmetadata("ows_enable_request","*");  
1050 - }  
1051 - $n = $this->map_object->numlayers;  
1052 - for ($i=0;$i < $n;$i++)  
1053 - {  
1054 - $l = $this->map_object->getlayer($i);  
1055 - $l->set("status",MS_DEFAULT);  
1056 - if(!$this->_zipped)  
1057 - $l->set("type",MS_LAYER_RASTER);  
1058 - //$l->setmetadata('wms_onlineresource',"../../ogc.php?tema=".$temp."&width=500&height=500&");  
1059 - //ms_newLayerObj($this->map_object, $l);  
1060 - }  
1061 - }  
1062 - if(!$this->map_object){  
1063 - $this->set_error('Cannot load mapfile '. $this->map);  
1064 - }  
1065 - }  
1066 - }  
1067 -  
1068 - /**  
1069 - * Test if has errors  
1070 - * @return boolean  
1071 - */  
1072 - function has_error(){  
1073 - return count($this->errors) > 0;  
1074 - }  
1075 -  
1076 - /**  
1077 - * Add error messages to folders TAGS  
1078 - */  
1079 - function add_errors(){  
1080 - foreach($this->errors as $layer => $errors){  
1081 - $folder =& $this->_xml->Document->addChild('Folder');  
1082 - $folder->addChild('name', $layer);  
1083 - $folder->addChild('description', '<p>' . join("</p>\n<p>", $errors) . "</p>");  
1084 - }  
1085 - return $errorxml;  
1086 - }  
1087 -  
1088 - /**  
1089 - * Fetch XML and format it  
1090 - */  
1091 - function get_kml(){  
1092 - $doc = new DOMDocument('1.0');  
1093 - $doc->formatOutput = true;  
1094 - $domnode = dom_import_simplexml($this->_xml);  
1095 - $domnode = $doc->importNode($domnode, true);  
1096 - $domnode = $doc->appendChild($domnode);  
1097 - return $doc->saveXML();  
1098 - }  
1099 -  
1100 - /**  
1101 - * Send header  
1102 - */  
1103 - function send_header(){  
1104 - header('Content-Disposition: attachment; filename=kml.km'.($this->_zipped ? 'z' : 'l'));  
1105 - header('Content-type: application/vnd.google-earth.km'.($this->_zipped ? 'z' : 'l').'+XML');  
1106 - }  
1107 -  
1108 - /**  
1109 - * Calculate cache file name  
1110 - */  
1111 - function get_cache_file_name(){  
1112 - //obtem o arquivo do metadata do layer se existir  
1113 - $layer = @$this->map_object->getlayerbyname($this->typename);  
1114 - if(!$layer)  
1115 - {$layer = $this->map_object->getlayer(0);}  
1116 - $k = $layer->getmetadata("arquivokmz");  
1117 - if($k != ""){  
1118 - return $k;  
1119 - }  
1120 - if(file_exists(dirname(__FILE__)."/../../../ms_configura.php")){  
1121 - include(dirname(__FILE__)."/../../../ms_configura.php");  
1122 - } else {  
1123 - include(dirname(__FILE__)."/../../ms_configura.php");  
1124 - }  
1125 - return $dir_tmp.'/'. md5($_SERVER['QUERY_STRING']) . ($this->_zipped ? '.kmz' : '.kml');  
1126 - }  
1127 -  
1128 - /**  
1129 - * Send stream  
1130 - */  
1131 - function send_stream($data){  
1132 - $this->send_header();  
1133 - // Compress data  
1134 -  
1135 - if($this->_zipped){  
1136 - include("zip.class.php");  
1137 - $ziper = new zipfile();  
1138 - $ziper->addFile($data, 'doc.kml');  
1139 - $data = $ziper->file();  
1140 - }  
1141 -  
1142 - // Create cache if needed  
1143 - if(ENABLE_CACHE && count($this->layers) == 1) {  
1144 - //error_log( 'creating cache ' . $this->get_cache_file_name() );  
1145 - file_put_contents($this->get_cache_file_name(), $data);  
1146 - }  
1147 - print $data;  
1148 - exit();  
1149 - }  
1150 -// phpversion <= 5.1.2  
1151 -  
1152 -function simplexml_addChild($parent, $name, $value=''){  
1153 - $new_child = new SimpleXMLElement("<$name>$value</$name>");  
1154 - $node1 = dom_import_simplexml($parent);  
1155 - $dom_sxe = dom_import_simplexml($new_child);  
1156 - $node2 = $node1->ownerDocument->importNode($dom_sxe, true);  
1157 - $node1->appendChild($node2);  
1158 - return simplexml_import_dom($node2); 58 +if (! function_exists('ms_GetVersion')) {
  59 + echo "Nao foi possivel carregar php_mapscript";
1159 } 60 }
1160 -function versao() 61 +
  62 +/**
  63 + * Main server class
  64 + */
  65 +class LayerServer
1161 { 66 {
1162 - $v = "5.0.0";  
1163 - $vs = explode(" ",ms_GetVersion());  
1164 - $cvs = count($vs);  
1165 - for ($i=0;$i<$cvs;++$i)  
1166 - {  
1167 - if(trim(strtolower($vs[$i])) == "version")  
1168 - {$v = $vs[$i+1];}  
1169 - }  
1170 - $versao["completa"] = $v;  
1171 - $v = explode(".",$v);  
1172 - $versao["principal"] = $v[0];  
1173 - $versao["inteiro"] = ms_GetVersionInt();  
1174 - return $versao;  
1175 -} 67 +
  68 + /**
  69 + * map file path
  70 + */
  71 + var $map;
  72 +
  73 + /**
  74 + * request
  75 + */
  76 + var $request;
  77 +
  78 + /**
  79 + * map instance
  80 + */
  81 + var $map_object;
  82 +
  83 + /**
  84 + * layer name(s) passed on the request
  85 + */
  86 + var $typename;
  87 +
  88 + /**
  89 + * array of requested layer objects (hash with layer name as key)
  90 + */
  91 + var $layers;
  92 +
  93 + /**
  94 + * filters
  95 + */
  96 + var $filter;
  97 +
  98 + /**
  99 + * bounding box
  100 + */
  101 + var $bbox;
  102 +
  103 + /**
  104 + * error messages
  105 + */
  106 + var $errors;
  107 +
  108 + /**
  109 + * send zipped data
  110 + */
  111 + var $_zipped = false;
  112 +
  113 + /**
  114 + * internal XML buffer
  115 + */
  116 + var $_xml;
  117 +
  118 + /**
  119 + * input projection
  120 + */
  121 + var $in_proj;
  122 +
  123 + /**
  124 + * output projection
  125 + */
  126 + var $out_proj;
  127 +
  128 + /**
  129 + * debug flag
  130 + */
  131 + var $_debug = false;
  132 +
  133 + /**
  134 + * end point
  135 + */
  136 + var $endpoint;
  137 +
  138 + /**
  139 + * custom style counter
  140 + */
  141 + var $style_counter = 0;
  142 +
  143 + /**
  144 + * Mapfile and data encoding encoding
  145 + * XMl output must be UTF-8, attributes and METADATA based strings
  146 + * must be converted to UTF-8, encoding defaults to ISO-8859-1, if
  147 + * your encoding is different, you can set it through CGI style parameters
  148 + */
  149 + var $encoding;
  150 +
  151 + /**
  152 + * send networklink
  153 + * wether folder should contain networklinks instead of real geometries
  154 + * it is automatically set when all layers are requested
  155 + */
  156 + var $_networklink;
  157 + var $postgis_mapa;
  158 +
  159 + /**
  160 + * Initialize
  161 + */
  162 + function LayerServer()
  163 + {
  164 + $this->errors = array();
  165 + // Load request parameters
  166 + $this->get_request();
  167 + $this->style_counter = 0;
  168 + // Load map
  169 + if (! $this->has_error()) {
  170 + $this->load_map();
  171 + }
  172 + }
  173 +
  174 + /**
  175 + * Run the server and sends data
  176 + *
  177 + * @return string or void
  178 + */
  179 + function run()
  180 + {
  181 + // Check cache
  182 + if (ENABLE_CACHE) {
  183 + $cache_file = $this->get_cache_file_name();
  184 + if (file_exists($cache_file)) {
  185 + $this->send_header();
  186 + readfile($cache_file);
  187 + exit();
  188 + }
  189 + }
  190 + // If not layer are requested, send all as networklinks
  191 + if (! $this->typename) {
  192 + $this->_networklink = true;
  193 + $this->typename = $this->get_layer_list();
  194 + } else {
  195 + $this->_networklink = false;
  196 + }
  197 + if ($this->_networklink == false) {
  198 + // desliga todos os layers
  199 + for ($i = 0; $i < $this->map_object->numlayers; $i ++) {
  200 + $l = $this->map_object->getLayer($i);
  201 + $l->set("status", MS_OFF);
  202 + }
  203 + // ajusta a legenda
  204 + $nomesl = explode(',', $this->typename);
  205 + foreach ($nomesl as $nomel) {
  206 + $layer = $this->map_object->getlayerbyname($nomel);
  207 + if ($layer) {
  208 + $layer->set("status", MS_DEFAULT);
  209 + if ($layer->numclasses > 0) {
  210 + $classe = $layer->getclass(0);
  211 + if (($classe->name == "") || ($classe->name == " ")) {
  212 + $classe->set("name", $layer->getmetadata("tema"));
  213 + }
  214 + // corrige o titulo da legenda
  215 + $nclass = $layer->numclasses;
  216 + for ($j = 0; $j < $nclass; $j ++) {
  217 + $classe = $layer->getclass($j);
  218 + if ($classe->title === "") {
  219 + $classe->title = $classe->name;
  220 + }
  221 + }
  222 + }
  223 + }
  224 + }
  225 + }
  226 + $imageObj = $this->map_object->drawlegend();
  227 + $url = $imageObj->saveWebImage();
  228 + $protocolo = explode("/", $_SERVER['SERVER_PROTOCOL']);
  229 + $url = strtolower($protocolo[0] . "://" . $_SERVER['HTTP_HOST']) . $url;
  230 + $legenda = " <ScreenOverlay>" . PHP_EOL . " <name>Legenda</name>" . PHP_EOL . " <Icon>" . PHP_EOL . " <href>" . $url . "</href>" . PHP_EOL . " </Icon>" . PHP_EOL . " <overlayXY x='0.01' y='0.14' xunits='fraction' yunits='fraction'/>" . PHP_EOL . " <screenXY x='0.01' y='0.14' xunits='fraction' yunits='fraction'/>" . PHP_EOL . " <size x='-1' y='-1' xunits='pixels' yunits='pixels'/>" . PHP_EOL . " </ScreenOverlay>" . PHP_EOL;
  231 + if ($this->_networklink == false) {
  232 + $this->_xml = new SimpleXMLElement('<kml xmlns="http://earth.google.com/kml/2.0"><Document >' . $legenda . '</Document></kml>');
  233 + } else {
  234 + $this->_xml = new SimpleXMLElement('<kml xmlns="http://earth.google.com/kml/2.0"><Document ></Document></kml>');
  235 + }
  236 + // Prepare projection
  237 + $this->in_proj = ms_newProjectionObj($this->map_object->getProjection());
  238 + // Set projection to GOOGLE earth's projection
  239 + $this->out_proj = ms_newProjectionObj("init=epsg:4326");
  240 + // Set endpoint
  241 + // die($_SERVER['REQUEST_URI']);
  242 +
  243 + $protocolo = explode("/", $_SERVER['SERVER_PROTOCOL']);
  244 + $protocolo = strtolower($protocolo[0]);
  245 + $this->endpoint = $protocolo . '://' . $_SERVER['SERVER_NAME'] . ($_SERVER['SERVER_PORT'] ? ':' . $_SERVER['SERVER_PORT'] : '') . $_SERVER['PHP_SELF'];
  246 + // Process request
  247 + if (! $this->has_error()) {
  248 + $this->process_request();
  249 + }
  250 + if ($this->has_error()) {
  251 + $this->add_errors();
  252 + }
  253 + return $this->send_stream($this->get_kml());
  254 + }
  255 +
  256 + /**
  257 + * Set debug flag
  258 + *
  259 + * @param boolean $value
  260 + */
  261 + function set_debug($value)
  262 + {
  263 + $this->_debug = $value;
  264 + }
  265 +
  266 + /**
  267 + * Get all request parameters
  268 + */
  269 + function get_request()
  270 + {
  271 + $this->map = $this->load_parm('map');
  272 + $this->bbox = $this->load_parm('bbox');
  273 + $this->filter = $this->load_parm('filter');
  274 + $this->typename = $this->load_parm('typename');
  275 + $this->encoding = $this->load_parm('encoding', 'ISO-8859-1');
  276 + $this->request = $this->load_parm('request', 'kml');
  277 + if ($this->request == 'kmz') {
  278 + $this->_zipped = true;
  279 + }
  280 + if (! $this->map) {
  281 + $this->set_error('No mapfile specified');
  282 + }
  283 + }
  284 +
  285 + /**
  286 + * Apply filter
  287 + *
  288 + * @return array
  289 + */
  290 + function apply_filter(&$layer, &$filter)
  291 + {
  292 + if ($layer->connectiontype == MS_POSTGIS) {
  293 + if ($filter->PropertyIsEqualTo) {
  294 + $searchstring = '"' . $filter->PropertyIsEqualTo->PropertyName . ' = ' . '\'' . addslashes($filter->PropertyIsEqualTo->Literal) . '\'' . '"';
  295 + $searchfield = $filter->PropertyIsEqualTo->PropertyName;
  296 + } elseif ($filter->PropertyIsLike) {
  297 + $searchfield = $filter->PropertyIsLike->PropertyName;
  298 + $searchstring = '"' . $filter->PropertyIsLike->PropertyName . ' LIKE \'%' . addslashes($filter->PropertyIsLike->Literal) . '%\'' . '"';
  299 + }
  300 + } elseif ($layer->connectiontype == MS_SHAPEFILE || $layer->connectiontype == MS_OGR) {
  301 + if ($filter->PropertyIsEqualTo) {
  302 + $searchstring = $filter->PropertyIsEqualTo->Literal;
  303 + $searchfield = $filter->PropertyIsEqualTo->PropertyName;
  304 + } elseif ($filter->PropertyIsLike) {
  305 + $searchstring = $filter->PropertyIsLike->Literal;
  306 + $searchfield = $filter->PropertyIsLike->PropertyName;
  307 + }
  308 + }
  309 + return array(
  310 + $searchfield,
  311 + $searchstring
  312 + );
  313 + }
  314 +
  315 + /**
  316 + * Process request
  317 + */
  318 + function process_request()
  319 + {
  320 + // Get layer(s)
  321 + $layers = explode(',', $this->typename);
  322 + if ($this->_networklink) {
  323 + foreach ($layers as $layer) {
  324 + $this->add_networklink($layer);
  325 + }
  326 + } else {
  327 + foreach ($layers as $layer) {
  328 + // echo "Oi";exit;
  329 + $this->process_layer_request($layer);
  330 + }
  331 + }
  332 + }
  333 +
  334 + /**
  335 + * Add a networklink
  336 + */
  337 + function add_networklink(&$layer_name)
  338 + {
  339 + $nl = & $this->_xml->Document->addChild('NetworkLink');
  340 + $layer = @$this->map_object->getLayerByName($layer_name);
  341 + if (! $layer) {
  342 + $layer = $this->map_object->getlayer(0);
  343 + }
  344 + $nl->addChild('name', $this->get_layer_description($layer));
  345 + $nl->addChild('visibility', 0);
  346 + $link = & $nl->addChild('Link');
  347 + $link->addChild('href', $this->endpoint . '?map=' . $this->map . '&amp;typename=' . urlencode($layer_name) . '&amp;request=' . ($this->_zipped ? 'kmz' : 'kml'));
  348 + }
  349 +
  350 + /**
  351 + * Process a single layer
  352 + *
  353 + * @return boolean false on error
  354 + */
  355 + function process_layer_request(&$layer_name)
  356 + {
  357 + error_reporting(0);
  358 + $v = "5.0.0";
  359 + $vs = explode(" ", ms_GetVersion());
  360 + $cvs = count($vs);
  361 + for ($i = 0; $i < $cvs; ++ $i) {
  362 + if (trim(strtolower($vs[$i])) == "version") {
  363 + $v = $vs[$i + 1];
  364 + }
  365 + }
  366 + $v = explode(".", $v);
  367 + $versao = $v[0];
  368 +
  369 + $layer = @$this->map_object->getLayerByName($layer_name);
  370 + if (! $layer) {
  371 + $layer = $this->map_object->getlayer(0);
  372 + }
  373 + if (! $layer) {
  374 + $this->set_error('Nenhum layer com esse nome foi encontrado no mapfile ' . $layer_name, $layer_name);
  375 + return false;
  376 + }
  377 + // Add to layer list
  378 + $this->layers[$layer_name] = & $layer;
  379 + // Get custom template if any
  380 + $description_template = $layer->getMetadata('DESCRIPTION_TEMPLATE');
  381 + // Set on
  382 + $layer->set('status', MS_DEFAULT);
  383 + // Set kml title from layer description (default to layer name)
  384 + $layer_desc = $this->get_layer_description($layer);
  385 +
  386 + // Now switch raster layers
  387 + // var_dump($layer->type == MS_LAYER_RASTER);
  388 + if ($layer->type == MS_LAYER_RASTER) {
  389 + // Check if wms_onlineresource metadata is set
  390 + $wms_link = $this->map_object->getMetadata('wms_onlineresource');
  391 + if (! $wms_link) {
  392 + $wms_link = $this->map_object->getMetadata('ows_onlineresource');
  393 + }
  394 + if (! $wms_link) {
  395 + $this->set_error('No WMS server available for ' . $layer_name, $layer_name);
  396 + return false;
  397 + }
  398 + // Add parameters to OGC server call
  399 + // Fix &
  400 + $wms_link = preg_replace('/&/', '&amp;', $wms_link);
  401 + $wms_link .= 'VERSION=1.1.1&amp;REQUEST=GetMap&amp;SRS=EPSG:4618&amp;STYLES=&amp;FORMAT=image/png&amp;TRANSPARENT=TRUE&amp;';
  402 + // Link ok, create folder
  403 + // $folder =& $this->_xml->Document->addChild('GroundOverlay');
  404 + $folder = & $this->simplexml_addChild($this->_xml->Document, 'GroundOverlay');
  405 + // simplexml_addChild($parent, $name, $value='')
  406 + // $folder->addChild('description', $this->get_layer_description($layer));
  407 + $this->simplexml_addChild($folder, 'name', $layer_desc);
  408 +
  409 + // $folder->addChild('name', $layer_desc);
  410 + $this->add_wms_link($folder, $layer, $wms_link);
  411 + } else {
  412 + // Apply filter
  413 + if ($this->filter) {
  414 + // Try loading as XML
  415 + try {
  416 + $filter = @new SimpleXMLElement($this->filter);
  417 + list ($searchfield, $searchstring) = $this->apply_filter($layer, $filter);
  418 + if (! ($searchfield && $searchstring)) {
  419 + $this->set_error('Error parsing filter', $layer_name);
  420 + return false;
  421 + }
  422 + } catch (Exception $e) {
  423 + $this->set_error('Wrong XML filter', $layer_name);
  424 + $this->filter = null;
  425 + return false;
  426 + }
  427 + }
  428 + //error_log(implode(",",$this->postgis_mapa));
  429 + if ($layer->connectiontype == MS_POSTGIS) {
  430 + $layer->set("connection", $this->postgis_mapa[$layer->connection]);
  431 + }
  432 + // Get results
  433 + if (MS_SUCCESS == $layer->open()) {
  434 + // Search which column to use to identify the feature
  435 + $namecol = $layer->getMetadata("itens");
  436 + if ($namecol == "") {
  437 + $cols = array_values($layer->getItems());
  438 + $namecol = $cols[0];
  439 + } else {
  440 + $namecol = explode(",", $namecol);
  441 + $namecol = $namecol[0];
  442 + }
  443 + // Add classes
  444 + $folder = & $this->_xml->Document->addChild('Folder');
  445 +
  446 + $class_list = $this->parse_classes($layer, $folder, $namecol, $title_field, $description_template);
  447 +
  448 + // die(print_r($class_list, true));
  449 + $folder->addChild('description', $this->get_layer_description($layer));
  450 + $folder->addChild('name', $layer_desc);
  451 +
  452 + // print("$searchfield && $searchstring");
  453 + if (! isset($searchfield)) {
  454 + $searchfield = false;
  455 + }
  456 + if (! isset($searchstring)) {
  457 + $searchstring = false;
  458 + }
  459 +
  460 + if ($searchfield && $searchstring) {
  461 + if (@$layer->queryByAttributes($searchfield, $searchstring, MS_MULTIPLE) == MS_SUCCESS) {
  462 + $layer->open();
  463 + // var_dump($layer->getItems()); die();
  464 + for ($j = 0; $j < $layer->getNumResults(); $j ++) {
  465 + // get next shape row
  466 + if ($versao >= 6) {
  467 + $shape = $layer->getShape($layer->getResult($j));
  468 + } else {
  469 + $result = $layer->getResult($j);
  470 + $shape = $layer->getFeature($result->shapeindex, $result->tileindex);
  471 + }
  472 + $this->process_shape($layer, $shape, $class_list, $folder, $namecol);
  473 + // end for loop
  474 + }
  475 + } else {
  476 + $this->set_error('Query returned no data', $layer_name);
  477 + return false;
  478 + }
  479 + } else { // Get all shapes
  480 + $layer->set("template", "none.htm");
  481 + $layer->queryByrect($this->map_object->extent);
  482 + $layer->open();
  483 + $n = $layer->getNumResults();
  484 + for ($j = 0; $j < $n; $j ++) {
  485 + // get next shape row
  486 + if ($versao >= 6) {
  487 + $result = $layer->getResult($j);
  488 + $shape = $layer->getShape($result);
  489 + } else {
  490 + $result = $layer->getResult($j);
  491 + $shape = $layer->getFeature($result->shapeindex, $result->tileindex);
  492 + }
  493 + $shape->classindex = $result->classindex;
  494 + $this->process_shape($layer, $shape, $class_list, $folder, $namecol);
  495 + }
  496 + if ($n == 0) {
  497 + $this->set_error('QueryByRect returned no data', $layer_name);
  498 + return false;
  499 + }
  500 + }
  501 + $layer->close();
  502 + } else {
  503 + $this->set_error('Layer cannot be opened', $layer_name);
  504 + return false;
  505 + }
  506 + }
  507 + return true;
  508 + }
  509 +
  510 + /**
  511 + * Process the shape
  512 + */
  513 + function process_shape(&$layer, &$shape, &$class_list, &$folder, &$namecol)
  514 + {
  515 + $permite = $layer->getmetadata("permitekmz");
  516 + if (strtolower($permite) == "nao") {
  517 + return;
  518 + }
  519 + $itens = $layer->getmetadata("itens");
  520 + $itensdesc = $layer->getmetadata("itensdesc");
  521 + $shape->project($this->in_proj, $this->out_proj);
  522 + // Assign style
  523 + if ($layer->classitem) {
  524 + // $style_id = $this->get_shape_class($layer->classitem, $shape->values, $class_list);
  525 + }
  526 + if (! isset($style_id)) {
  527 + // Get first class
  528 + $class_keys = array_keys($class_list);
  529 + $indice = $shape->classindex;
  530 + $classe = $layer->getclass($indice);
  531 + $nome = $classe->name;
  532 + $style_id = preg_replace('/[^A-z0-9]/', '_', $layer->name . $nome);
  533 + }
  534 + // Add the feature
  535 + if (array_key_exists('folder', $class_list[$style_id])) {
  536 + $feature_folder = & $class_list[$style_id]['folder'];
  537 + } else {
  538 + // die('missing folder for ' . $style_id);
  539 + $feature_folder = & $folder;
  540 + }
  541 + if (! is_object($feature_folder)) {
  542 + $folder_name = $feature_folder;
  543 + $feature_folder = & $folder->addChild('Folder');
  544 + $feature_folder->addChild('name', $folder_name);
  545 + }
  546 + // Add style class
  547 + $style_url = & $this->add_style($layer, $feature_folder, $style_id, $class_list[$style_id], $namecol, $shape->values);
  548 +
  549 + $wkt = $shape->toWkt();
  550 + $description_template = $layer->getMetadata('DESCRIPTION_TEMPLATE'); // false;
  551 + if ($description_template == "") {
  552 + $description_template = false;
  553 + }
  554 + $placemark = & $this->add_feature($feature_folder, $wkt, $shape->values[$namecol], $shape->values, $description_template, $class_list[$style_id], $itens, $itensdesc);
  555 +
  556 + $placemark->addChild('styleUrl', '#' . $style_url);
  557 + }
  558 +
  559 + /**
  560 + * Add the feature to the result set
  561 + *
  562 + * @return reference to placemark object
  563 + */
  564 + function &add_feature(&$folder, &$wkt, $featurename, $attributes, $description_template, $style_data, $itens, $itensdesc)
  565 + {
  566 + $pm = $folder->addChild('Placemark');
  567 + $fname = mb_convert_encoding($featurename, "UTF-8", mb_detect_encoding($featurename, 'UTF-8, UTF-7, ASCII, ISO-8859-1'));
  568 + $pm->addChild('name', $fname);
  569 + $pm->addChild('description', $this->get_feature_description($fname, $attributes, $description_template, $itens, $itensdesc));
  570 + // Now parse the wkt
  571 + if (strpos($wkt, 'MULTILINESTRING') !== false) {
  572 + $this->add_multilinestring($wkt, $pm, $featurename, $style_data['icon']);
  573 + } elseif (strpos($wkt, 'LINESTRING') !== false) {
  574 + $this->add_linestring($wkt, $pm, $featurename, $style_data['icon']);
  575 + } elseif (strpos($wkt, 'POINT') !== false) {
  576 + $this->add_point($wkt, $pm, $featurename);
  577 + } elseif (strpos($wkt, 'MULTIPOLYGON') !== false) {
  578 + if (TREAT_POLY_AS_LINE) {
  579 + $ml = $pm->addChild('MultiGeometry');
  580 + foreach (split('\), \(', $wkt) as $line) {
  581 + $this->add_multilinestring($line, $ml, $featurename);
  582 + }
  583 + } else {
  584 + $this->add_multipolygon($wkt, $pm, $featurename);
  585 + }
  586 + } elseif (strpos($wkt, 'POLYGON') !== false) {
  587 + if (TREAT_POLY_AS_LINE) {
  588 + $this->add_multilinestring($wkt, $pm, $featurename);
  589 + } else {
  590 + $this->add_polygon($wkt, $pm, $featurename);
  591 + }
  592 + } else {
  593 + // Error?
  594 + }
  595 + return $pm;
  596 + }
  597 +
  598 + /**
  599 + * Add a linestring
  600 + */
  601 + function add_linestring(&$wkt, &$element, $featurename, $add_points)
  602 + {
  603 + preg_match('/(\d+[^\(\)]*\d)/', $wkt, $data);
  604 + $data = str_replace(', ', '#', $data[1]);
  605 + $data = str_replace(' ', ',', $data);
  606 + $data = str_replace('#', ' ', $data);
  607 + if ($add_points) {
  608 + preg_match('/^(\d+\.\d+,\d+\.\d+).*(\d+\.\d+,\d+\.\d+)$/', $data, $points);
  609 + if (count($points) == 3) {
  610 + $mg = $element->addChild('MultiGeometry');
  611 + $ls = $mg->addChild('LineString');
  612 + $pt1 = $mg->addChild('Point');
  613 + $pt1->addChild('coordinates', $points[1]);
  614 + $pt2 = $mg->addChild('Point');
  615 + $pt2->addChild('coordinates', $points[2]);
  616 + } else {
  617 + die('errore');
  618 + $ls = $element->addChild('LineString');
  619 + }
  620 + // print_r($points);die();
  621 + } else {
  622 + $ls = $element->addChild('LineString');
  623 + }
  624 + $ls->addChild('coordinates', $data);
  625 + }
  626 +
  627 + /**
  628 + * Add a multilinestring
  629 + */
  630 + function add_multilinestring(&$wkt, &$element, $featurename, $add_points)
  631 + {
  632 + $ml = $element->addChild('MultiGeometry');
  633 + foreach (split('\), \(', $wkt) as $line) {
  634 + $this->add_linestring($line, $ml, $featurename, $add_points);
  635 + }
  636 + }
  637 +
  638 + /**
  639 + * Add a point
  640 + */
  641 + function add_point(&$wkt, &$element, $featurename)
  642 + {
  643 + $pt = $element->addChild('Point');
  644 + /*
  645 + * preg_match('/(\d\.?\d+\s\d+\.?\d+)/', $wkt, $data);
  646 + * //var_dump($data);exit;
  647 + * $data = str_replace(' ', ',', $data[1]);
  648 + */
  649 + $data = str_replace("(", "", $wkt);
  650 + $data = str_replace(")", "", $data);
  651 + $data = str_replace("POINT", "", $data);
  652 + $data = str_replace(" ", ",", trim($data));
  653 + // echo $data;exit;
  654 + $pt->addChild('coordinates', $data);
  655 + }
  656 +
  657 + /**
  658 + * Add a polygon
  659 + */
  660 + function add_polygon(&$wkt, &$element, $featurename)
  661 + {
  662 + $ml = $element->addChild('Polygon');
  663 + foreach (split('\), \(', $wkt) as $line) {
  664 + preg_match('/(\d+[^\(\)]*\d)/', $line, $data);
  665 + $data = str_replace(', ', '#', $data[1]);
  666 + $data = str_replace(' ', ',', $data);
  667 + // Add 1 meter height
  668 + $data = str_replace('#', ',1 ', $data) . ',1';
  669 + $ml->addChild('tessellate', 1);
  670 + // $element->addChild('altitudeMode', 'relativeToGround');
  671 + $element->addChild('altitudeMode', 'clampToGround');
  672 + $ob = $ml->addChild('outerBoundaryIs');
  673 + $ls = $ob->addChild('LinearRing');
  674 + //a inclusao do - foi necessario pois o sinal nao e mantido no processo. Deve ter uma forma melhor de fazer isso
  675 + $ls->addChild('coordinates', "-".$data);
  676 + }
  677 + }
  678 +
  679 + /**
  680 + * Add a multipolygon
  681 + * fixme: untested, should take holes into account
  682 + */
  683 + function add_multipolygon(&$wkt, &$element, $featurename)
  684 + {
  685 + $ml = $element->addChild('MultiGeometry');
  686 + foreach (split('\), \(', $wkt) as $line) {
  687 + $this->add_polygon($line, $ml, $featurename);
  688 + }
  689 + }
  690 +
  691 + /**
  692 + * Get the feature description
  693 + */
  694 + function get_feature_description($featurename, $attributes, $description_template, $itens, $itensdesc)
  695 + {
  696 + // Compute hyperlink
  697 + // var_dump($attributes);exit;
  698 + // if($description_template != ""){return $description_template;}
  699 + $n = "";
  700 + if ($description_template != "") {
  701 + foreach ($attributes as $k => $val) {
  702 + $description_template = str_replace("%" . $k . "%", $attributes[$k], $description_template);
  703 + }
  704 + $n = $description_template;
  705 + } else {
  706 + if ($itens == "") {
  707 + foreach ($attributes as $k => $val) {
  708 + $n .= $k . " - " . $attributes[$k] . "\n";
  709 + }
  710 + } else {
  711 + $itens = explode(",", $itens);
  712 + $itensdesc = explode(",", $itensdesc);
  713 + for ($i = 0; $i < count($itens); $i ++) {
  714 + $n .= $itensdesc[$i] . " - " . $attributes[$itens[$i]] . "\n";
  715 + }
  716 + }
  717 + }
  718 + $description = mb_convert_encoding($n, "UTF-8", mb_detect_encoding($n, "UTF-8,ISO-8859-1"));
  719 + return $description;
  720 + }
  721 +
  722 + /**
  723 + * Parse classes
  724 + *
  725 + * @return array hash of 'style_id' => style_data)
  726 + */
  727 + function parse_classes(&$layer, &$folder, &$namecol, &$title_field, &$description_template)
  728 + {
  729 + $style_ar = array();
  730 + $numclasses = $layer->numclasses;
  731 + $versao = $this->versao();
  732 + $vi = $versao["inteiro"];
  733 + for ($i = 0; $i < $numclasses; $i ++) {
  734 + $class = $layer->getClass($i);
  735 + if ($vi >= 60200) {
  736 + if ($class->numlabels > 0)
  737 + $label = $class->getLabel(0);
  738 + } else {
  739 + $label = $class->label;
  740 + }
  741 + if ($label) {
  742 + $style['label_color'] = $label->color;
  743 + $style['label_size'] = $label->size;
  744 + }
  745 + // Get styles
  746 + for ($j = 0; $j < $class->numstyles; $j ++) {
  747 + $_style = $class->getStyle($j);
  748 + $style['color'] = $_style->color;
  749 + $style['outlinecolor'] = $_style->outlinecolor;
  750 + $style['width'] = $_style->size; // Lines
  751 + $style['backgroundcolor'] = $_style->backgroundcolor;
  752 + if ($layer->type == MS_LAYER_POINT)
  753 + $style['icon'] = $this->get_icon_url($layer, $class->name, $i);
  754 + $style['icon_width'] = $_style->size; // Points
  755 + }
  756 + $style['expression'] = $class->getExpressionString();
  757 + // Set description_template if any
  758 + $style['description_template'] = $description_template;
  759 + // Get icon for lines if any
  760 + if ($icon = $layer->getMetadata('KML_ADD_POINT')) {
  761 + $style['icon'] = $icon;
  762 + $style['icon_width'] = 32;
  763 + }
  764 + // Create style element
  765 + $style_id = preg_replace('/[^A-z0-9]/', '_', $layer->name . $class->name);
  766 + $this->add_style($layer, $folder, $style_id, $style, $namecol, $title_field);
  767 + // create folder if more than one class
  768 + if ($numclasses > 1) {
  769 + // $style['folder'] =& $class->name;
  770 + // $folder->addChild('Folder');
  771 + // $style['folder']->addChild('name', $class->name);
  772 + }
  773 + $style_ar[$style_id] = $style;
  774 + }
  775 + return $style_ar;
  776 + }
  777 +
  778 + /**
  779 + * Return a CSV list of all layer names in the mapfile
  780 + * fixme: filter out ANNOTATIONS and other "strange" layers
  781 + */
  782 + function get_layer_list()
  783 + {
  784 + $layer_list = array();
  785 + for ($i = 0; $i < $this->map_object->numlayers; $i ++) {
  786 + $layer = & $this->map_object->getLayer($i);
  787 + $kml_skip = $layer->getMetadata('KML_SKIP');
  788 + if (strtolower($kml_skip) !== 'true') {
  789 + $layer_list[] = $layer->name;
  790 + }
  791 + }
  792 + return join(',', $layer_list);
  793 + }
  794 +
  795 + /**
  796 + * Return the class for the shape, default to last class if not match
  797 + */
  798 + function get_shape_class(&$classitem, &$values, &$class_list)
  799 + {
  800 + // var_dump($class_list); die();
  801 + foreach ($class_list as $style_id => $style_data) {
  802 + if ($style_data['expression'] && preg_match($style_data['expression'], $values[$classitem])) {
  803 + // print "get_shape_class($classitem) ".$values[$classitem]." matches<br>";
  804 + return $style_id;
  805 + }
  806 + }
  807 + // print "get_shape_class($classitem) ".$values[$classitem]." no matches<br>";
  808 + return $style_id;
  809 + }
  810 +
  811 + /**
  812 + * Add the style
  813 + *
  814 + * @return the style URL
  815 + */
  816 + function add_style(&$layer, &$folder, $style_id, &$style_data)
  817 + {
  818 + // Calculare style URL
  819 + if ($style_data['description_template']) {
  820 + $this->style_counter ++;
  821 + $style_id .= '_' . $this->style_counter;
  822 + $balloon_data = $this->get_feature_description($attributes[$namecol], $attributes, $style_data['description_template']);
  823 + }
  824 +
  825 + // Check if the style already exists
  826 + $expr = '//*[@id=\'' . $style_id . '\']';
  827 + if ($folder->xpath($expr)) {
  828 + return $style_id;
  829 + }
  830 + $new_style = & $folder->addChild('Style');
  831 + $new_style['id'] = $style_id;
  832 + // Switch layer type
  833 + switch ($layer->type) {
  834 + case MS_LAYER_POINT:
  835 + $this->add_style_point($new_style, $style_data);
  836 + break;
  837 + case MS_LAYER_POLYGON:
  838 + $this->add_style_polygon($new_style, $style_data);
  839 + break;
  840 + case MS_LAYER_LINE:
  841 + $this->add_style_line($new_style, $style_data);
  842 + // Add KML_ADD_POINT icon
  843 + if ($style_data['icon']) {
  844 + $this->add_style_point($new_style, $style_data);
  845 + }
  846 + break;
  847 + }
  848 + return $style_id;
  849 + }
  850 +
  851 + /**
  852 + * Add style for lines
  853 + */
  854 + function add_style_line(&$new_style, &$style_data)
  855 + {
  856 + if ($style_data['outlinecolor']->red != - 1) {
  857 + $st = & $new_style->addChild('LineStyle');
  858 + $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['outlinecolor']->blue, $style_data['outlinecolor']->green, $style_data['outlinecolor']->red));
  859 + if ($width) {
  860 + $st->addChild('width', $width);
  861 + }
  862 + } elseif ($style_data['color']->red != - 1) {
  863 + $st = & $new_style->addChild('LineStyle');
  864 + $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['color']->blue, $style_data['color']->green, $style_data['color']->red));
  865 + if ($width) {
  866 + $st->addChild('width', $width);
  867 + }
  868 + }
  869 + }
  870 +
  871 + /**
  872 + * Add style for points
  873 + */
  874 + function add_style_point(&$new_style, &$style_data)
  875 + {
  876 + if ($style_data['icon']) {
  877 + $st = & $new_style->addChild('IconStyle');
  878 + if ($style_data['width'] && $style_data['icon_width'] != 32) {
  879 + /**
  880 + */
  881 + // $st->addChild('scale', $style_data['icon_width'] / 32);
  882 + $st->addChild('scale', 1);
  883 + } else {
  884 + $st->addChild('scale', 1);
  885 + }
  886 + $icon = & $st->addChild('Icon');
  887 + $icon->addChild('href', htmlentities($style_data['icon']));
  888 + }
  889 + $ls = & $new_style->addChild('LabelStyle');
  890 + $ls->addChild('scale', $style_data['label_size'] / 32);
  891 + // Add the balloon style if description_template is set
  892 + /*
  893 + * if($style_data['description_template']){
  894 + * $this->add_balloon_style($new_style, $balloon_data);
  895 + * }
  896 + */
  897 + // Label size and color
  898 + /*
  899 + * if($style_data['label_size'] || $style_data['label_color']){
  900 + * $ls =& $new_style->addChild('LabelStyle');
  901 + * if($style_data['label_size'] != -1 && $style_data['label_size'] != 32){
  902 + * $ls->addChild('scale', $style_data['label_size'] / 32);
  903 + * }
  904 + * if($style_data['label_color']->red != -1){
  905 + * $ls->addChild('color', sprintf('FF%02X%02X%02X', $style_data['label_color']->blue, $style_data['label_color']->green, $style_data['label_color']->red));
  906 + * }
  907 + * }
  908 + */
  909 + }
  910 +
  911 + /**
  912 + * Add style for polygons
  913 + */
  914 + function add_style_polygon(&$new_style, &$style_data)
  915 + {
  916 + // Get also outline styles
  917 + $this->add_style_line($new_style, $style_data);
  918 + $st = & $new_style->addChild('PolyStyle');
  919 + // die(print_r($backgroundcolor, true));
  920 + if ($style_data['color']->red != - 1) {
  921 + $st->addChild('color', sprintf('FF%02X%02X%02X', $style_data['color']->blue, $style_data['color']->green, $style_data['color']->red));
  922 + $st->addChild('fill', 1);
  923 + } else {
  924 + $st->addChild('fill', 0);
  925 + }
  926 + $st->addChild('outline', 1);
  927 + }
  928 +
  929 + /**
  930 + * Add a WMS raster link
  931 + */
  932 + function add_wms_link(&$folder, &$layer, &$link)
  933 + {
  934 + // Build up the KML response document.
  935 + // $icon =& $folder->addChild('Icon');
  936 + $icon = & $this->simplexml_addChild($folder, 'Icon');
  937 + // $icon->addChild('href', $link . 'layers=' . $layer->name);
  938 + $this->simplexml_addChild($icon, 'href', $link . 'layers=' . $layer->name);
  939 + // $icon->addChild('viewRefreshMode', 'onStop');
  940 + $this->simplexml_addChild($icon, 'viewRefreshMode', 'onStop');
  941 + // $llbox =& $folder->addChild('LatLonBox');
  942 + $llbox = & $this->simplexml_addChild($folder, 'LatLonBox');
  943 + $ext = $this->map_object->extent;
  944 + $ext->project($this->in_proj, $this->out_proj);
  945 + // $llbox->north = $ext->maxy;
  946 + $this->simplexml_addChild($llbox, 'north', $ext->maxy);
  947 + // $llbox->south = $ext->miny;
  948 + $this->simplexml_addChild($llbox, 'south', $ext->miny);
  949 + // $llbox->east = $ext->maxx;
  950 + $this->simplexml_addChild($llbox, 'east', $ext->maxx);
  951 + // $llbox->west = $ext->minx;
  952 + $this->simplexml_addChild($llbox, 'west', $ext->minx);
  953 + // Reset original projection
  954 + $ext->project($this->out_proj, $this->in_proj);
  955 + }
  956 +
  957 + /**
  958 + * Get the url for a point icon
  959 + */
  960 + function get_icon_url($layer, $classname, $classindex)
  961 + {
  962 + $classe = $layer->getclass($classindex);
  963 + $estilo = $classe->getstyle(0);
  964 + $url = "";
  965 + $imageObj = $classe->createLegendIcon(30, 30);
  966 + if ($imageObj) {
  967 + $url = $imageObj->saveWebImage();
  968 + $protocolo = explode("/", $_SERVER['SERVER_PROTOCOL']);
  969 + $url = strtolower($protocolo[0] . "://" . $_SERVER['HTTP_HOST']) . $url;
  970 + $nome = $imageObj->imagepath . basename($url);
  971 +
  972 + $img = imagecreatefrompng($nome);
  973 + $index = imagecolorexact($img, 255, 255, 255);
  974 + imagecolortransparent($img, $index);
  975 + imagepng($img, $nome);
  976 + }
  977 + return $url; // $this->endpoint . '?service=icon&map=' . $this->map . '&typename=' . urlencode($layer->name) . '&classname=' . urlencode($classname);
  978 + }
  979 +
  980 + /**
  981 + * Get the layer description
  982 + */
  983 + function get_layer_description(&$layer)
  984 + {
  985 + $description = $layer->getMetadata('DESCRIPTION');
  986 + if (! $description) {
  987 + $description = $layer->getMetadata('OWS_TITLE');
  988 + }
  989 + if (! $description) {
  990 + $description = $layer->getMetadata('WFS_TITLE');
  991 + }
  992 + if (! $description) {
  993 + $description = $layer->getMetadata('WMS_TITLE');
  994 + }
  995 + if (! $description) {
  996 + $description = $layer->getMetadata('TEMA');
  997 + }
  998 + if (! $description) {
  999 + $description = $layer->name;
  1000 + }
  1001 + $description = mb_convert_encoding($description, "UTF-8", mb_detect_encoding($description, "UTF-8,ISO-8859-1"));
  1002 + return $description;
  1003 + }
  1004 +
  1005 + /**
  1006 + * Add style for balloon
  1007 + *
  1008 + * @param
  1009 + * string style XML id
  1010 + * @param
  1011 + * string column name for title
  1012 + */
  1013 + function add_balloon_style(&$style, $balloon_data)
  1014 + {
  1015 + $balloon = & $style->addChild('BalloonStyle');
  1016 + $balloon->addChild('text', htmlentities($balloon_data));
  1017 + }
  1018 +
  1019 + /**
  1020 + * Get a request parameter
  1021 + *
  1022 + * @param string $name
  1023 + * @param string $default
  1024 + * parameter optional
  1025 + * @return string the parameter value or empty string if null
  1026 + */
  1027 + function load_parm($name, $default = '')
  1028 + {
  1029 + if (! isset($_REQUEST[$name]))
  1030 + return $default;
  1031 + $value = $_REQUEST[$name];
  1032 + if (get_magic_quotes_gpc() != 1)
  1033 + $value = addslashes($value);
  1034 + // $value = escapeshellcmd($value);
  1035 + return $value;
  1036 + }
  1037 +
  1038 + /**
  1039 + * Set error message
  1040 + *
  1041 + * @param string $message
  1042 + * @param string $layer
  1043 + * name
  1044 + */
  1045 + function set_error($message, $layer = 'Error')
  1046 + {
  1047 + $this->errors[$layer][] = $message;
  1048 + }
  1049 +
  1050 + /**
  1051 + * Load the map and create the map instance
  1052 + */
  1053 + function load_map()
  1054 + {
  1055 + if (! file_exists($this->map) && is_readable($this->map)) {
  1056 + $this->set_error('Cannot read mapfile ' . $this->map);
  1057 + } else {
  1058 + $protocolo = explode("/", $_SERVER['SERVER_PROTOCOL']);
  1059 + $servidor = strtolower($protocolo[0]) . "://" . $_SERVER['HTTP_HOST'];
  1060 + $temp = $this->map;
  1061 + if (file_exists(dirname(__FILE__) . "/../../../ms_configura.php")) {
  1062 + include (dirname(__FILE__) . "/../../../ms_configura.php");
  1063 + } else {
  1064 + include (dirname(__FILE__) . "/../../ms_configura.php");
  1065 + }
  1066 + $this->postgis_mapa = $postgis_mapa;
  1067 + if (! file_exists($this->map)) {
  1068 + $maptemp = ms_newMapObj($locaplic . "/temas/" . $this->map . ".map");
  1069 + // if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
  1070 + // {$this->map = $locaplic."/aplicmap/geral1windows.map";}
  1071 + // else
  1072 + // {$this->map = $locaplic."/aplicmap/geral1.map";}
  1073 +
  1074 + $versao = $this->versao();
  1075 + $versao = $versao["principal"];
  1076 + if (! isset($base) || $base == "") {
  1077 + if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
  1078 + $base = $locaplic . "/aplicmap/geral1windowsv" . $versao . ".map";
  1079 + } else {
  1080 + if ($base == "" && file_exists('/var/www/i3geo/aplicmap/geral1debianv' . $versao . '.map')) {
  1081 + $base = "/var/www/i3geo/aplicmap/geral1debianv" . $versao . ".map";
  1082 + }
  1083 + if ($base == "" && file_exists('/var/www/html/i3geo/aplicmap/geral1fedorav' . $versao . '.map')) {
  1084 + $base = "/var/www/html/i3geo/aplicmap/geral1fedorav" . $versao . ".map";
  1085 + }
  1086 + if ($base == "" && file_exists('/opt/www/html/i3geo/aplicmap/geral1fedorav' . $versao . '.map')) {
  1087 + $base = "/opt/www/html/i3geo/aplicmap/geral1v" . $versao . ".map";
  1088 + }
  1089 + if ($base == "") {
  1090 + $base = $locaplic . "/aplicmap/geral1v" . $versao . ".map";
  1091 + }
  1092 + }
  1093 + }
  1094 + $this->map = $base;
  1095 +
  1096 + $this->map_object = ms_newMapObj($this->map);
  1097 + if (! $this->_zipped) {
  1098 + $this->map_object->setmetadata('wms_onlineresource', $servidor . ":80/i3geo/ogc.php?tema=" . $temp . "&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");
  1099 + $this->map_object->setmetadata("ows_enable_request", "*");
  1100 + }
  1101 + $n = $this->map_object->numlayers;
  1102 + for ($i = 0; $i < $n; $i ++) {
  1103 + $l = $this->map_object->getlayer($i);
  1104 + $l->set("status", MS_DELETE);
  1105 + $l->set("name", "");
  1106 + }
  1107 + for ($i = 0; $i < ($maptemp->numlayers); $i ++) {
  1108 + $l = $maptemp->getlayer($i);
  1109 + $l->set("status", MS_DEFAULT);
  1110 + if (! $this->_zipped) {
  1111 + $l->set("type", MS_LAYER_RASTER);
  1112 + $l->setmetadata('wms_onlineresource', "../../ogc.php?tema=" . $temp . "&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");
  1113 + $l->setmetadata("ows_enable_request", "*");
  1114 + }
  1115 + ms_newLayerObj($this->map_object, $l);
  1116 + }
  1117 + } else {
  1118 + $this->map_object = ms_newMapObj($this->map);
  1119 + // $w = $this->map_object->web;
  1120 + // $w->set("template","none.htm");
  1121 +
  1122 + if (! $this->_zipped) {
  1123 + // $this->map_object->setmetadata('wms_onlineresource',$servidor.":80".$locmapserv."?map=".$temp."&width=1500&height=1500&");
  1124 + $this->map_object->setmetadata('wms_onlineresource', "../../ogc.php?tema=" . $temp . "&width=1500&height=1500&TRANSPARENT=true&FORMAT=image/png&");
  1125 + $this->map_object->setmetadata("ows_enable_request", "*");
  1126 + }
  1127 + $n = $this->map_object->numlayers;
  1128 + for ($i = 0; $i < $n; $i ++) {
  1129 + $l = $this->map_object->getlayer($i);
  1130 + $l->set("status", MS_DEFAULT);
  1131 + if (! $this->_zipped)
  1132 + $l->set("type", MS_LAYER_RASTER);
  1133 + // $l->setmetadata('wms_onlineresource',"../../ogc.php?tema=".$temp."&width=500&height=500&");
  1134 + // ms_newLayerObj($this->map_object, $l);
  1135 + }
  1136 + }
  1137 + if (! $this->map_object) {
  1138 + $this->set_error('Cannot load mapfile ' . $this->map);
  1139 + }
  1140 + }
  1141 + }
  1142 +
  1143 + /**
  1144 + * Test if has errors
  1145 + *
  1146 + * @return boolean
  1147 + */
  1148 + function has_error()
  1149 + {
  1150 + return count($this->errors) > 0;
  1151 + }
  1152 +
  1153 + /**
  1154 + * Add error messages to folders TAGS
  1155 + */
  1156 + function add_errors()
  1157 + {
  1158 + foreach ($this->errors as $layer => $errors) {
  1159 + $folder = & $this->_xml->Document->addChild('Folder');
  1160 + $folder->addChild('name', $layer);
  1161 + $folder->addChild('description', '<p>' . join("</p>\n<p>", $errors) . "</p>");
  1162 + }
  1163 + return $errorxml;
  1164 + }
  1165 +
  1166 + /**
  1167 + * Fetch XML and format it
  1168 + */
  1169 + function get_kml()
  1170 + {
  1171 + $doc = new DOMDocument('1.0');
  1172 + $doc->formatOutput = true;
  1173 + $domnode = dom_import_simplexml($this->_xml);
  1174 + $domnode = $doc->importNode($domnode, true);
  1175 + $domnode = $doc->appendChild($domnode);
  1176 + return $doc->saveXML();
  1177 + }
  1178 +
  1179 + /**
  1180 + * Send header
  1181 + */
  1182 + function send_header()
  1183 + {
  1184 + header('Content-Disposition: attachment; filename=kml.km' . ($this->_zipped ? 'z' : 'l'));
  1185 + header('Content-type: application/vnd.google-earth.km' . ($this->_zipped ? 'z' : 'l') . '+XML');
  1186 + }
  1187 +
  1188 + /**
  1189 + * Calculate cache file name
  1190 + */
  1191 + function get_cache_file_name()
  1192 + {
  1193 + // obtem o arquivo do metadata do layer se existir
  1194 + $layer = @$this->map_object->getlayerbyname($this->typename);
  1195 + if (! $layer) {
  1196 + $layer = $this->map_object->getlayer(0);
  1197 + }
  1198 + $k = $layer->getmetadata("arquivokmz");
  1199 + if ($k != "") {
  1200 + return $k;
  1201 + }
  1202 + if (file_exists(dirname(__FILE__) . "/../../../ms_configura.php")) {
  1203 + include (dirname(__FILE__) . "/../../../ms_configura.php");
  1204 + } else {
  1205 + include (dirname(__FILE__) . "/../../ms_configura.php");
  1206 + }
  1207 + return $dir_tmp . '/' . md5($_SERVER['QUERY_STRING']) . ($this->_zipped ? '.kmz' : '.kml');
  1208 + }
  1209 +
  1210 + /**
  1211 + * Send stream
  1212 + */
  1213 + function send_stream($data)
  1214 + {
  1215 + $this->send_header();
  1216 + // Compress data
  1217 +
  1218 + if ($this->_zipped) {
  1219 + include ("zip.class.php");
  1220 + $ziper = new zipfile();
  1221 + $ziper->addFile($data, 'doc.kml');
  1222 + $data = $ziper->file();
  1223 + }
  1224 +
  1225 + // Create cache if needed
  1226 + if (ENABLE_CACHE && count($this->layers) == 1) {
  1227 + // error_log( 'creating cache ' . $this->get_cache_file_name() );
  1228 + file_put_contents($this->get_cache_file_name(), $data);
  1229 + }
  1230 + print $data;
  1231 + exit();
  1232 + }
  1233 +
  1234 + // phpversion <= 5.1.2
  1235 + function simplexml_addChild($parent, $name, $value = '')
  1236 + {
  1237 + $new_child = new SimpleXMLElement("<$name>$value</$name>");
  1238 + $node1 = dom_import_simplexml($parent);
  1239 + $dom_sxe = dom_import_simplexml($new_child);
  1240 + $node2 = $node1->ownerDocument->importNode($dom_sxe, true);
  1241 + $node1->appendChild($node2);
  1242 + return simplexml_import_dom($node2);
  1243 + }
  1244 +
  1245 + function versao()
  1246 + {
  1247 + $v = "5.0.0";
  1248 + $vs = explode(" ", ms_GetVersion());
  1249 + $cvs = count($vs);
  1250 + for ($i = 0; $i < $cvs; ++ $i) {
  1251 + if (trim(strtolower($vs[$i])) == "version") {
  1252 + $v = $vs[$i + 1];
  1253 + }
  1254 + }
  1255 + $versao["completa"] = $v;
  1256 + $v = explode(".", $v);
  1257 + $versao["principal"] = $v[0];
  1258 + $versao["inteiro"] = ms_GetVersionInt();
  1259 + return $versao;
  1260 + }
1176 } 1261 }
1177 ?> 1262 ?>
pacotes/kmlmapserver/kmlservice.php
@@ -26,6 +26,7 @@ http://10.1.1.34:80/i3geo/pacotes/kmlmapserver/kmlservice.php?map=bioma&amp;typename @@ -26,6 +26,7 @@ http://10.1.1.34:80/i3geo/pacotes/kmlmapserver/kmlservice.php?map=bioma&amp;typename
26 */ 26 */
27 error_reporting(0); 27 error_reporting(0);
28 set_time_limit(0); 28 set_time_limit(0);
  29 +//error_log($_SERVER['QUERY_STRING']);
29 //para o caso do mapa ser o que esta em uso 30 //para o caso do mapa ser o que esta em uso
30 if(!empty($_GET["sid"])){ 31 if(!empty($_GET["sid"])){
31 session_name("i3GeoPHP"); 32 session_name("i3GeoPHP");