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

Last change on this file since 490 was 490, checked in by djay, 10 years ago

Remove memory leaks from ZOO-Kernel. Fix issue #99.

  • Property svn:eol-style set to native
  • Property svn:mime-type set to text/x-csrc
File size: 34.1 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#ifdef USE_MS
26#ifndef WIN32
27#define CLASS class
28#else
29#define CLASS _class
30#endif
31#include "service_internal_ms.h"
32
33/**
34 * Map composed by a main.cfg maps name as key and the corresponding
35 * MapServer Mafile Metadata name to use
36 * see doc from here :
37 *  - http://mapserver.org/ogc/wms_server.html
38 *  - http://mapserver.org/ogc/wfs_server.html
39 *  - http://mapserver.org/ogc/wcs_server.html
40 */
41map* getCorrespondance(){
42  map* res=createMap("encoding","ows_encoding");
43  addToMap(res,"abstract","ows_abstract");
44  addToMap(res,"title","ows_title");
45  addToMap(res,"keywords","ows_keywordlist");
46  addToMap(res,"fees","ows_fees");
47  addToMap(res,"accessConstraints","ows_accessconstraints");
48  addToMap(res,"providerName","ows_attribution_title");
49  addToMap(res,"providerSite","ows_service_onlineresource");
50  addToMap(res,"individualName","ows_contactperson");
51  addToMap(res,"positionName","ows_contactposition");
52  addToMap(res,"providerName","ows_contactorganization");
53  addToMap(res,"role","ows_role");
54  addToMap(res,"addressType","ows_addresstype");
55  addToMap(res,"addressCity","ows_city");
56  addToMap(res,"addressDeliveryPoint","ows_address");
57  addToMap(res,"addressPostalCode","ows_postcode");
58  addToMap(res,"addressAdministrativeArea","ows_stateorprovince");
59  addToMap(res,"addressCountry","ows_country");
60  addToMap(res,"phoneVoice","ows_contactvoicetelephone");
61  addToMap(res,"phoneFacsimile","ows_contactfacsimiletelephone");
62  addToMap(res,"addressElectronicMailAddress","ows_contactelectronicmailaddress");
63  // Missing Madatory Informations
64  addToMap(res,"hoursOfService","ows_hoursofservice");
65  addToMap(res,"contactInstructions","ows_contactinstructions");
66  return res;
67}
68
69void setMapSize(maps* output,double minx,double miny,double maxx,double maxy){
70  double maxWidth=640;
71  double maxHeight=480;
72  double deltaX=maxx-minx;
73  double deltaY=maxy-miny;
74  double qWidth;
75  qWidth=maxWidth/deltaX;
76  double qHeight;
77  qHeight=maxHeight/deltaY;
78#ifdef DEBUGMS
79  fprintf(stderr,"deltaX : %.15f \ndeltaY : %.15f\n",deltaX,deltaY);
80  fprintf(stderr,"qWidth : %.15f \nqHeight : %.15f\n",qWidth,qHeight);
81#endif
82
83  double width=deltaX*qWidth;
84  double height=height=deltaY*qWidth;
85  if(deltaX<deltaY){
86    width=deltaX*qHeight;
87    height=deltaY*qHeight;
88  }
89  if(height<0)
90    height=-height;
91  if(width<0)
92    width=-width;
93  char sWidth[1024];
94  char sHeight[1024];
95  sprintf(sWidth,"%.3f",width);
96  sprintf(sHeight,"%.3f",height);
97#ifdef DEBUGMS
98  fprintf(stderr,"sWidth : %.15f \nsHeight : %.15f\n",sWidth,sHeight);
99#endif
100  if(output!=NULL){
101    addToMap(output->content,"width",sWidth);
102    addToMap(output->content,"height",sHeight);
103  }
104}
105
106void setReferenceUrl(maps* m,maps* tmpI){
107  outputMapfile(m,tmpI);
108  map *msUrl=getMapFromMaps(m,"main","mapserverAddress");
109  map *msOgcVersion=getMapFromMaps(m,"main","msOgcVersion");
110  map *dataPath=getMapFromMaps(m,"main","dataPath");
111  map *sid=getMapFromMaps(m,"lenv","usid");
112  map* format=getMap(tmpI->content,"mimeType");
113  map* rformat=getMap(tmpI->content,"requestedMimeType");
114  map* width=getMap(tmpI->content,"width");
115  map* height=getMap(tmpI->content,"height");
116  map* protoMap=getMap(tmpI->content,"msOgc");
117  map* versionMap=getMap(tmpI->content,"msOgcVersion");
118  char options[3][5][25]={
119    {"WMS","1.3.0","GetMap","layers=%s","wms_extent"},
120    {"WFS","1.1.0","GetFeature","typename=%s","wcs_extent"},
121    {"WCS","1.1.0","GetCoverage","coverage=%s","wcs_extent"}
122  };
123  int proto=0;
124  if(rformat==NULL){
125    rformat=getMap(tmpI->content,"mimeType");
126  }
127  if(strncasecmp(rformat->value,"text/xml",8)==0)
128    proto=1;
129  if(strncasecmp(rformat->value,"image/tiff",10)==0)
130    proto=2;
131  if(protoMap!=NULL){
132    if(strncasecmp(protoMap->value,"WMS",3)==0)
133      proto=0;
134    else{
135      if(strncasecmp(protoMap->value,"WFS",3)==0)
136        proto=1;
137      else 
138        proto=2;
139    }
140  }
141  char *protoVersion=options[proto][1];
142  if(proto==1){
143    if(msOgcVersion!=NULL)
144      protoVersion=msOgcVersion->value;
145    if(versionMap!=NULL)
146      protoVersion=versionMap->value;
147  }
148
149  map* extent=getMap(tmpI->content,options[proto][4]);
150  map* crs=getMap(tmpI->content,"crs");
151  int hasCRS=1;
152  if(crs==NULL){
153    crs=getMapFromMaps(m,"main","crs");
154    if(crs==NULL){
155      crs=createMap("crs","epsg:4326");
156      hasCRS=0;
157    }
158  }
159  char layers[128];
160  sprintf(layers,options[proto][3],tmpI->name);
161
162  char* webService_url=(char*)malloc((strlen(msUrl->value)+strlen(format->value)+strlen(tmpI->name)+strlen(width->value)+strlen(height->value)+strlen(extent->value)+256)*sizeof(char));
163
164  if(proto>0){
165    sprintf(webService_url,
166            "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&format=%s&bbox=%s&crs=%s",
167            msUrl->value,
168            dataPath->value,
169            tmpI->name,
170            sid->value,
171            options[proto][2],
172            options[proto][0],
173            protoVersion,
174            layers,
175            rformat->value,
176            extent->value,
177            crs->value
178            );
179  }
180  else{
181    sprintf(webService_url,
182            "%s?map=%s/%s_%s.map&request=%s&service=%s&version=%s&%s&width=%s&height=%s&format=%s&bbox=%s&crs=%s",
183            msUrl->value,
184            dataPath->value,
185            tmpI->name,
186            sid->value,
187            options[proto][2],
188            options[proto][0],
189            protoVersion,
190            layers,
191            width->value,
192            height->value,
193            rformat->value,
194            extent->value,
195            crs->value
196            );
197  }
198  if(hasCRS==0){
199    freeMap(&crs);
200    free(crs);
201  }
202  addToMap(tmpI->content,"Reference",webService_url);
203
204}
205
206/**
207 * Set projection using Authority Code and Name if available or fallback to
208 * proj4 definition if available or fallback to default EPSG:4326
209 */
210void setSrsInformations(maps* output,mapObj* m,layerObj* myLayer,
211                        char* pszProjection){
212  OGRSpatialReferenceH  hSRS;
213  map* msSrs=NULL;
214  hSRS = OSRNewSpatialReference(NULL);
215  if( pszProjection!=NULL && strlen(pszProjection)>1){
216    if(OSRImportFromWkt( hSRS, &pszProjection ) == CE_None ){
217      char *proj4Str=NULL;
218      if(OSRGetAuthorityName(hSRS,NULL)!=NULL && 
219         OSRGetAuthorityCode(hSRS,NULL)!=NULL){
220        char tmpSrs[20];
221        sprintf(tmpSrs,"%s:%s",
222                OSRGetAuthorityName(hSRS,NULL),OSRGetAuthorityCode(hSRS,NULL));
223        msLoadProjectionStringEPSG(&m->projection,tmpSrs);
224        msLoadProjectionStringEPSG(&myLayer->projection,tmpSrs);
225       
226        char tmpSrss[256];
227        sprintf(tmpSrss,"EPSG:4326 EPSG:900913 %s",tmpSrs);
228       
229        msInsertHashTable(&(m->web.metadata), "ows_srs", tmpSrss);
230        msInsertHashTable(&(myLayer->metadata), "ows_srs", tmpSrss);
231       
232#ifdef DEBUGMS
233        fprintf(stderr,"isGeo %b\n\n",OSRIsGeographic(hSRS)==TRUE);
234#endif
235        if(output!=NULL){
236          if(OSRIsGeographic(hSRS)==TRUE)
237            addToMap(output->content,"crs_isGeographic","true");
238          else
239            addToMap(output->content,"crs_isGeographic","false");
240          addToMap(output->content,"crs",tmpSrs);
241        }
242      }
243      else{
244        OSRExportToProj4(hSRS,&proj4Str);
245        if(proj4Str!=NULL && strlen(proj4Str)>0){
246#ifdef DEBUGMS
247          fprintf(stderr,"PROJ (%s)\n",proj4Str);
248#endif
249          msLoadProjectionString(&(m->projection),proj4Str);
250          msLoadProjectionString(&(myLayer->projection),proj4Str);
251          if(output!=NULL){ 
252            if(OSRIsGeographic(hSRS)==TRUE)
253              addToMap(output->content,"crs_isGeographic","true");
254            else
255              addToMap(output->content,"crs_isGeographic","false");
256          }
257        }
258        else{
259          msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
260          msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
261          if(output!=NULL){
262            addToMap(output->content,"crs_isGeographic","true");
263          }
264        }
265        if(output!=NULL){
266          addToMap(output->content,"crs","EPSG:4326");
267          addToMap(output->content,"real_extent","true");
268        }
269        msInsertHashTable(&(m->web.metadata),"ows_srs", "EPSG:4326 EPSG:900913");
270        msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913");
271      }
272    }
273  }
274  else{
275    if(output!=NULL){
276      msSrs=getMap(output->content,"msSrs");
277    }
278    if(msSrs!=NULL){
279      msLoadProjectionStringEPSG(&m->projection,msSrs->value);
280      msLoadProjectionStringEPSG(&myLayer->projection,msSrs->value);
281      char tmpSrs[128];
282      sprintf(tmpSrs,"%s EPSG:4326 EPSG:900913",msSrs->value);
283      msInsertHashTable(&(m->web.metadata),"ows_srs",tmpSrs);
284      msInsertHashTable(&(myLayer->metadata),"ows_srs",tmpSrs);
285    }else{
286      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
287      msLoadProjectionStringEPSG(&myLayer->projection,"EPSG:4326");
288      msInsertHashTable(&(m->web.metadata),"ows_srs","EPSG:4326 EPSG:900913");
289      msInsertHashTable(&(myLayer->metadata),"ows_srs","EPSG:4326 EPSG:900913");
290    }
291    if(output!=NULL){
292      addToMap(output->content,"crs",msSrs->value);
293      addToMap(output->content,"crs_isGeographic","true");
294    }
295  }
296
297  OSRDestroySpatialReference( hSRS );
298}
299
300void setMsExtent(maps* output,mapObj* m,layerObj* myLayer,
301                 double minX,double minY,double maxX,double maxY){
302  msMapSetExtent(m,minX,minY,maxX,maxY);
303#ifdef DEBUGMS
304  fprintf(stderr,"Extent %.15f %.15f %.15f %.15f\n",minX,minY,maxX,maxY);
305#endif
306  char tmpExtent[1024];
307  sprintf(tmpExtent,"%.15f %.15f %.15f %.15f",minX,minY,maxX,maxY);
308#ifdef DEBUGMS
309  fprintf(stderr,"Extent %s\n",tmpExtent);
310#endif
311  msInsertHashTable(&(myLayer->metadata), "ows_extent", tmpExtent);
312 
313  if(output!=NULL){
314    map* test=getMap(output->content,"real_extent");
315    if(test!=NULL){
316      pointObj min, max;
317      projectionObj tempSrs;
318      min.x = m->extent.minx;
319      min.y = m->extent.miny;
320      max.x = m->extent.maxx;
321      max.y = m->extent.maxy;
322      char tmpSrsStr[1024];
323      msInitProjection(&tempSrs);
324      msLoadProjectionStringEPSG(&tempSrs,"EPSG:4326");
325
326      msProjectPoint(&(m->projection),&tempSrs,&min);
327      msProjectPoint(&m->projection,&tempSrs,&max);
328     
329      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",min.y,min.x,max.y,max.x);
330      map* isGeo=getMap(output->content,"crs_isGeographic");
331#ifdef DEBUGMS
332      fprintf(stderr,"isGeo = %s\n",isGeo->value);
333#endif
334      if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
335        sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
336      addToMap(output->content,"wms_extent",tmpExtent);
337      sprintf(tmpSrsStr,"%.3f,%.3f,%.3f,%.3f",min.x,min.y,max.x,max.y);
338      addToMap(output->content,"wcs_extent",tmpExtent);
339    }else{
340      sprintf(tmpExtent,"%f,%f,%f,%f",minX, minY, maxX, maxY);
341      map* isGeo=getMap(output->content,"crs_isGeographic");
342      if(isGeo!=NULL){
343#ifdef DEBUGMS
344        fprintf(stderr,"isGeo = %s\n",isGeo->value);
345#endif
346        if(isGeo!=NULL && strcasecmp("true",isGeo->value)==0)
347          sprintf(tmpExtent,"%f,%f,%f,%f", minY,minX, maxY, maxX);
348      }
349      addToMap(output->content,"wms_extent",tmpExtent); 
350      sprintf(tmpExtent,"%.3f,%.3f,%.3f,%.3f",minX,minY,maxX,maxY);
351      addToMap(output->content,"wcs_extent",tmpExtent);
352    }
353  }
354
355  setMapSize(output,minX,minY,maxX,maxY);
356}
357
358int tryOgr(maps* conf,maps* output,mapObj* m){
359
360  map* tmpMap=getMap(output->content,"storage");
361  char *pszDataSource=tmpMap->value;
362
363  /**
364   * Try to open the DataSource using OGR
365   */
366  OGRRegisterAll();
367  /**
368   * Try to load the file as ZIP
369   */
370
371  OGRDataSourceH poDS1 = NULL;
372  OGRSFDriverH *poDriver1 = NULL;
373  char *dsName=(char*)malloc((8+strlen(pszDataSource)+1)*sizeof(char));
374  char *odsName=zStrdup(pszDataSource);
375  char *sdsName=zStrdup(pszDataSource);
376  char *demo=strstr(odsName,".");
377  sdsName[strlen(sdsName)-(strlen(demo)-1)]='d';
378  sdsName[strlen(sdsName)-(strlen(demo)-2)]='i';
379  sdsName[strlen(sdsName)-(strlen(demo)-3)]='r';
380  sdsName[strlen(sdsName)-(strlen(demo)-4)]=0;
381
382  odsName[strlen(odsName)-(strlen(demo)-1)]='z';
383  odsName[strlen(odsName)-(strlen(demo)-2)]='i';
384  odsName[strlen(odsName)-(strlen(demo)-3)]='p';
385  odsName[strlen(odsName)-(strlen(demo)-4)]=0;
386  sprintf(dsName,"/vsizip/%s",odsName);
387
388#ifdef DEBUGMS
389  fprintf(stderr,"Try loading %s, %s, %s\n",dsName,odsName,dsName);
390#endif
391
392  FILE* file = fopen(pszDataSource, "rb");
393  FILE* fileZ = fopen(odsName, "wb");
394  fseek(file, 0, SEEK_END);
395  unsigned long fileLen=ftell(file);
396  fseek(file, 0, SEEK_SET);
397  char *buffer=(char *)malloc(fileLen+1);
398  fread(buffer, fileLen, 1, file);
399  fwrite(buffer,fileLen, 1, fileZ);
400  fclose(file);
401  fclose(fileZ);
402  free(buffer);
403#ifdef DEBUGMS
404  fprintf(stderr,"Try loading %s",dsName);
405#endif
406  poDS1 = OGROpen( dsName, FALSE, poDriver1 );
407  if( poDS1 == NULL ){
408    fprintf(stderr,"Unable to access the DataSource as ZIP File\n");
409    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
410    OGR_DS_Destroy(poDS1);
411  }else{
412#ifdef DEBUGMS
413    fprintf(stderr,"The DataSource is a  ZIP File\n");
414#endif
415    char** demo=VSIReadDir(dsName);
416    int i=0;
417    zMkdir(sdsName
418#ifndef WIN32
419                ,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH
420#endif
421                );
422    while(demo[i]!=NULL){
423#ifdef DEBUGMS
424      fprintf(stderr,"ZIP File content : %s\n",demo[i]);
425#endif
426      char *tmpDs=(char*)malloc((strlen(dsName)+strlen(demo[i])+2)*sizeof(char));
427      sprintf(tmpDs,"%s/%s",dsName,demo[i]);
428      fprintf(stderr,"read : %s\n",tmpDs);
429     
430      VSILFILE* vsif=VSIFOpenL(tmpDs,"rb");
431#ifdef DEBUGMS
432      fprintf(stderr,"open : %s\n",tmpDs);
433#endif
434      VSIFSeekL(vsif,0,SEEK_END);
435      vsi_l_offset size=VSIFTellL(vsif);
436#ifdef DEBUGMS
437      fprintf(stderr,"size : %d\n",size);
438#endif
439      VSIFSeekL(vsif,0,SEEK_SET);
440      char *vsifcontent=(char*) malloc(((int)size+1)*sizeof(char));
441      VSIFReadL(vsifcontent,1,(size_t)size,vsif);
442      char *fpath=(char*) malloc((strlen(sdsName)+strlen(demo[1])+2)*sizeof(char));
443      sprintf(fpath,"%s/%s",sdsName,demo[i]);
444      int f=zOpen(fpath,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
445      zWrite(f,vsifcontent,(int)size);
446      close(f);
447      chmod(fpath,S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH);
448      char* tmpP=strstr(fpath,".shp");
449      if(tmpP==NULL)
450        tmpP=strstr(fpath,".SHP");
451      if(tmpP!=NULL){
452#ifdef DEBUGMS
453        fprintf(stderr,"*** DEBUG %s\n",strstr(tmpP,"."));
454#endif
455        if( strcmp(tmpP,".shp")==0 || strcmp(tmpP,".SHP")==0 ){
456          tmpMap=getMap(output->content,"storage");
457          free(tmpMap->value);
458          tmpMap->value=(char*) malloc((strlen(fpath)+1)*sizeof(char));
459          sprintf(tmpMap->value,"%s",fpath);
460          pszDataSource=tmpMap->value;
461#ifdef DEBUGMS
462          fprintf(stderr,"*** DEBUG %s\n",pszDataSource);
463#endif
464        }
465      }
466      VSIFCloseL(vsif);
467      i++;
468    }
469
470  }
471
472  OGRDataSourceH poDS = NULL;
473  OGRSFDriverH *poDriver = NULL;
474  poDS = OGROpen( pszDataSource, FALSE, poDriver );
475  if( poDS == NULL ){
476#ifdef DEBUGMS
477    fprintf(stderr,"Unable to access the DataSource %s\n",pszDataSource);
478#endif
479    setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
480    OGR_DS_Destroy(poDS);
481    OGRCleanupAll();
482#ifdef DEBUGMS
483    fprintf(stderr,"Unable to access the DataSource, exit! \n"); 
484#endif
485    return -1;
486  }
487
488  int iLayer = 0;
489  for( iLayer=0; iLayer < OGR_DS_GetLayerCount(poDS); iLayer++ ){
490    OGRLayerH poLayer = OGR_DS_GetLayer(poDS,iLayer);
491
492    if( poLayer == NULL ){
493#ifdef DEBUGMS
494      fprintf(stderr,"Unable to access the DataSource Layer \n");
495#endif
496      setMapInMaps(conf,"lenv","message","Unable to open datasource in read only mode");
497      return -1;
498    }
499
500    /**
501     * Add a new layer set name, data
502     */
503    if(msGrowMapLayers(m)==NULL){
504      return -1;
505    }
506    if(initLayer((m->layers[m->numlayers]), m) == -1){
507      return -1;
508    }
509
510    layerObj* myLayer=m->layers[m->numlayers];
511#ifdef DEBUGMS
512    dumpMaps(output);
513#endif
514    myLayer->name = zStrdup(output->name);
515    myLayer->tileitem=NULL;
516    myLayer->data = zStrdup(OGR_L_GetName(poLayer));
517    myLayer->connection = zStrdup(pszDataSource);
518    myLayer->index = m->numlayers;
519    myLayer->dump = MS_TRUE;
520    myLayer->status = MS_ON;
521    msConnectLayer(myLayer,MS_OGR,pszDataSource);
522
523    /**
524     * Detect the Geometry Type or use Polygon
525     */
526    if(OGR_L_GetGeomType(poLayer) != wkbUnknown){
527      switch(OGR_L_GetGeomType(poLayer)){
528      case wkbPoint:
529      case wkbMultiPoint:
530      case wkbPoint25D:
531      case wkbMultiPoint25D:
532#ifdef DEBUGMS
533        fprintf(stderr,"POINT DataSource Layer \n");
534#endif
535        myLayer->type = MS_LAYER_POINT;
536        break;
537      case wkbLineString :
538      case wkbMultiLineString :
539      case wkbLineString25D:
540      case wkbMultiLineString25D:
541#ifdef DEBUGMS
542        fprintf(stderr,"LINE DataSource Layer \n");
543#endif
544        myLayer->type = MS_LAYER_LINE;
545        break;
546      case wkbPolygon:
547      case wkbMultiPolygon:
548      case wkbPolygon25D:
549      case wkbMultiPolygon25D:
550#ifdef DEBUGMS
551        fprintf(stderr,"POLYGON DataSource Layer \n");
552#endif
553        myLayer->type = MS_LAYER_POLYGON;
554        break;
555      default:
556        myLayer->type = MS_LAYER_POLYGON;
557        break;
558      }
559    }else
560      myLayer->type = MS_LAYER_POLYGON;
561
562    /**
563     * Detect spatial reference or use WGS84
564     */
565    OGRSpatialReferenceH srs=OGR_L_GetSpatialRef(poLayer);
566    if(srs!=NULL){
567      char *wkt=NULL;
568      OSRExportToWkt(srs,&wkt);
569      setSrsInformations(output,m,myLayer,wkt);
570    }
571    else{
572      addToMap(output->content,"crs","EPSG:4326");
573      addToMap(output->content,"crs_isGeographic","true");
574      msLoadProjectionStringEPSG(&m->projection,"EPSG:4326");
575      msInsertHashTable(&(m->web.metadata), "ows_srs", "EPSG:4326 EPSG:900913");
576      msInsertHashTable(&(myLayer->metadata), "ows_srs", "EPSG:4326 EPSG:900913");
577    }
578
579    OGREnvelope oExt;
580    if (OGR_L_GetExtent(poLayer,&oExt, TRUE) == OGRERR_NONE){
581      setMsExtent(output,m,myLayer,oExt.MinX, oExt.MinY, oExt.MaxX, oExt.MaxY);
582    }
583 
584    /**
585     * Detect the FID column or use the first attribute field as FID
586     */
587    char *fid=(char*)OGR_L_GetFIDColumn(poLayer);
588    if(strlen(fid)==0){
589      OGRFeatureDefnH def=OGR_L_GetLayerDefn(poLayer);
590      int fIndex=0;
591      for(fIndex=0;fIndex<OGR_FD_GetFieldCount(def);fIndex++){
592        OGRFieldDefnH fdef=OGR_FD_GetFieldDefn(def,fIndex);
593        fid=(char*)OGR_Fld_GetNameRef(fdef);
594        break;
595      }
596    }
597    msInsertHashTable(&(myLayer->metadata), "gml_featureid", fid);
598    msInsertHashTable(&(myLayer->metadata), "gml_include_items", "all");
599    msInsertHashTable(&(myLayer->metadata), "ows_name", output->name);
600    map* tmpMap=getMap(output->content,"title");
601    if(tmpMap!=NULL)
602      msInsertHashTable(&(myLayer->metadata), "ows_title", tmpMap->value);
603    else
604      msInsertHashTable(&(myLayer->metadata), "ows_title", "Default Title");
605   
606    if(msGrowLayerClasses(myLayer) == NULL)
607      return -1;
608    if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
609      return -1;
610    myLayer->CLASS[myLayer->numclasses]->type = myLayer->type;
611    if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
612      return -1;
613    if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
614      return -1;
615    /**
616     * Apply msStyle else fallback to the default style
617     */
618    tmpMap=getMap(output->content,"msStyle");
619    if(tmpMap!=NULL)
620      msUpdateStyleFromString(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles],tmpMap->value,0);
621    else{
622      /**
623       * Set style
624       */
625      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=125;
626      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=125;
627      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=255;
628      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.red=80;
629      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.green=80;
630      myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinecolor.blue=80;
631     
632      /**
633       * Set specific style depending on type
634       */
635      if(myLayer->type == MS_LAYER_POLYGON)
636        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
637      if(myLayer->type == MS_LAYER_LINE){
638        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->width=3;
639        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->outlinewidth=1.5;
640      }
641      if(myLayer->type == MS_LAYER_POINT){
642        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->symbol=1;
643        myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->size=15;
644      }
645     
646    }
647    myLayer->CLASS[myLayer->numclasses]->numstyles++;
648    myLayer->numclasses++;
649   
650    m->layerorder[m->numlayers] = m->numlayers;
651    m->numlayers++;
652
653  }
654
655  OGR_DS_Destroy(poDS);
656  OGRCleanupAll();
657
658  return 1;
659}
660
661
662int tryGdal(maps* conf,maps* output,mapObj* m){
663  map* tmpMap=getMap(output->content,"storage");
664  char *pszFilename=tmpMap->value;
665  GDALDatasetH hDataset;
666  GDALRasterBandH hBand;
667  double adfGeoTransform[6];
668  int i, iBand;
669 
670  /**
671   * Try to open the DataSource using GDAL
672   */
673  GDALAllRegister();
674  hDataset = GDALOpen( pszFilename, GA_ReadOnly );
675  if( hDataset == NULL ){
676#ifdef DEBUGMS
677    fprintf(stderr,"Unable to access the DataSource %s \n",pszFilename);
678#endif
679    setMapInMaps(conf,"lenv","message","gdalinfo failed - unable to open");
680    GDALDestroyDriverManager();
681    return -1;
682  }
683#ifdef DEBUGMS
684  fprintf(stderr,"Accessing the DataSource %s %d\n",pszFilename,__LINE__);
685#endif
686
687  /**
688   * Add a new layer set name, data
689   */
690  if(msGrowMapLayers(m)==NULL){
691    return -1;
692  }
693  if(initLayer((m->layers[m->numlayers]), m) == -1){
694    return -1;
695  }
696  m->layers[m->numlayers]->index=m->numlayers;
697
698  layerObj* myLayer=m->layers[m->numlayers];
699  myLayer->name = zStrdup(output->name);
700  myLayer->tileitem=NULL;
701  myLayer->data = zStrdup(pszFilename);
702  myLayer->index = m->numlayers;
703  myLayer->dump = MS_TRUE;
704  myLayer->status = MS_ON;
705  myLayer->type = MS_LAYER_RASTER;
706
707  char *title=output->name;
708  tmpMap=getMap(output->content,"title");
709  if(tmpMap!=NULL)
710    title=tmpMap->value;
711  char *abstract=output->name;
712  tmpMap=getMap(output->content,"abstract");
713  if(tmpMap!=NULL)
714    abstract=tmpMap->value;
715
716  msInsertHashTable(&(myLayer->metadata), "ows_label", title);
717  msInsertHashTable(&(myLayer->metadata), "ows_title", title);
718  msInsertHashTable(&(myLayer->metadata), "ows_abstract", abstract);
719  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_name", output->name);
720  msInsertHashTable(&(myLayer->metadata), "ows_rangeset_label", title);
721
722  /**
723   * Set Map Size to the raster size
724   */
725  m->width=GDALGetRasterXSize( hDataset );
726  m->height=GDALGetRasterYSize( hDataset );
727 
728  /**
729   * Set projection using Authority Code and Name if available or fallback to
730   * proj4 definition if available or fallback to default EPSG:4326
731   */
732  const char *tRef=GDALGetProjectionRef( hDataset );
733  if( tRef != NULL && strlen(tRef)>0 ){
734    char *pszProjection;
735    pszProjection = (char *) GDALGetProjectionRef( hDataset );
736    //#ifdef DEBUGMS
737    fprintf(stderr,"Accessing the DataSource %s\n",GDALGetProjectionRef( hDataset ));
738    //#endif
739    setSrsInformations(output,m,myLayer,pszProjection);
740  }else{
741    fprintf(stderr,"NO SRS FOUND ! %s\n",GDALGetProjectionRef( hDataset ));   
742  }
743
744
745  /**
746   * Set extent
747   */
748  if( GDALGetGeoTransform( hDataset, adfGeoTransform ) == CE_None ){
749    if( adfGeoTransform[2] == 0.0 && adfGeoTransform[4] == 0.0 ){
750
751      double minX = adfGeoTransform[0]
752        + adfGeoTransform[2] * GDALGetRasterYSize(hDataset);
753      double minY = adfGeoTransform[3]
754        + adfGeoTransform[5] * GDALGetRasterYSize(hDataset);
755
756      double maxX = adfGeoTransform[0]
757        + adfGeoTransform[1] * GDALGetRasterXSize(hDataset);
758      double maxY = adfGeoTransform[3]
759        + adfGeoTransform[4] * GDALGetRasterXSize(hDataset);
760
761       setMsExtent(output,m,myLayer,minX,minY,maxX,maxY);
762
763    }
764  }
765
766  /**
767   * Extract information about available bands to set the bandcount and the
768   * processing directive
769   */
770  char nBands[2];
771  int nBandsI=GDALGetRasterCount( hDataset );
772  sprintf(nBands,"%d",GDALGetRasterCount( hDataset ));
773  msInsertHashTable(&(myLayer->metadata), "ows_bandcount", nBands);
774  if(nBandsI>=3)
775    msLayerAddProcessing(myLayer,"BANDS=1,2,3");
776  else if(nBandsI>=2)
777    msLayerAddProcessing(myLayer,"BANDS=1,2");
778  else
779    msLayerAddProcessing(myLayer,"BANDS=1");
780
781  /**
782   * Name available Bands
783   */
784  char lBands[6];
785  char *nameBands=NULL;
786  for( iBand = 0; iBand < nBandsI; iBand++ ){
787    sprintf(lBands,"Band%d",iBand+1);
788    if(nameBands==NULL){
789      nameBands=(char*)malloc((strlen(lBands)+1)*sizeof(char));
790      sprintf(nameBands,"%s",lBands);
791    }else{
792      if(iBand<4){
793        char *tmpS=zStrdup(nameBands);
794        nameBands=(char*)realloc(nameBands,(strlen(nameBands)+strlen(lBands)+1)*sizeof(char));
795        sprintf(nameBands,"%s %s",tmpS,lBands);
796        free(tmpS);
797      }
798    }
799  }
800  msInsertHashTable(&(myLayer->metadata), "ows_bandnames", nameBands);
801 
802  /**
803   * Loops over metadata informations to setup specific informations
804   */
805  for( iBand = 0; iBand < nBandsI; iBand++ ){
806    //int         bGotNodata;//, bSuccess;
807    double      adfCMinMax[2]/*, dfNoData*/;
808    //int         nBlockXSize, nBlockYSize, nMaskFlags;
809    //double      /*dfMean, dfStdDev*/;
810    hBand = GDALGetRasterBand( hDataset, iBand+1 );
811
812    CPLErrorReset();
813    GDALComputeRasterMinMax( hBand, FALSE, adfCMinMax );
814    char tmpN[21];
815    sprintf(tmpN,"Band%d",iBand+1);
816    if (CPLGetLastErrorType() == CE_None){
817      char tmpMm[100];
818      sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
819      char tmpI[21];
820      sprintf(tmpI,"%s_interval",tmpN);
821      msInsertHashTable(&(myLayer->metadata), tmpI, tmpMm);
822
823      map* test=getMap(output->content,"msClassify");
824      if(test!=NULL && strncasecmp(test->value,"true",4)==0){
825        /**
826         * Classify one band raster pixel value using regular interval
827         */
828        int _tmpColors[10][3]={
829          {102,153,204},
830          {51,102,153},
831          {102,102,204},
832          {51,204,0},
833          {153,255,102},
834          {204,255,102},
835          {102,204,153},
836          {255,69,64},
837          {255,192,115},
838          {255,201,115}
839        };
840         
841        if(nBandsI==1){
842          double delta=adfCMinMax[1]-adfCMinMax[0];
843          double interval=delta/10;
844          double cstep=adfCMinMax[0];
845          for(i=0;i<10;i++){
846            /**
847             * Create a new class
848             */
849            if(msGrowLayerClasses(myLayer) == NULL)
850              return -1;
851            if(initClass((myLayer->CLASS[myLayer->numclasses])) == -1)
852              return -1;
853            myLayer->CLASS[myLayer->numclasses]->type = myLayer->type;
854            if(msGrowClassStyles(myLayer->CLASS[myLayer->numclasses]) == NULL)
855              return -1;
856            if(initStyle(myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]) == -1)
857              return -1;
858           
859            /**
860             * Set class name
861             */
862            char className[7];
863            sprintf(className,"class%d",i);
864            myLayer->CLASS[myLayer->numclasses]->name=zStrdup(className);
865           
866            /**
867             * Set expression
868             */
869            char expression[1024];
870            if(i+1<10)
871              sprintf(expression,"([pixel]>=%.3f AND [pixel]<%.3f)",cstep,cstep+interval);
872            else
873              sprintf(expression,"([pixel]>=%.3f AND [pixel]<=%.3f)",cstep,cstep+interval);
874            msLoadExpressionString(&myLayer->CLASS[myLayer->numclasses]->expression,expression);
875           
876            /**
877             * Set color
878             */
879            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.red=_tmpColors[i][0];
880            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.green=_tmpColors[i][1];
881            myLayer->CLASS[myLayer->numclasses]->styles[myLayer->CLASS[myLayer->numclasses]->numstyles]->color.blue=_tmpColors[i][2];
882            cstep+=interval;
883            myLayer->CLASS[myLayer->numclasses]->numstyles++;
884            myLayer->numclasses++;
885           
886          }
887         
888          char tmpMm[100];
889          sprintf(tmpMm,"%.3f %.3f",adfCMinMax[0],adfCMinMax[1]);
890         
891        }
892      }
893    }
894    if( strlen(GDALGetRasterUnitType(hBand)) > 0 ){
895      char tmpU[21];
896      sprintf(tmpU,"%s_band_uom",tmpN);
897      msInsertHashTable(&(myLayer->metadata), tmpU, GDALGetRasterUnitType(hBand));
898    }
899
900  }
901
902  m->layerorder[m->numlayers] = m->numlayers;
903  m->numlayers++;
904  GDALClose( hDataset );
905  GDALDestroyDriverManager();
906  CPLCleanupTLS();
907  return 1;
908}
909
910/**
911 * Create a MapFile for WMS, WFS or WCS Service output
912 */
913void outputMapfile(maps* conf,maps* outputs){
914
915  /**
916   * Firs store the value on disk
917   */
918  map* mime=getMap(outputs->content,"mimeType");
919  char *ext="data";
920  if(mime!=NULL)
921    if(strncasecmp(mime->value,"application/json",16)==0)
922      ext="json";
923
924  map* tmpMap=getMapFromMaps(conf,"main","dataPath");
925  map* sidMap=getMapFromMaps(conf,"lenv","usid");
926  char *pszDataSource=(char*)malloc((strlen(tmpMap->value)+strlen(sidMap->value)+strlen(outputs->name)+17)*sizeof(char));
927  sprintf(pszDataSource,"%s/ZOO_DATA_%s_%s.%s",tmpMap->value,outputs->name,sidMap->value,ext); 
928  int f=zOpen(pszDataSource,O_WRONLY|O_CREAT,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
929  map* sizeMap=getMap(outputs->content,"size");
930  map* vData=getMap(outputs->content,"value");
931  if(sizeMap!=NULL){
932    zWrite(f,vData->value,atoi(sizeMap->value)*sizeof(char));
933  }
934  else{
935    zWrite(f,vData->value,(strlen(vData->value)+1)*sizeof(char));
936  }
937  close(f);
938  addToMap(outputs->content,"storage",pszDataSource);
939
940  /*
941   * Create an empty map, set name, default size and extent
942   */
943  mapObj *myMap=msNewMapObj();
944  free(myMap->name);
945  myMap->name=zStrdup("ZOO-Project_WXS_Server");
946  msMapSetSize(myMap,2048,2048);
947  msMapSetExtent(myMap,-1,-1,1,1);
948 
949  /*
950   * Set imagepath and imageurl using tmpPath and tmpUrl from main.cfg
951   */
952  map *tmp1=getMapFromMaps(conf,"main","tmpPath");
953  myMap->web.imagepath=zStrdup(tmp1->value);
954  tmp1=getMapFromMaps(conf,"main","tmpUrl");
955  myMap->web.imageurl=zStrdup(tmp1->value);
956 
957  /*
958   * Define supported output formats
959   */
960  outputFormatObj *o1=msCreateDefaultOutputFormat(NULL,"AGG/PNG","png");
961  o1->imagemode=MS_IMAGEMODE_RGBA;
962  o1->transparent=MS_TRUE;
963  o1->inmapfile=MS_TRUE;
964  msAppendOutputFormat(myMap,msCloneOutputFormat(o1));
965  msFreeOutputFormat(o1);
966
967#ifdef USE_KML
968  outputFormatObj *o2=msCreateDefaultOutputFormat(NULL,"KML","kml");
969  o2->inmapfile=MS_TRUE; 
970  msAppendOutputFormat(myMap,msCloneOutputFormat(o2));
971  msFreeOutputFormat(o2);
972#endif
973
974  outputFormatObj *o3=msCreateDefaultOutputFormat(NULL,"GDAL/GTiff","tiff");
975  if(!o3)
976    fprintf(stderr,"Unable to initialize GDAL driver !\n");
977  else{
978    o3->imagemode=MS_IMAGEMODE_BYTE;
979    o3->inmapfile=MS_TRUE; 
980    msAppendOutputFormat(myMap,msCloneOutputFormat(o3));
981    msFreeOutputFormat(o3);
982  }
983
984  outputFormatObj *o4=msCreateDefaultOutputFormat(NULL,"GDAL/AAIGRID","grd");
985  if(!o4)
986    fprintf(stderr,"Unable to initialize GDAL driver !\n");
987  else{
988    o4->imagemode=MS_IMAGEMODE_INT16;
989    o4->inmapfile=MS_TRUE; 
990    msAppendOutputFormat(myMap,msCloneOutputFormat(o4));
991    msFreeOutputFormat(o4);
992  }
993
994#ifdef USE_CAIRO
995  outputFormatObj *o5=msCreateDefaultOutputFormat(NULL,"CAIRO/PNG","cairopng");
996  if(!o5)
997    fprintf(stderr,"Unable to initialize CAIRO driver !\n");
998  else{
999    o5->imagemode=MS_IMAGEMODE_RGBA;
1000    o5->transparent=MS_TRUE;
1001    o5->inmapfile=MS_TRUE;
1002    msAppendOutputFormat(myMap,msCloneOutputFormat(o5));
1003    msFreeOutputFormat(o5);
1004  }
1005#endif
1006
1007  /*
1008   * Set default projection to EPSG:4326
1009   */
1010  msLoadProjectionStringEPSG(&myMap->projection,"EPSG:4326");
1011  myMap->transparent=1;
1012
1013  /**
1014   * Set metadata extracted from main.cfg file maps
1015   */
1016  maps* cursor=conf;
1017  map* correspondance=getCorrespondance();
1018  while(cursor!=NULL){
1019    map* _cursor=cursor->content;
1020    map* vMap;
1021    while(_cursor!=NULL){
1022      if((vMap=getMap(correspondance,_cursor->name))!=NULL){
1023        if (msInsertHashTable(&(myMap->web.metadata), vMap->value, _cursor->value) == NULL){
1024#ifdef DEBUGMS
1025          fprintf(stderr,"Unable to add metadata");
1026#endif
1027          return;
1028        }
1029      }
1030      _cursor=_cursor->next;
1031    }
1032    cursor=cursor->next;
1033  }
1034
1035  /*
1036   * Set mapserver PROJ_LIB/GDAL_DATA or any other config parameter from
1037   * the main.cfg [mapserver] section if any
1038   */
1039  maps *tmp3=getMaps(conf,"mapserver");
1040  if(tmp3!=NULL){
1041    map* tmp4=tmp3->content;
1042    while(tmp4!=NULL){
1043      msSetConfigOption(myMap,tmp4->name,tmp4->value);
1044      tmp4=tmp4->next;
1045    }
1046  }
1047
1048  /**
1049   * Set a ows_rootlayer_title, 
1050   */
1051  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_name", "ZOO_Project_Layer") == NULL){
1052#ifdef DEBUGMS
1053    fprintf(stderr,"Unable to add metadata");
1054#endif
1055    return;
1056  }
1057  if (msInsertHashTable(&(myMap->web.metadata), "ows_rootlayer_title", "ZOO_Project_Layer") == NULL){
1058#ifdef DEBUGMS
1059    fprintf(stderr,"Unable to add metadata");
1060#endif
1061    return;
1062  }
1063
1064  /**
1065   * Enable all the WXS requests using ows_enable_request
1066   * see http://mapserver.org/trunk/development/rfc/ms-rfc-67.html
1067   */
1068  if (msInsertHashTable(&(myMap->web.metadata), "ows_enable_request", "*") == NULL){
1069#ifdef DEBUGMS
1070    fprintf(stderr,"Unable to add metadata");
1071#endif
1072    return;
1073  }
1074  msInsertHashTable(&(myMap->web.metadata), "ows_srs", "EPSG:4326");
1075
1076  if(tryOgr(conf,outputs,myMap)<0)
1077    if(tryGdal(conf,outputs,myMap)<0)
1078      return ;
1079
1080  tmp1=getMapFromMaps(conf,"main","dataPath");
1081  char *tmpPath=(char*)malloc((13+strlen(tmp1->value))*sizeof(char));
1082  sprintf(tmpPath,"%s/symbols.sym",tmp1->value);
1083  msInitSymbolSet(&myMap->symbolset);
1084  myMap->symbolset.filename=zStrdup(tmpPath);
1085  free(tmpPath);
1086
1087  map* sid=getMapFromMaps(conf,"lenv","usid");
1088  char *mapPath=
1089    (char*)malloc((7+strlen(sid->value)+strlen(outputs->name)+strlen(tmp1->value))*sizeof(char));
1090  sprintf(mapPath,"%s/%s_%s.map",tmp1->value,outputs->name,sid->value);
1091  msSaveMap(myMap,mapPath);
1092  msFreeMap(myMap);
1093}
1094
1095#endif
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