source: branches/prototype-v0/zoo-project/zoo-kernel/service_internal_ms.c @ 860

Last change on this file since 860 was 860, checked in by djay, 6 years ago

Add status_code key to the lenv section to support returning a specific HTTP error code from the service code. Fix callback invocation to support inputs arrays at step 1 and 2. Fix issue with cpu usage. Fix issue with mapserver publication when an input is optional. Fix callback invocation at step 7 in case the service has failed on the HPC side.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 45.0 KB
Line 
1/*
2 * Author : Gérald FENOY
3 *
4 *  Copyright 2010-2011 Fondazione Edmund Mach. All rights reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
24
25/**
26 * Cross platform definition of layerObj->class
27 */
28#ifndef WIN32
29#define CLASS class
30#else
31#define CLASS _class
32#endif
33#include "service_internal_ms.h"
34#include "server_internal.h"
35#include "response_print.h"
36
37/**
38 * Get a list of configuration keys having a corresponding mandatory ows_*.
39 * Map composed by a main.cfg maps name as key and the corresponding
40 * MapServer Mafile Metadata name to use
41 * see doc from here :
42 *  - http://mapserver.org/ogc/wms_server.html
43 *  - http://mapserver.org/ogc/wfs_server.html
44 *  - http://mapserver.org/ogc/wcs_server.html
45 *
46 * @return a new map containing a table linking a name of a configuration key
47 * to a corresponding mandatory ows_* keyword (ie. "fees" => "ows_fees").
48 */
49map* getCorrespondance(){
50  map* res=createMap("encoding","ows_encoding");
51  addToMap(res,"abstract","ows_abstract");
52  addToMap(res,"title","ows_title");
53  addToMap(res,"keywords","ows_keywordlist");
54  addToMap(res,"fees","ows_fees");
55  addToMap(res,"accessConstraints","ows_accessconstraints");
56  addToMap(res,"providerName","ows_attribution_title");
57  addToMap(res,"providerSite","ows_service_onlineresource");
58  addToMap(res,"individualName","ows_contactperson");
59  addToMap(res,"positionName","ows_contactposition");
60  addToMap(res,"providerName","ows_contactorganization");
61  addToMap(res,"role","ows_role");
62  addToMap(res,"addressType","ows_addresstype");
63  addToMap(res,"addressCity","ows_city");
64  addToMap(res,"addressDeliveryPoint","ows_address");
65  addToMap(res,"addressPostalCode","ows_postcode");
66  addToMap(res,"addressAdministrativeArea","ows_stateorprovince");
67  addToMap(res,"addressCountry","ows_country");
68  addToMap(res,"phoneVoice","ows_contactvoicetelephone");
69  addToMap(res,"phoneFacsimile","ows_contactfacsimiletelephone");
70  addToMap(res,"addressElectronicMailAddress","ows_contactelectronicmailaddress");
71  // Missing Madatory Informations
72  addToMap(res,"hoursOfService","ows_hoursofservice");
73  addToMap(res,"contactInstructions","ows_contactinstructions");
74  return res;
75}
76
77/**
78 * Return the current publish_id value
79 * @param elem and maps pointer on which the search occur
80 * @return the integer value of the publish_id field, if any, 0 otherwise
81 */ 
82int getPublishedId(maps* elem){
83  map* myIndex=getMap(elem->content,"published_id");
84  if(myIndex!=NULL){
85    return atoi(myIndex->value);
86  }
87  return 0;
88}
89/**
90 * Add width and height keys to an output maps containing the maximum width
91 * and height for displaying the full data extent.
92 * Restriction to an image having a size of 640x480 (width * height)
93 *
94 * @param output
95 * @param minx the lower left x coordinate
96 * @param miny the lower left y coordinate
97 * @param maxx the upper right x coordinate
98 * @param maxy the upper right y coordinate
99 */
100void setMapSize(maps* output,double minx,double miny,double maxx,double maxy){
101  int imyIndex=getPublishedId(output);
102  double maxWidth=640;
103  double maxHeight=480;
104  double deltaX=maxx-minx;
105  double deltaY=maxy-miny;
106  double qWidth;
107  qWidth=maxWidth/deltaX;
108  double qHeight;
109  qHeight=maxHeight/deltaY;
110#ifdef DEBUGMS
111  fprintf(stderr,"deltaX : %.15f \ndeltaY : %.15f\n",deltaX,deltaY);
112  fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",qWidth,qHeight);
113#endif
114
115  double width=deltaX*qWidth;
116  double height=height=deltaY*qWidth;
117  if(deltaX<deltaY){
118    width=deltaX*qHeight;
119    height=deltaY*qHeight;
120  }
121  if(height<0)
122    height=-height;
123  if(width<0)
124    width=-width;
125  char sWidth[1024];
126  char sHeight[1024];
127  sprintf(sWidth,"%.3f",width);
128  sprintf(sHeight,"%.3f",height);
129#ifdef DEBUGMS
130  fprintf(stderr,"sWidth : %.15f \nsHeight : %.15f\n",sWidth,sHeight);
131#endif
132  if(output!=NULL){
133    setMapArray(output->content,"width",imyIndex,sWidth);
134    setMapArray(output->content,"height",imyIndex,sHeight);
135  }
136}
137
138/**
139 * Add a Reference key to an output containing the WMFS/WFS/WCS request for
140 * accessing service result
141 *
142 * @param m the conf maps containing the main.cfg settings
143 * @param tmpI the specific output maps to add the Reference key
144 */
145void setReferenceUrl(maps* m,maps* tmpI){
146  map *msUrl=getMapFromMaps(m,"main","mapserverAddress");
147  if(msUrl==NULL){
148    errorException (m, _("Unable to find any mapserverAddress defined in the main.cfg file"),
149                    "InternalError", NULL);
150    exit(-1);
151  }
152  int imyIndex=getPublishedId(tmpI);
153  if(getMapArray(tmpI->content,"ref_wms_link",imyIndex)!=NULL)
154    return;
155  outputMapfile(m,tmpI);
156  int finalProto=-1;
157  map *msOgcVersion=getMapFromMaps(m,"main","msOgcVersion");
158  map *dataPath=getMapFromMaps(m,"main","dataPath");
159  map *sid=getMapFromMaps(m,"lenv","usid");
160  map* format=getMapArray(tmpI->content,"mimeType",imyIndex);
161  map* rformat=getMapArray(tmpI->content,"requestedMimeType",imyIndex);
162  map* width=getMapArray(tmpI->content,"width",imyIndex);
163  map* height=getMapArray(tmpI->content,"height",imyIndex);
164  map* protoMap=getMapArray(tmpI->content,"msOgc",imyIndex);
165  map* versionMap=getMapArray(tmpI->content,"msOgcVersion",imyIndex);
166  map* datatype=getMapArray(tmpI->content,"geodatatype",imyIndex);
167  char options[4][5][25]={
168    {"WMS","1.3.0","GetMap","layers=%s","wms_extent"},
169    {"WFS","1.1.0","GetFeature","typename=%s","wcs_extent"},
170    {"WCS","2.0.0","GetCoverage","coverageid=%s","wcs_extent"},
171    {"WCS","1.1.0","GetCoverage","coverage=%s","wcs_extent"}
172  };
173  if(datatype==NULL || strncmp(datatype->value,"other",5)==0){
174    map* minNb=getMap(tmpI->content,"minoccurs");
175    if(minNb==NULL || atoi(minNb->value)>=1){
176      setMapInMaps(m,"lenv","mapError","true");
177      setMapInMaps(m,"lenv","locator",tmpI->name);
178      setMapInMaps(m,"lenv","message",_("The ZOO-Kernel was able to retrieve the data but could not read it as geographic data."));
179      if(getMapFromMaps(m,"lenv","state")==NULL)
180        errorException (m, _("Unable to find any geographic data"), "WrongInputData", tmpI->name);
181    }
182    return;
183  }
184  int proto=0;
185  if(rformat==NULL){
186    rformat=getMapArray(tmpI->content,"mimeType",imyIndex);
187  }
188  if(strncasecmp(rformat->value,"text/xml",8)==0)
189    proto=1;
190  if(strncasecmp(rformat->value,"image/tiff",10)==0 ||
191     strncasecmp(rformat->value,"image/geotiff",10)==0)
192    proto=2;
193  int hasFormat=-1;
194  if(protoMap!=NULL){
195    hasFormat=1;
196    if(strncasecmp(protoMap->value,"WMS",3)==0){
197      proto=0;
198      rformat=createMap("value","image/png");
199    }
200    else{
201      if(strncasecmp(protoMap->value,"WFS",3)==0){
202        proto=1;
203        rformat=createMap("value","text/xml");
204      }
205      else {
206        proto=2;
207        rformat=createMap("value","image/tiff");
208      }
209    }
210  }
211  char *protoVersion=options[proto][1];
212  if(proto==1){
213    if(msOgcVersion!=NULL)
214      protoVersion=msOgcVersion->value;
215    if(versionMap!=NULL)
216      protoVersion=versionMap->value;
217  }
218
219
220  map* extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
221  map* crs=getMapArray(tmpI->content,"crs",imyIndex);
222  int hasCRS=1;
223  if(crs==NULL){
224    crs=getMapFromMaps(m,"main","crs");
225    if(crs==NULL){
226      crs=createMap("crs","epsg:4326");
227      hasCRS=0;
228    }
229  }
230  char layers[128];
231  sprintf(layers,options[proto][3],tmpI->name);
232
233  if(format==NULL || width==NULL || height==NULL || extent==NULL){
234    char tmpStr[1024];
235    sprintf(tmpStr,_("Unable to create the mapfile for %s because of missing values."),tmpI->name);
236    errorException (m, tmpStr,
237                    "InternalError", NULL);
238    exit(-1);
239    return;
240  }
241
242  if(proto==0){
243    hasFormat=1;
244    rformat=createMap("mimeType","image/png");
245  }else{
246    if(proto==1){
247      rformat=createMap("mimeType","text/xml");
248      hasFormat=1;
249    }
250    else
251      if(proto==2){
252        rformat=createMap("mimeType","image/tiff");
253        hasFormat=1;
254        finalProto=1;
255      }
256  }
257 
258  char* webService_url=(char*)malloc((strlen(msUrl->value)+strlen(rformat->value)+strlen(tmpI->name)+strlen(width->value)+strlen(height->value)+strlen(extent->value)+256)*sizeof(char));
259
260
261  if(proto>0){
262    if(proto==2)
263      finalProto=1;
264    sprintf(webService_url,
265            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
266            msUrl->value,
267            dataPath->value,
268            tmpI->name,
269            imyIndex,
270            sid->value,
271            options[proto][2],
272            options[proto][0],
273            protoVersion,
274            layers,
275            rformat->value,
276            extent->value,
277            crs->value
278            );
279    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
280      setMapArray(tmpI->content,"ref_wcs_link",imyIndex,webService_url);
281    }
282    else{
283      setMapArray(tmpI->content,"ref_wfs_link",imyIndex,webService_url);
284    }
285    proto=0;
286    freeMap(&rformat);
287    free(rformat);
288    rformat=createMap("mimeType","image/png");
289  }
290  else{
291    sprintf(webService_url,
292            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
293            msUrl->value,
294            dataPath->value,
295            tmpI->name,
296            imyIndex,
297            sid->value,
298            options[proto][2],
299            options[proto][0],
300            protoVersion,
301            layers,
302            width->value,
303            height->value,
304            rformat->value,
305            extent->value,
306            crs->value
307            );
308    setMapArray(tmpI->content,"ref_wms_link",imyIndex,webService_url);
309    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
310      proto=2;
311      freeMap(&rformat);
312      free(rformat);
313      rformat=createMap("mimeType","image/tiff");
314    }
315    else{
316      proto=1;
317      freeMap(&rformat);
318      free(rformat);
319      rformat=createMap("mimeType","text/xml");
320    }
321  }
322  setMapArray(tmpI->content,"Reference",imyIndex,webService_url);
323  memset(layers,0,128);
324  sprintf(layers,options[proto][3],tmpI->name);
325  protoVersion=options[proto][1];
326  extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
327  memset(webService_url,0,strlen(webService_url));
328  if(proto>0){
329    if(proto==2)
330      finalProto=1;
331    sprintf(webService_url,
332            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
333            msUrl->value,
334            dataPath->value,
335            tmpI->name,
336            imyIndex,
337            sid->value,
338            options[proto][2],
339            options[proto][0],
340            protoVersion,
341            layers,
342            rformat->value,
343            extent->value,
344            crs->value
345            );
346    if(datatype!=NULL && strncasecmp(datatype->value,"raster",6)==0){
347      setMapArray(tmpI->content,"ref_wcs_link",imyIndex,webService_url);
348    }
349    else{
350      setMapArray(tmpI->content,"ref_wfs_link",imyIndex,webService_url);
351    }
352  }else{
353    sprintf(webService_url,
354            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
355            msUrl->value,
356            dataPath->value,
357            tmpI->name,
358            imyIndex,
359            sid->value,
360            options[proto][2],
361            options[proto][0],
362            protoVersion,
363            layers,
364            width->value,
365            height->value,
366            rformat->value,
367            extent->value,
368            crs->value
369            );
370    setMapArray(tmpI->content,"ref_wms_link",imyIndex,webService_url);
371  }
372  if(finalProto>0){
373    proto=3;
374    memset(layers,0,128);
375    sprintf(layers,options[proto][3],tmpI->name);
376    protoVersion=options[proto][1];
377    extent=getMapArray(tmpI->content,options[proto][4],imyIndex);
378    memset(webService_url,0,strlen(webService_url));
379    freeMap(&rformat);
380    free(rformat);
381    rformat=createMap("value","image/tiff");
382    sprintf(webService_url,
383            "%s?map=%s/%s_%d_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
384            msUrl->value,
385            dataPath->value,
386            tmpI->name,
387            imyIndex,
388            sid->value,
389            options[proto][2],
390            options[proto][0],
391            protoVersion,
392            layers,
393            rformat->value,
394            extent->value,
395            crs->value
396            );
397    setMapArray(tmpI->content,"ref_wcs_preview_link",imyIndex,webService_url);
398  }
399  if(hasCRS==0){
400    freeMap(&crs);
401    free(crs);
402  }
403  freeMap(&rformat);
404  free(rformat);
405  free(webService_url);
406}
407
408/**
409 * Set projection for a layer in a MAPFILE using Authority Code and Name if
410 * available or fallback to proj4 definition if available or fallback to
411 * default EPSG:4326
412 *
413 * @param output the output maps
414 * @param m the opened mapObj
415 * @param myLayer the layerObj
416 * @param pszProjection a char* containing the SRS definition in WKT format
417 */
418void setSrsInformations(maps* output,mapObj* m,layerObj* myLayer,
419                        char* pszProjection){
420  OGRSpatialReferenceH  hSRS;
421  map* msSrs=NULL;
422  int imyIndex=getPublishedId(output);
423  hSRS = OSRNewSpatialReference(NULL);
424  if( pszProjection!=NULL && strlen(pszProjection)>1){
425    if(OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ){
426      char *proj4Str=NULL;
427      if(OSRGetAuthorityName(hSRS,NULL)!=NULL && 
428         OSRGetAuthorityCode(hSRS,NULL)!=NULL){
429        char tmpSrs[20];
430        sprintf(tmpSrs,"%s:%s",
431                OSRGetAuthorityName(hSRS,NULL),OSRGetAuthorityCode(hSRS,NULL));
432        msLoadProjectionStringEPSG(&m->projection,tmpSrs);
433        msLoadProjectionStringEPSG(&myLayer->projection,tmpSrs);
434       
435        char tmpSrss[256];
436        sprintf(tmpSrss,"EPSG:4326 EPSG:900913 EPSG:3857 %s",tmpSrs);
437       
438        msInsertHashTable(&(m->web.metadata), "ows_srs", tmpSrss);
439        msInsertHashTable(&(myLayer->metadata), "ows_srs", tmpSrss);
440       
441#ifdef DEBUGMS
442        fprintf(stderr,"isGeo %b\n\n",OSRIsGeographic(hSRS)==TRUE);
443#endif
444        if(output!=NULL){
445          if(OSRIsGeographic(hSRS)==TRUE)
446            setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
447          else
448            setMapArray(output->content,"crs_isGeographic",imyIndex,"false");
449          setMapArray(output->content,"crs",imyIndex,tmpSrs);
450        }
451      }
452      else{
453        OSRExportToProj4(hSRS,&proj4Str);
454        if(proj4Str!=NULL && strlen(proj4Str)>0){
455#ifdef DEBUGMS
456          fprintf(stderr,"PROJ (%s)\n",proj4Str);
457#endif
458          msLoadProjectionString(&(m->projection),proj4Str);
459          msLoadProjectionString(&(myLayer->projection),proj4Str);
460          if(output!=NULL){ 
461            if(OSRIsGeographic(hSRS)==TRUE)
462              setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
463            else
464              setMapArray(output->content,"crs_isGeographic",imyIndex,"false");
465          }
466          free(proj4Str);
467        }
468        else{
469          msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
470          msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
471          if(output!=NULL){
472            setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
473          }
474        }
475        if(output!=NULL){
476          setMapArray(output->content,"crs",imyIndex,"EPSG:4326");
477          setMapArray(output->content,"real_extent",imyIndex,"true");
478        }
479        msInsertHashTable(&(m->web.metadata),"ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
480        msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913 EPSG:3857");
481      }
482    }
483  }
484  else{
485    if(output!=NULL){
486      msSrs=getMapArray(output->content,"msSrs",imyIndex);
487    }
488    if(msSrs!=NULL){
489      msLoadProjectionStringEPSG(&m->projection,msSrs->value);
490      msLoadProjectionStringEPSG(&myLayer->projection,msSrs->value);
491      char tmpSrs[128];
492      sprintf(tmpSrs,"%s EPSG:4326 EPSG:900913 EPSG:3857",msSrs->value);
493      msInsertHashTable(&(m->web.metadata),"ows_srs",tmpSrs);
494      msInsertHashTable(&(myLayer->metadata),"ows_srs",tmpSrs);
495    }else{
496      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
497      msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
498      msInsertHashTable(&(m->web.metadata),"ows_srs","EPSG:4326 EPSG:900913 EPSG:3857");
499      msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913 EPSG:3857");
500    }
501    if(output!=NULL){
502      setMapArray(output->content,"crs",imyIndex,msSrs->value);
503      setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
504    }
505  }
506
507  OSRDestroySpatialReference( hSRS );
508}
509
510/**
511 * Set the MAPFILE extent, the the ows_extent for the layer, add wms_extent and
512 * wfs_extent to the output maps and call setMapSize.
513 *
514 * @param output the specific output
515 * @param m the mapObj
516 * @param myLayer the layerObj
517 * @param minX the lower left x coordinate
518 * @param minY the lower left y coordinate
519 * @param maxX the upper right x coordinate
520 * @param maxY the upper right y coordinate
521 * @see setMapSize
522 */
523void setMsExtent(maps* output,mapObj* m,layerObj* myLayer,
524                 double minX,double minY,double maxX,double maxY){
525  int imyIndex=getPublishedId(output);
526  msMapSetExtent(m,minX,minY,maxX,maxY);
527#ifdef DEBUGMS
528  fprintf(stderr,"Extent %.15f %.15f %.15f %.15f\n",minX,minY,maxX,maxY);
529#endif
530  char tmpExtent[1024];
531  sprintf(tmpExtent,"%.15f %.15f %.15f %.15f",minX,minY,maxX,maxY);
532#ifdef DEBUGMS
533  fprintf(stderr,"Extent %s\n",tmpExtent);
534#endif
535  msInsertHashTable(&(myLayer->metadata), "ows_extent", tmpExtent);
536 
537  if(output!=NULL){
538    map* test=getMapArray(output->content,"real_extent",imyIndex);
539    pointObj min, max;
540    projectionObj tempSrs;
541    min.x = m->extent.minx;
542    min.y = m->extent.miny;
543    max.x = m->extent.maxx;
544    max.y = m->extent.maxy;
545    char tmpSrsStr[1024];
546    msInitProjection(&tempSrs);
547    msLoadProjectionStringEPSG(&tempSrs,"EPSG:4326");
548
549    msProjectPoint(&(myLayer->projection),&tempSrs,&min);
550    msProjectPoint(&myLayer->projection,&tempSrs,&max);
551 
552    if(test!=NULL){
553      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.y,min.x,max.y,max.x);
554      map* isGeo=getMapArray(output->content,"crs_isGeographic",imyIndex);
555#ifdef DEBUGMS
556      fprintf(stderr,"isGeo = %s\n",isGeo->value);
557#endif
558      if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0){
559        sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.y,min.x,max.y,max.x);
560        setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
561        sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
562      }else{
563        sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
564        setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
565      }
566      setMapArray(output->content,"wms_extent",imyIndex,tmpExtent);
567      sprintf(tmpSrsStr,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
568      setMapArray(output->content,"wcs_extent",imyIndex,tmpExtent);
569    }else{
570      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
571      setMapArray(output->content,"wgs84_extent",imyIndex,tmpExtent);
572      sprintf(tmpExtent,"%f,%f,%f,%f",minX, minY, maxX, maxY);
573      map* isGeo=getMapArray(output->content,"crs_isGeographic",imyIndex);
574      if(isGeo!=NULL){
575#ifdef DEBUGMS
576        fprintf(stderr,"isGeo = %s\n",isGeo->value);
577#endif
578        if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
579          sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
580      }
581      setMapArray(output->content,"wms_extent",imyIndex,tmpExtent); 
582      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",minX,minY,maxX,maxY);
583      setMapArray(output->content,"wcs_extent",imyIndex,tmpExtent);
584    }
585  }
586
587  setMapSize(output,minX,minY,maxX,maxY);
588}
589
590/**
591 * Try to open a vector output and define the corresponding layer in the MAPFILE
592 *
593 * @param conf the conf maps containing the main.cfg settings
594 * @param output the specific output maps
595 * @param m the mapObj
596 */
597int tryOgr(maps* conf,maps* output,mapObj* m){
598  int imyIndex=getPublishedId(output);
599  map* tmpMap=getMapArray(output->content,"storage",imyIndex);
600  char *pszDataSource=tmpMap->value;
601
602  /**
603   * Try to open the DataSource using OGR
604   */
605  OGRRegisterAll();
606  /**
607   * Try to load the file as ZIP
608   *
609  OGRDataSourceH poDS1 = NULL;
610  OGRSFDriverH *poDriver1 = NULL;
611  char *dsName=(char*)malloc((8+strlen(pszDataSource)+1)*sizeof(char));
612  char *odsName=zStrdup(pszDataSource);
613  char *sdsName=zStrdup(pszDataSource);
614  char *demo=".data";
615  sdsName[strlen(sdsName)-(strlen(demo)-1)]='d';
616  sdsName[strlen(sdsName)-(strlen(demo)-2)]='i';
617  sdsName[strlen(sdsName)-(strlen(demo)-3)]='r';
618  sdsName[strlen(sdsName)-(strlen(demo)-4)]=0;
619
620  odsName[strlen(odsName)-(strlen(demo)-1)]='z';
621  odsName[strlen(odsName)-(strlen(demo)-2)]='i';
622  odsName[strlen(odsName)-(strlen(demo)-3)]='p';
623  odsName[strlen(odsName)-(strlen(demo)-4)]=0;
624  sprintf(dsName,"/vsizip/%s",odsName);
625
626#ifdef DEBUGMS
627  fprintf(stderr,"Try loading %s, %s, %s\n",dsName,odsName,dsName);
628#endif
629
630  FILE* file = fopen(pszDataSource, "rb");
631  FILE* fileZ = fopen(odsName, "wb");
632  free(odsName);
633  fseek(file, 0, SEEK_END);
634  unsigned long fileLen=ftell(file);
635  fseek(file, 0, SEEK_SET);
636  char *buffer=(char *)malloc(fileLen+1);
637  fread(buffer, fileLen, 1, file);
638  fwrite(buffer,fileLen, 1, fileZ);
639  fclose(file);
640  fclose(fileZ);
641  free(buffer);
642#ifdef DEBUGMS
643  fprintf(stderr,"Try loading %s",dsName);
644#endif
645  poDS1 = OGROpen( dsName, FALSE, poDriver1 );
646  if( poDS1 == NULL ){
647    fprintf(stderr,"Unable to access the DataSource as ZIP File\n");
648    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
649    fprintf(stderr,"Remove ZIP File!\n");
650    unlink(odsName);
651    //OGR_DS_Destroy(poDS1);
652  }else{
653#ifdef DEBUGMS
654    fprintf(stderr,"The DataSource is a  ZIP File\n");
655#endif
656    char** demo=VSIReadDir(dsName);
657    int i=0;
658    zMkdir(sdsName
659#ifndef WIN32
660                ,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
661#endif
662                );
663    while(demo[i]!=NULL){
664#ifdef DEBUGMS
665      fprintf(stderr,"ZIP File content : %s\n",demo[i]);
666#endif
667      char *tmpDs=(char*)malloc((strlen(dsName)+strlen(demo[i])+2)*sizeof(char));
668      sprintf(tmpDs,"%s/%s",dsName,demo[i]);
669      fprintf(stderr,"read : %s\n",tmpDs);
670     
671      VSILFILE* vsif=VSIFOpenL(tmpDs,"rb");
672#ifdef DEBUGMS
673      fprintf(stderr,"open : %s\n",tmpDs);
674#endif
675      VSIFSeekL(vsif,0,SEEK_END);
676      vsi_l_offset size=VSIFTellL(vsif);
677#ifdef DEBUGMS
678      fprintf(stderr,"size : %d\n",size);
679#endif
680      VSIFSeekL(vsif,0,SEEK_SET);
681      char *vsifcontent=(char*) malloc(((int)size+1)*sizeof(char));
682      VSIFReadL(vsifcontent,1,(size_t)size,vsif);
683      char *fpath=(char*) malloc((strlen(sdsName)+strlen(demo[1])+2)*sizeof(char));
684      sprintf(fpath,"%s/%s",sdsName,demo[i]);
685      int f=zOpen(fpath,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
686      zWrite(f,vsifcontent,(int)size);
687      close(f);
688      chmod(fpath,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH);
689      char* tmpP=strstr(fpath,".shp");
690      if(tmpP==NULL)
691        tmpP=strstr(fpath,".SHP");
692      if(tmpP!=NULL){
693#ifdef DEBUGMS
694        fprintf(stderr,"*** DEBUG %s\n",strstr(tmpP,"."));
695#endif
696        if( strcmp(tmpP,".shp")==0 || strcmp(tmpP,".SHP")==0 ){
697          tmpMap=getMap(output->content,"storage");
698          free(tmpMap->value);
699          tmpMap->value=(char*) malloc((strlen(fpath)+1)*sizeof(char));
700          sprintf(tmpMap->value,"%s",fpath);
701          pszDataSource=tmpMap->value;
702#ifdef DEBUGMS
703          fprintf(stderr,"*** DEBUG %s\n",pszDataSource);
704#endif
705        }
706      }
707      VSIFCloseL(vsif);
708      i++;
709    }
710    OGR_DS_Destroy(poDS1);
711    }
712  free(sdsName);
713  free(dsName);*/
714 
715  OGRDataSourceH poDS = NULL;
716  OGRSFDriverH *poDriver = NULL;
717  poDS = OGROpen( pszDataSource, FALSE, poDriver );
718  if( poDS == NULL ){
719#ifdef DEBUGMS
720    fprintf(stderr,"Unable to access the DataSource %s\n",pszDataSource);
721#endif
722    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
723#ifdef DEBUGMS
724    fprintf(stderr,"Unable to access the DataSource, exit! \n"); 
725#endif
726    return -1;
727  }
728
729  setMapArray(output->content,"geodatatype",imyIndex,"vector");
730  int iLayer = 0;
731  for( iLayer=0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++ ){
732    OGRLayerH poLayer = OGR_DS_GetLayer(poDS,iLayer);
733
734    if( poLayer == NULL ){
735#ifdef DEBUGMS
736      fprintf(stderr,"Unable to access the DataSource Layer \n");
737#endif
738      setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
739      return -1;
740    }
741
742    /**
743     * Add a new layer set name, data
744     */
745    if(msGrowMapLayers(m)==NULL){
746      return -1;
747    }
748    if(initLayer((m->layers[m->numlayers]), m) == -1){
749      return -1;
750    }
751
752    layerObj* myLayer=m->layers[m->numlayers];
753#ifdef DEBUGMS
754    dumpMaps(output);
755#endif
756    myLayer->name = zStrdup(output->name);
757    myLayer->tileitem=NULL;
758    myLayer->data = zStrdup(OGR_L_GetName(poLayer));
759    myLayer->connection = zStrdup(pszDataSource);
760    myLayer->index = m->numlayers;
761    myLayer->dump = MS_TRUE;
762    myLayer->status = MS_ON;
763    msConnectLayer(myLayer,MS_OGR,pszDataSource);
764
765    addIntToMapArray(output->content,"nb_features",imyIndex,OGR_L_GetFeatureCount(poLayer,1));
766
767    /**
768     * Detect the Geometry Type or use Polygon
769     */
770    if(OGR_L_GetGeomType(poLayer) != wkbUnknown){
771      switch(OGR_L_GetGeomType(poLayer)){
772      case wkbPoint:
773      case wkbMultiPoint:
774      case wkbPoint25D:
775      case wkbMultiPoint25D:
776#ifdef DEBUGMS
777        fprintf(stderr,"POINT DataSource Layer \n");
778#endif
779        myLayer->type = MS_LAYER_POINT;
780        break;
781      case wkbLineString :
782      case wkbMultiLineString :
783      case wkbLineString25D:
784      case wkbMultiLineString25D:
785#ifdef DEBUGMS
786        fprintf(stderr,"LINE DataSource Layer \n");
787#endif
788        myLayer->type = MS_LAYER_LINE;
789        break;
790      case wkbPolygon:
791      case wkbMultiPolygon:
792      case wkbPolygon25D:
793      case wkbMultiPolygon25D:
794#ifdef DEBUGMS
795        fprintf(stderr,"POLYGON DataSource Layer \n");
796#endif
797        myLayer->type = MS_LAYER_POLYGON;
798        break;
799      default:
800        myLayer->type = MS_LAYER_POLYGON;
801        break;
802      }
803    }else
804      myLayer->type = MS_LAYER_POLYGON;
805
806    /**
807     * Detect spatial reference or use WGS84
808     */
809    OGRSpatialReferenceH srs=OGR_L_GetSpatialRef(poLayer);
810    if(srs!=NULL){
811      char *wkt=NULL;
812      OSRExportToWkt(srs,&wkt);
813      setSrsInformations(output,m,myLayer,wkt);
814      free(wkt);
815    }
816    else{
817      setMapArray(output->content,"crs",imyIndex,"EPSG:4326");
818      setMapArray(output->content,"crs_isGeographic",imyIndex,"true");
819      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
820      msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
821      msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913 EPSG:3857");
822    }
823
824    OGREnvelope oExt;
825    if (OGR_L_GetExtent(poLayer,&oExt, TRUE) == OGRERR_NONE){
826      setMsExtent(output,m,myLayer,oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
827      char extent[1024];
828      memset(&extent,0,1024);
829      sprintf(extent,"%d,%d,%d,%d",oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
830      setMapArray(output->content,"boundingbox",imyIndex,extent);
831    }
832 
833    /**
834     * Detect the FID column or use the first attribute field as FID
835     */
836    char *fid=(char*)OGR_L_GetFIDColumn(poLayer);
837    if(strlen(fid)==0){
838      OGRFeatureDefnH def=OGR_L_GetLayerDefn(poLayer);
839      int fIndex=0;
840      for(fIndex=0;fIndex<OGR_FD_GetFieldCount(def);fIndex++){
841        OGRFieldDefnH fdef=OGR_FD_GetFieldDefn(def,fIndex);
842        fid=(char*)OGR_Fld_GetNameRef(fdef);
843        break;
844      }
845    }
846    msInsertHashTable(&(myLayer->metadata), "gml_featureid", fid);
847    msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
848    msInsertHashTable(&(myLayer->metadata), "ows_name", output->name);
849    map* tmpMap=getMapArray(output->content,"title",imyIndex);
850    if(tmpMap!=NULL)
851      msInsertHashTable(&(myLayer->metadata), "ows_title", tmpMap->value);
852    else
853      msInsertHashTable(&(myLayer->metadata), "ows_title", "Default Title");
854   
855    if(msGrowLayerClasses(myLayer) == NULL)
856      return -1;
857    if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
858      return -1;
859    if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
860      return -1;
861    if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
862      return -1;
863    /**
864     * Apply msStyle else fallback to the default style
865     */
866    tmpMap=getMap(output->content,"msStyle");
867    if(tmpMap!=NULL)
868      msUpdateStyleFromString(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles],tmpMap->value,0);
869    else{
870      /**
871       * Set style
872       */
873      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=125;
874      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=125;
875      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=255;
876      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
877      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
878      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
879     
880      /**
881       * Set specific style depending on type
882       */
883      if(myLayer->type == MS_LAYER_POLYGON)
884        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
885      if(myLayer->type == MS_LAYER_LINE){
886        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
887        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
888      }
889      if(myLayer->type == MS_LAYER_POINT){
890        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->symbol=1;
891        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->size=15;
892      }
893     
894    }
895    myLayer->CLASS[myLayer->numclasses]->numstyles++;
896    myLayer->numclasses++;
897   
898    m->layerorder[m->numlayers] = m->numlayers;
899    m->numlayers++;
900
901  }
902
903  OGR_DS_Destroy(poDS);
904  //OGRCleanupAll();
905
906  return 1;
907}
908
909/**
910 * Try to open a raster output and define the corresponding layer in the MAPFILE
911 *
912 * @param conf the conf maps containing the main.cfg settings
913 * @param output the specific output maps
914 * @param m the mapObj
915 */
916int tryGdal(maps* conf,maps* output,mapObj* m){
917  int imyIndex=getPublishedId(output);
918  map* tmpMap=getMapArray(output->content,"storage",imyIndex);
919  char *pszFilename=tmpMap->value;
920  GDALDatasetH hDataset;
921  GDALRasterBandH hBand;
922  double adfGeoTransform[6];
923  int i, iBand;
924 
925  /**
926   * Try to open the DataSource using GDAL
927   */
928  GDALAllRegister();
929  hDataset = GDALOpen( pszFilename, GA_Update );
930  if( hDataset == NULL ){
931#ifdef DEBUGMS
932    fprintf(stderr,"Unable to access the DataSource %s \n",pszFilename);
933#endif
934    setMapArray(output->content,"geodatatype",imyIndex,"other");
935    setMapInMaps(conf,"lenv","message","gdalinfo failed - unable to open");
936    GDALDestroyDriverManager();
937    return -1;
938  }
939#ifdef DEBUGMS
940  fprintf(stderr,"Accessing the DataSource %s %d\n",pszFilename,__LINE__);
941#endif
942
943  setMapArray(output->content,"geodatatype",imyIndex,"raster");
944  /**
945   * Add a new layer set name, data
946   */
947  if(msGrowMapLayers(m)==NULL){
948    return -1;
949  }
950  if(initLayer((m->layers[m->numlayers]), m) == -1){
951    return -1;
952  }
953  m->layers[m->numlayers]->index=m->numlayers;
954
955  layerObj* myLayer=m->layers[m->numlayers];
956  myLayer->name = zStrdup(output->name);
957  myLayer->tileitem=NULL;
958  myLayer->data = zStrdup(pszFilename);
959  myLayer->index = m->numlayers;
960  myLayer->dump = MS_TRUE;
961  myLayer->status = MS_ON;
962  myLayer->type = MS_LAYER_RASTER;
963
964  char *title=output->name;
965  tmpMap=getMapArray(output->content,"title",imyIndex);
966  if(tmpMap!=NULL)
967    title=tmpMap->value;
968  char *abstract=output->name;
969  tmpMap=getMapArray(output->content,"abstract",imyIndex);
970  if(tmpMap!=NULL)
971    abstract=tmpMap->value;
972
973  msInsertHashTable(&(myLayer->metadata), "ows_label", title);
974  msInsertHashTable(&(myLayer->metadata), "ows_title", title);
975  msInsertHashTable(&(myLayer->metadata), "ows_abstract", abstract);
976  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_name", output->name);
977  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_label", title);
978
979  /**
980   * Set Map Size to the raster size
981   */
982  m->width=GDALGetRasterXSize( hDataset );
983  m->height=GDALGetRasterYSize( hDataset );
984  addIntToMapArray(output->content,"nb_pixels",imyIndex,GDALGetRasterXSize( hDataset )*GDALGetRasterYSize( hDataset ));
985 
986  /**
987   * Set projection using Authority Code and Name if available or fallback to
988   * proj4 definition if available or fallback to default EPSG:4326
989   */
990  const char *tRef=GDALGetProjectionRef( hDataset );
991  if( tRef != NULL && strlen(tRef)>0 ){
992    char *pszProjection;
993    pszProjection = (char *) GDALGetProjectionRef( hDataset );
994#ifdef DEBUGMS
995    fprintf(stderr,"Accessing the DataSource %s\n",GDALGetProjectionRef( hDataset ));
996#endif
997    setSrsInformations(output,m,myLayer,pszProjection);
998  }else{
999    fprintf(stderr,"NO SRS FOUND ! %s\n",GDALGetProjectionRef( hDataset ));
1000    CPLErr sp=GDALSetProjection( hDataset , "+init=epsg:4326" );
1001    if(sp!=CE_None){
1002      fprintf(stderr,"NO SRS FOUND ! %s\n",CPLGetLastErrorMsg());
1003    }
1004  }
1005
1006  /**
1007   * Set extent
1008   */
1009  if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ){
1010    if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 ){
1011
1012      double minX = adfGeoTransform[0]
1013        + adfGeoTransform[2] * GDALGetRasterYSize(hDataset);
1014      double minY = adfGeoTransform[3]
1015        + adfGeoTransform[5] * GDALGetRasterYSize(hDataset);
1016
1017      double maxX = adfGeoTransform[0]
1018        + adfGeoTransform[1] * GDALGetRasterXSize(hDataset);
1019      double maxY = adfGeoTransform[3]
1020        + adfGeoTransform[4] * GDALGetRasterXSize(hDataset);
1021
1022      setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
1023      char extent[1024];
1024      memset(&extent,0,1024);
1025      sprintf(extent,"%d,%d,%d,%d",minX,minY,maxX,maxY);
1026      setMapArray(output->content,"boundingbox",imyIndex,extent);
1027    }
1028  }else{
1029    int scale=1;
1030    if(m->width>2048){
1031      addIntToMapArray(output->content,"width",imyIndex,2048);
1032      scale=2048/m->width;
1033    }else
1034      addIntToMapArray(output->content,"width",imyIndex,m->width);
1035    addIntToMapArray(output->content,"height",imyIndex,m->height*scale);
1036  }
1037
1038  /**
1039   * Extract information about available bands to set the bandcount and the
1040   * processing directive
1041   */
1042  char nBands[3];
1043  memset(&nBands,0,3);
1044  int nBandsI=GDALGetRasterCount( hDataset );
1045  if(nBandsI<100){
1046    sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
1047    msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
1048  }
1049  if(nBandsI>=3)
1050    if(nBandsI==4)
1051      msLayerAddProcessing(myLayer,"BANDS=1,2,3,4");
1052    else
1053      msLayerAddProcessing(myLayer,"BANDS=1,2,3");
1054  else if(nBandsI>=2)
1055    msLayerAddProcessing(myLayer,"BANDS=1,2");
1056  else
1057    msLayerAddProcessing(myLayer,"BANDS=1");
1058 
1059
1060  /**
1061   * Name available Bands
1062   */
1063  char lBands[7];
1064  char *nameBands=NULL;
1065  for( iBand = 0; iBand < nBandsI; iBand++ ){
1066    memset(&lBands,0,7);
1067    sprintf(lBands,"Band%d",iBand+1);   
1068    if(nameBands==NULL){
1069      nameBands=(char*)malloc((strlen(lBands)+1)*sizeof(char));
1070      sprintf(nameBands,"%s",lBands);
1071    }else{
1072      /*if(iBand<4)*/{
1073        char *tmpS=zStrdup(nameBands);
1074        nameBands=(char*)realloc(nameBands,(strlen(tmpS)+strlen(lBands)+2)*sizeof(char));
1075        sprintf(nameBands,"%s %s",tmpS,lBands);
1076        free(tmpS);
1077      }
1078    }
1079  }
1080  if(nameBands!=NULL){
1081    msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
1082    free(nameBands);
1083  }
1084
1085  /**
1086   * Loops over metadata information to setup specific information
1087   */
1088  for( iBand = 0; iBand < nBandsI; iBand++ ){
1089    double      pdfMin, pdfMax, pdfMean, pdfStdDev;
1090    hBand = GDALGetRasterBand( hDataset, iBand+1 );
1091
1092    CPLErrorReset();
1093    GDALComputeRasterStatistics( hBand, TRUE, &pdfMin, &pdfMax, &pdfMean, &pdfStdDev, NULL,NULL);
1094    char tmpN[21];
1095    sprintf(tmpN,"Band%d",iBand+1);
1096    if (CPLGetLastErrorType() == CE_None){
1097      char tmpMm[100],tmpMp[100];
1098      sprintf(tmpMm,"%.3f %.3f",pdfMin,pdfMax);
1099      sprintf(tmpMp,"SCALE_%d=%.3f,%.3f",iBand+1,pdfMean-(2*pdfStdDev),pdfMean+(2*pdfStdDev));
1100      char tmpI[31];     
1101      sprintf(tmpI,"%s_interval",tmpN);
1102      msInsertHashTable(&(myLayer->metadata), tmpI, tmpMm);
1103      if(pdfMax>255)
1104        msLayerAddProcessing(myLayer,tmpMp);
1105      map* test=getMap(output->content,"msClassify");
1106      if(test!=NULL && strncasecmp(test->value,"true",4)==0){
1107        /**
1108         * Classify one band raster pixel value using regular interval
1109         */
1110        int _tmpColors[10][3]={
1111          {102,153,204},
1112          {51,102,153},
1113          {102,102,204},
1114          {51,204,0},
1115          {153,255,102},
1116          {204,255,102},
1117          {102,204,153},
1118          {255,69,64},
1119          {255,192,115},
1120          {255,201,115}
1121        };
1122         
1123        if(nBandsI==1){
1124          double delta=pdfMax-pdfMin;
1125          double interval=delta/10;
1126          double cstep=pdfMin;
1127          for(i=0;i<10;i++){
1128            /**
1129             * Create a new class
1130             */
1131            if(msGrowLayerClasses(myLayer) == NULL)
1132              return -1;
1133            if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
1134              return -1;
1135            if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
1136              return -1;
1137            if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
1138              return -1;
1139           
1140            /**
1141             * Set class name
1142             */
1143            char className[7];
1144            sprintf(className,"class%d",i);
1145            myLayer->CLASS[myLayer->numclasses]->name=zStrdup(className);
1146           
1147            /**
1148             * Set expression
1149             */
1150            char expression[1024];
1151            if(i+1<10)
1152              sprintf(expression,"([pixel]>=%.3f AND [pixel]<%.3f)",cstep,cstep+interval);
1153            else
1154              sprintf(expression,"([pixel]>=%.3f AND [pixel]<=%.3f)",cstep,cstep+interval);
1155            msLoadExpressionString(&myLayer->CLASS[myLayer->numclasses]->expression,expression);
1156           
1157            /**
1158             * Set color
1159             */
1160            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=_tmpColors[i][0];
1161            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=_tmpColors[i][1];
1162            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=_tmpColors[i][2];
1163            cstep+=interval;
1164            myLayer->CLASS[myLayer->numclasses]->numstyles++;
1165            myLayer->numclasses++;
1166           
1167          }
1168         
1169          char tmpMm[100];
1170          sprintf(tmpMm,"%.3f %.3f",pdfMin,pdfMax);
1171         
1172        }
1173      }
1174      else{
1175        if(nBandsI==1){
1176          myLayer->offsite.red=0;
1177          myLayer->offsite.green=0;
1178          myLayer->offsite.blue=0;
1179        }
1180      }
1181    }
1182    if( strlen(GDALGetRasterUnitType(hBand)) > 0 ){
1183      char tmpU[31];
1184      sprintf(tmpU,"%s_band_uom",tmpN);
1185      msInsertHashTable(&(myLayer->metadata), tmpU, GDALGetRasterUnitType(hBand));
1186    }
1187
1188  }
1189  msLayerAddProcessing(myLayer,"RESAMPLE=BILINEAR");
1190
1191  m->layerorder[m->numlayers] = m->numlayers;
1192  m->numlayers++;
1193  GDALClose( hDataset );
1194  GDALDestroyDriverManager();
1195  CPLCleanupTLS();
1196  return 1;
1197}
1198
1199/**
1200 * Create a MapFile for WMS, WFS or WCS Service output
1201 *
1202 * @param conf the conf maps containing the main.cfg settings
1203 * @param outputs a specific output maps
1204 */
1205void outputMapfile(maps* conf,maps* outputs){
1206  /**
1207   * First store the value on disk
1208   */
1209  int imyIndex=getPublishedId(outputs);
1210  map* mime=getMapArray(outputs->content,"mimeType",imyIndex);
1211  char *ext="data";
1212  if(mime!=NULL)
1213    if(strncasecmp(mime->value,"application/json",16)==0)
1214      ext="json";
1215
1216  map* storage=getMapArray(outputs->content,"storage",imyIndex);
1217  if(storage==NULL){
1218    map* tmpMap=getMapFromMaps(conf,"main","dataPath");
1219    map* sidMap=getMapFromMaps(conf,"lenv","usid");
1220    char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
1221    sprintf(pszDataSource,"%s/ZOO_DATA_%d_%s_%s.%s",tmpMap->value,imyIndex,outputs->name,sidMap->value,ext);
1222    int f=zOpen(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
1223    map *gfile=getMapArray(outputs->content,"generated_file",imyIndex);
1224    if(gfile!=NULL){
1225      readGeneratedFile(conf,outputs->content,gfile->value);       
1226    }
1227    map* sizeMap=getMapArray(outputs->content,"size",imyIndex);
1228    map* vData=getMapArray(outputs->content,"value",imyIndex);
1229    if(sizeMap!=NULL){
1230      zWrite(f,vData->value,atoi(sizeMap->value)*sizeof(char));
1231    }
1232    else{
1233      zWrite(f,vData->value,(strlen(vData->value)+1)*sizeof(char));
1234    }
1235    close(f);
1236    setMapArray(outputs->content,"storage",imyIndex,pszDataSource);
1237    free(pszDataSource);
1238  }
1239
1240  /*
1241   * Create an empty map, set name, default size and extent
1242   */
1243  mapObj *myMap=msNewMapObj();
1244  free(myMap->name);
1245  myMap->name=zStrdup("ZOO-Project_WXS_Server");
1246  msMapSetSize(myMap,2048,2048);
1247  msMapSetExtent(myMap,-1,-1,1,1);
1248 
1249  /*
1250   * Set imagepath and imageurl using tmpPath and tmpUrl from main.cfg
1251   */
1252  map *tmp1=getMapFromMaps(conf,"main","tmpPath");
1253  myMap->web.imagepath=zStrdup(tmp1->value);
1254  tmp1=getMapFromMaps(conf,"main","tmpUrl");
1255  myMap->web.imageurl=zStrdup(tmp1->value);
1256 
1257  /*
1258   * Define supported output formats
1259   */
1260  outputFormatObj *o1=msCreateDefaultOutputFormat(NULL,"AGG/PNG","png");
1261  o1->imagemode=MS_IMAGEMODE_RGBA;
1262  o1->transparent=MS_TRUE;
1263  o1->inmapfile=MS_TRUE;
1264  msAppendOutputFormat(myMap,msCloneOutputFormat(o1));
1265  msFreeOutputFormat(o1);
1266
1267#ifdef USE_KML
1268  outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
1269  if(!o2){
1270    perror("Unable to initialize KML driver");
1271    fprintf(stderr,"Unable to initialize KML driver !\n");
1272  }else{
1273    o2->inmapfile=MS_TRUE; 
1274    msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
1275    msFreeOutputFormat(o2);
1276  }
1277#endif
1278
1279  outputFormatObj *o3=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","tiff");
1280  if(!o3)
1281    fprintf(stderr,"Unable to initialize GDAL driver !\n");
1282  else{
1283    o3->imagemode=MS_IMAGEMODE_BYTE;
1284    o3->inmapfile=MS_TRUE; 
1285    msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
1286    msFreeOutputFormat(o3);
1287  }
1288
1289  outputFormatObj *o4=msCreateDefaultOutputFormat(NULL,"GDAL/AAIGRID","grd");
1290  if(!o4)
1291    fprintf(stderr,"Unable to initialize GDAL driver !\n");
1292  else{
1293    o4->imagemode=MS_IMAGEMODE_INT16;
1294    o4->inmapfile=MS_TRUE; 
1295    msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
1296    msFreeOutputFormat(o4);
1297  }
1298
1299#ifdef USE_CAIRO
1300  outputFormatObj *o5=msCreateDefaultOutputFormat(NULL,"CAIRO/PNG","cairopng");
1301  if(!o5)
1302    fprintf(stderr,"Unable to initialize CAIRO driver !\n");
1303  else{
1304    o5->imagemode=MS_IMAGEMODE_RGBA;
1305    o5->transparent=MS_TRUE;
1306    o5->inmapfile=MS_TRUE;
1307    msAppendOutputFormat(myMap,msCloneOutputFormat(o5));
1308    msFreeOutputFormat(o5);
1309  }
1310#endif
1311
1312  outputFormatObj *o6=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","geotiff");
1313  if(!o6)
1314    fprintf(stderr,"Unable to initialize GDAL driver !\n");
1315  else{
1316    o6->imagemode=MS_IMAGEMODE_BYTE;
1317    o6->mimetype=strdup("image/geotiff");
1318    o6->inmapfile=MS_TRUE;
1319    msAppendOutputFormat(myMap,msCloneOutputFormat(o6));
1320    msFreeOutputFormat(o6);
1321  }
1322
1323  /*
1324   * Set default projection to EPSG:4326
1325   */
1326  msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
1327  myMap->transparent=1;
1328
1329  /**
1330   * Set metadata extracted from main.cfg file maps
1331   */
1332  maps* cursor=conf;
1333  map* correspondance=getCorrespondance();
1334  while(cursor!=NULL){
1335    map* _cursor=cursor->content;
1336    map* vMap;
1337    while(_cursor!=NULL){
1338      if((vMap=getMap(correspondance,_cursor->name))!=NULL){
1339        if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
1340#ifdef DEBUGMS
1341          fprintf(stderr,"Unable to add metadata");
1342#endif
1343          return;
1344        }
1345      }
1346      _cursor=_cursor->next;
1347    }
1348    cursor=cursor->next;
1349  }
1350  freeMap(&correspondance);
1351  free(correspondance);
1352
1353  /*
1354   * Set mapserver PROJ_LIB/GDAL_DATA or any other config parameter from
1355   * the main.cfg [mapserver] section if any
1356   */
1357  maps *tmp3=getMaps(conf,"mapserver");
1358  if(tmp3!=NULL){
1359    map* tmp4=tmp3->content;
1360    while(tmp4!=NULL){
1361      msSetConfigOption(myMap,tmp4->name,tmp4->value);
1362      tmp4=tmp4->next;
1363    }
1364  }
1365
1366  /**
1367   * Set a ows_rootlayer_title, 
1368   */
1369  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_name", "ZOO_Project_Layer") == NULL){
1370#ifdef DEBUGMS
1371    fprintf(stderr,"Unable to add metadata");
1372#endif
1373    return;
1374  }
1375  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_title", "ZOO_Project_Layer") == NULL){
1376#ifdef DEBUGMS
1377    fprintf(stderr,"Unable to add metadata");
1378#endif
1379    return;
1380  }
1381
1382  /**
1383   * Enable all the WXS requests using ows_enable_request
1384   * see http://mapserver.org/trunk/development/rfc/ms-rfc-67.html
1385   */
1386  if (msInsertHashTable(&(myMap->web.metadata), "ows_enable_request", "*") == NULL){
1387#ifdef DEBUGMS
1388    fprintf(stderr,"Unable to add metadata");
1389#endif
1390    return;
1391  }
1392  msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
1393
1394  if(tryOgr(conf,outputs,myMap)<0)
1395    if(tryGdal(conf,outputs,myMap)<0)
1396      return ;
1397
1398  tmp1=getMapFromMaps(conf,"main","dataPath");
1399  char *tmpPath=(char*)malloc((13+strlen(tmp1->value))*sizeof(char));
1400  sprintf(tmpPath,"%s/symbols.sym",tmp1->value);
1401  msInitSymbolSet(&myMap->symbolset);
1402  myMap->symbolset.filename=zStrdup(tmpPath);
1403  free(tmpPath);
1404
1405  map* sid=getMapFromMaps(conf,"lenv","usid");
1406  char *mapPath=
1407    (char*)malloc((14+strlen(sid->value)+strlen(outputs->name)+strlen(tmp1->value))*sizeof(char));
1408  sprintf(mapPath,"%s/%s_%d_%s.map",tmp1->value,outputs->name,imyIndex,sid->value);
1409  msSaveMap(myMap,mapPath);
1410  free(mapPath);
1411  //msFreeSymbolSet(&myMap->symbolset);
1412  msFreeMap(myMap);
1413  //msFree(myMap);
1414  msGDALCleanup();
1415}
1416
Note: See TracBrowser for help on using the repository browser.

Search

ZOO Sponsors

http://www.zoo-project.org/trac/chrome/site/img/geolabs-logo.pnghttp://www.zoo-project.org/trac/chrome/site/img/neogeo-logo.png http://www.zoo-project.org/trac/chrome/site/img/apptech-logo.png http://www.zoo-project.org/trac/chrome/site/img/3liz-logo.png http://www.zoo-project.org/trac/chrome/site/img/gateway-logo.png

Become a sponsor !

Knowledge partners

http://www.zoo-project.org/trac/chrome/site/img/ocu-logo.png http://www.zoo-project.org/trac/chrome/site/img/gucas-logo.png http://www.zoo-project.org/trac/chrome/site/img/polimi-logo.png http://www.zoo-project.org/trac/chrome/site/img/fem-logo.png http://www.zoo-project.org/trac/chrome/site/img/supsi-logo.png http://www.zoo-project.org/trac/chrome/site/img/cumtb-logo.png

Become a knowledge partner

Related links

http://zoo-project.org/img/ogclogo.png http://zoo-project.org/img/osgeologo.png