source: trunk/zoo-project/zoo-kernel/service_internal_ms.c

Last change on this file was 984, checked in by djay, 3 years ago

Take into account building ZOO-Project on ubuntu focal (cf. https://trac.osgeo.org/osgeolive/ticket/2282). Add the OTB and SAGA support to the Dockerfile to make the corresponding demos using docker WPS server. Add OGC API - Processes demo to the demos list.

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

Search

Context Navigation

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