mapwcs11.c 57.3 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * Project:  MapServer
 * Purpose:  OpenGIS Web Coverage Server (WCS) 1.1.0 Implementation.  This
 *           file holds some WCS 1.1.0 specific functions but other parts
 *           are still implemented in mapwcs.c.
 * Author:   Frank Warmerdam and the MapServer team.
 *
 ******************************************************************************
 * Copyright (c) 2007, Frank Warmerdam
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
20
 * The above copyright notice and this permission notice shall be included in
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 * all copies of this Software or works derived from this Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *****************************************************************************/

#include <assert.h>
#include "mapserver.h"
#include "maperror.h"
#include "mapthread.h"
#include "mapwcs.h"



40
#if defined(USE_WCS_SVR)
41 42 43
#include "mapwcs.h"
#include "gdal.h"
#include "cpl_string.h" /* GDAL string handling */
44
#endif
45

46 47 48 49 50
#if defined(USE_LIBXML2)
#include "maplibxml2.h"
#endif

#if defined(USE_WCS_SVR) && defined(USE_LIBXML2)
51 52 53 54 55 56
/*
** msWCSException11()
**
** Report current MapServer error in XML exception format.
** Wrapper function around msOWSCommonExceptionReport. Merely
** passes WCS specific info.
57
**
58 59
*/

60 61 62
int msWCSException11(mapObj *map, const char *locator,
                     const char *exceptionCode, const char *version)
{
63 64 65 66 67 68
  int size = 0;
  char *errorString     = NULL;
  char *errorMessage    = NULL;
  char *schemasLocation = NULL;
  const char * encoding;

69
  xmlDocPtr  psDoc      = NULL;
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  xmlNodePtr psRootNode = NULL;
  xmlNsPtr   psNsOws    = NULL;
  xmlChar *buffer       = NULL;

  psNsOws = xmlNewNs(NULL, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");

  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
  errorString = msGetErrorString("\n");
  errorMessage = msEncodeHTMLEntities(errorString);
  schemasLocation = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));

  psDoc = xmlNewDoc(BAD_CAST "1.0");

  psRootNode = msOWSCommonExceptionReport(psNsOws, OWS_1_1_0, schemasLocation, version, msOWSGetLanguage(map, "exception"), exceptionCode, locator, errorMessage);

  xmlDocSetRootElement(psDoc, psRootNode);

87
  xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/ows/1.1", BAD_CAST "ows");
88 89

  if (encoding)
90
    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
91
  else
92 93
    msIO_setHeader("Content-Type","text/xml");
  msIO_sendHeaders();
94 95

  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
96

97 98 99 100 101 102 103 104
  msIO_printf("%s", buffer);

  /*free buffer and the document */
  free(errorString);
  free(errorMessage);
  free(schemasLocation);
  xmlFree(buffer);
  xmlFreeDoc(psDoc);
105
  xmlFreeNs(psNsOws);
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

  /* clear error since we have already reported it */
  msResetErrorList();

  return MS_FAILURE;
}

/************************************************************************/
/*                       msWCSGetFormatsList11()                        */
/*                                                                      */
/*      Fetch back a comma delimited formats list for the past layer    */
/*      if one is supplied, otherwise for all formats supported by      */
/*      the server.  Formats should be identified by mime type.         */
/************************************************************************/

static char *msWCSGetFormatsList11( mapObj *map, layerObj *layer )

{
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
  char *format_list = msStrdup("");
  char **tokens = NULL, **formats = NULL;
  int  i, numtokens = 0, numformats;
  char *value;

  msApplyDefaultOutputFormats(map);

  /* -------------------------------------------------------------------- */
  /*      Parse from layer metadata.                                      */
  /* -------------------------------------------------------------------- */
  if( layer != NULL
      && (value = msOWSGetEncodeMetadata( &(layer->metadata),"CO","formats",
                                          "GTiff" )) != NULL ) {
    tokens = msStringSplit(value, ' ', &numtokens);
    msFree(value);
  }

  /* -------------------------------------------------------------------- */
  /*      Parse from map.web metadata.                                    */
  /* -------------------------------------------------------------------- */
  else if((value = msOWSGetEncodeMetadata( &(map->web.metadata), "CO", "formats",
                                           NULL)) != NULL ) {
    tokens = msStringSplit(value, ' ', &numtokens);
    msFree(value);
  }

  /* -------------------------------------------------------------------- */
  /*      Or generate from all configured raster output formats that      */
  /*      look plausible.                                                 */
  /* -------------------------------------------------------------------- */
  else {
    tokens = (char **) calloc(map->numoutputformats,sizeof(char*));
    for( i = 0; i < map->numoutputformats; i++ ) {
      switch( map->outputformatlist[i]->renderer ) {
          /* seeminly normal raster format */
#ifdef USE_GD
        case MS_RENDER_WITH_GD:
#endif
        case MS_RENDER_WITH_AGG:
        case MS_RENDER_WITH_RAWDATA:
          tokens[numtokens++] = msStrdup(map->outputformatlist[i]->name);
          break;

          /* rest of formats aren't really WCS compatible */
        default:
          break;

      }
172
    }
173
  }
174

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  /* -------------------------------------------------------------------- */
  /*      Convert outputFormatObj names into mime types and remove        */
  /*      duplicates.                                                     */
  /* -------------------------------------------------------------------- */
  numformats = 0;
  formats = (char **) calloc(sizeof(char*),numtokens);

  for( i = 0; i < numtokens; i++ ) {
    int format_i, j;
    const char *mimetype;

    for( format_i = 0; format_i < map->numoutputformats; format_i++ ) {
      if( strcasecmp(map->outputformatlist[format_i]->name,
                     tokens[i]) == 0 )
        break;
190 191
    }

192 193 194 195 196

    if( format_i == map->numoutputformats ) {
      msDebug("Failed to find outputformat info on format '%s', ignore.\n",
              tokens[i] );
      continue;
197 198
    }

199 200 201 202 203 204
    mimetype = map->outputformatlist[format_i]->mimetype;
    if( mimetype == NULL || strlen(mimetype) == 0 ) {
      msDebug("No mimetime for format '%s', ignoring.\n",
              tokens[i] );
      continue;
    }
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
    for( j = 0; j < numformats; j++ ) {
      if( strcasecmp(mimetype,formats[j]) == 0 )
        break;
    }

    if( j < numformats ) {
      msDebug( "Format '%s' ignored since mimetype '%s' duplicates another outputFormatObj.\n",
               tokens[i], mimetype );
      continue;
    }

    formats[numformats++] = msStrdup(mimetype);
  }

  msFreeCharArray(tokens,numtokens);

  /* -------------------------------------------------------------------- */
  /*      Turn mimetype list into comma delimited form for easy use       */
  /*      with xml functions.                                             */
  /* -------------------------------------------------------------------- */
  for(i=0; i<numformats; i++) {
    if(i > 0) {
      format_list = msStringConcatenate(format_list, (char *) ",");
229
    }
230 231 232
    format_list = msStringConcatenate(format_list, formats[i]);
  }
  msFreeCharArray(formats,numformats);
233

234
  return format_list;
235 236 237 238 239 240 241 242 243
}

/************************************************************************/
/*                msWCSGetCapabilities11_CoverageSummary()              */
/*                                                                      */
/*      Generate a WCS 1.1 CoverageSummary.                             */
/************************************************************************/

static int msWCSGetCapabilities11_CoverageSummary(
244 245
  mapObj *map, wcsParamsObj *params, cgiRequestObj *req,
  xmlDocPtr doc, xmlNodePtr psContents, layerObj *layer )
246 247

{
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  coverageMetadataObj cm;
  int status;
  const char *value;
  char *owned_value;
  char *format_list;
  xmlNodePtr psCSummary;
  xmlNsPtr psOwsNs = xmlSearchNs( doc, psContents, BAD_CAST "ows" );
  char **tokens = NULL;
  int i = 0;
  int n = 0;

  status = msWCSGetCoverageMetadata(layer, &cm);
  if(status != MS_SUCCESS) return MS_FAILURE;

  psCSummary = xmlNewChild( psContents, NULL, BAD_CAST "CoverageSummary", NULL );

  /* -------------------------------------------------------------------- */
  /*      Title (from description)                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
  if( value == NULL )
    value = msOWSLookupMetadata( &(layer->metadata), "CO", "title");
  if( value == NULL )
    value = layer->name;
  xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Title", BAD_CAST value );

  /* -------------------------------------------------------------------- */
  /*      Abstract                                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
  xmlNewChild( psCSummary, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );

  /* -------------------------------------------------------------------- */
  /*      Keywords                                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");

  if (value) {
    xmlNodePtr psNode;

    psNode = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Keywords", NULL);

    tokens = msStringSplit(value, ',', &n);
    if (tokens && n > 0) {
      for (i=0; i<n; i++) {
        xmlNewChild(psNode, NULL, BAD_CAST "Keyword", BAD_CAST tokens[i] );
      }
      msFreeCharArray(tokens, n);
296
    }
297
  }
298

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  /* -------------------------------------------------------------------- */
  /*      Metadata Link                                                   */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href");

  if (value) {
    xmlNodePtr psMetadata = xmlNewChild(psCSummary, psOwsNs, BAD_CAST "Metadata", NULL);
    xmlNsPtr psXlinkNs = xmlSearchNs( doc, xmlDocGetRootElement(doc), BAD_CAST "xlink" );
    const char *metadatalink_type = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_type");
    const char *metadatalink_format = msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_format");

    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "type", BAD_CAST "simple");
    xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "href", BAD_CAST value);
    if (metadatalink_type != NULL) {
      xmlNewProp(psMetadata, BAD_CAST "about", BAD_CAST metadatalink_type);
    }
    if (metadatalink_format != NULL) {
      xmlNewNsProp(psMetadata, psXlinkNs, BAD_CAST "role", BAD_CAST metadatalink_format);
317
    }
318
  }
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333
  /* -------------------------------------------------------------------- */
  /*      WGS84 bounding box.                                             */
  /* -------------------------------------------------------------------- */
  xmlAddChild(
    psCSummary,
    msOWSCommonWGS84BoundingBox( psOwsNs, 2,
                                 cm.llextent.minx, cm.llextent.miny,
                                 cm.llextent.maxx, cm.llextent.maxy ));

  /* -------------------------------------------------------------------- */
  /*      Supported CRSes.                                                */
  /* -------------------------------------------------------------------- */
  if( (owned_value =
         msOWSGetProjURN( &(layer->projection), &(layer->metadata),
334
                          "CO", MS_FALSE)) != NULL ) {
335 336 337 338
    /* ok */
  } else if((owned_value =
               msOWSGetProjURN( &(layer->map->projection),
                                &(layer->map->web.metadata),
339
                                "CO", MS_FALSE)) != NULL ) {
340 341 342
    /* ok */
  } else
    msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");
343

344 345 346
  if( owned_value != NULL && strlen(owned_value) > 0 )
    msLibXml2GenerateList( psCSummary, NULL, "SupportedCRS",
                           owned_value, ' ' );
347

348
  msFree( owned_value );
349

350 351 352 353
  /* -------------------------------------------------------------------- */
  /*      SupportedFormats                                                */
  /* -------------------------------------------------------------------- */
  format_list = msWCSGetFormatsList11( map, layer );
354

355 356 357
  if (strlen(format_list) > 0 )
    msLibXml2GenerateList( psCSummary, NULL, "SupportedFormat",
                           format_list, ',' );
358

359 360 361 362 363 364 365 366
  msFree( format_list );

  /* -------------------------------------------------------------------- */
  /*      Identifier (layer name)                                         */
  /* -------------------------------------------------------------------- */
  xmlNewChild( psCSummary, NULL, BAD_CAST "Identifier", BAD_CAST layer->name );

  return MS_SUCCESS;
367 368 369 370 371
}

/************************************************************************/
/*                       msWCSGetCapabilities11()                       */
/************************************************************************/
372
int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
373
                           cgiRequestObj *req, owsRequestObj *ows_request)
374
{
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  xmlDocPtr psDoc = NULL;       /* document pointer */
  xmlNodePtr psRootNode, psMainNode, psNode;
  char *identifier_list = NULL, *format_list = NULL;
  const char *updatesequence=NULL;
  const char *encoding;
  xmlNsPtr psOwsNs, psXLinkNs;
  char *schemaLocation = NULL;
  char *xsi_schemaLocation = NULL;
  char *script_url=NULL, *script_url_encoded=NULL;

  xmlChar *buffer = NULL;
  int size = 0, i;
  msIOContext *context = NULL;

  int ows_version = OWS_1_1_0;

  /* -------------------------------------------------------------------- */
  /*      Handle updatesequence                                           */
  /* -------------------------------------------------------------------- */

  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
397

398 399 400 401 402 403 404 405 406 407 408
  if (params->updatesequence != NULL) {
    i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
    if (i == 0) { /* current */
      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
      return msWCSException11(map, "updatesequence", "CurrentUpdateSequence", params->version);
    }
    if (i > 0) { /* invalid */
      msSetError(MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)", "msWCSGetCapabilities11()", params->updatesequence, updatesequence);
      return msWCSException11(map, "updatesequence", "InvalidUpdateSequence", params->version);
    }
  }
409

410 411 412 413 414 415 416
  /* -------------------------------------------------------------------- */
  /*      Build list of layer identifiers available.                      */
  /* -------------------------------------------------------------------- */
  identifier_list = msStrdup("");
  for(i=0; i<map->numlayers; i++) {
    layerObj *layer = map->layers[i];
    int       new_length;
417

418 419
    if(!msWCSIsLayerSupported(layer))
      continue;
420

421 422
    new_length = strlen(identifier_list) + strlen(layer->name) + 2;
    identifier_list = (char *) realloc(identifier_list,new_length);
423

424 425 426 427
    if( strlen(identifier_list) > 0 )
      strcat( identifier_list, "," );
    strcat( identifier_list, layer->name );
  }
428

429 430 431 432
  /* -------------------------------------------------------------------- */
  /*      Create document.                                                */
  /* -------------------------------------------------------------------- */
  psDoc = xmlNewDoc(BAD_CAST "1.0");
433

434
  psRootNode = xmlNewNode(NULL, BAD_CAST "Capabilities");
435

436
  xmlDocSetRootElement(psDoc, psRootNode);
437

438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  /* -------------------------------------------------------------------- */
  /*      Name spaces                                                     */
  /* -------------------------------------------------------------------- */
  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
  psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
  psXLinkNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );

  /*xmlNewProp(psRootNode, BAD_CAST " */
  xmlNewProp(psRootNode, BAD_CAST "version", BAD_CAST params->version );

  updatesequence = msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");

  if (updatesequence)
    xmlNewProp(psRootNode, BAD_CAST "updateSequence", BAD_CAST updatesequence);

  schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
  xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsGetCapabilities.xsd ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
  msFree(schemaLocation);
  msFree(xsi_schemaLocation);

  /* -------------------------------------------------------------------- */
  /*      Service metadata.                                               */
  /* -------------------------------------------------------------------- */
  if( params->section == NULL
      || strstr(params->section,"All") != NULL
      || strstr(params->section,"ServiceIdentification") != NULL ) {
    xmlAddChild(psRootNode, msOWSCommonServiceIdentification(
                              psOwsNs, map, "OGC WCS", params->version, "CO"));
  }
477

478 479 480 481 482 483 484
  /*service provider*/
  if( params->section == NULL
      || strstr(params->section,"All") != NULL
      || strstr(params->section,"ServiceProvider") != NULL ) {
    xmlAddChild(psRootNode, msOWSCommonServiceProvider(
                              psOwsNs, psXLinkNs, map, "CO"));
  }
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
  /* -------------------------------------------------------------------- */
  /*      Operations metadata.                                            */
  /* -------------------------------------------------------------------- */
  /*operation metadata */
  if ((script_url=msOWSGetOnlineResource(map, "CO", "onlineresource", req)) == NULL
      || (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
    msSetError(MS_WCSERR, "Server URL not found", "msWCSGetCapabilities11()");
    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
  }
  free( script_url );

  if( params->section == NULL
      || strstr(params->section,"All") != NULL
      || strstr(params->section,"OperationsMetadata") != NULL ) {
    psMainNode= xmlAddChild(psRootNode,msOWSCommonOperationsMetadata(psOwsNs));

    /* -------------------------------------------------------------------- */
    /*      GetCapabilities - add Sections and AcceptVersions?              */
    /* -------------------------------------------------------------------- */
    psNode = msOWSCommonOperationsMetadataOperation(
               psOwsNs, psXLinkNs,
               "GetCapabilities", OWS_METHOD_GETPOST, script_url_encoded);

    xmlAddChild(psMainNode, psNode);
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                  ows_version, psOwsNs, "Parameter", "service", "WCS"));
    xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                  ows_version, psOwsNs, "Parameter", "version", (char *)params->version));

    /* -------------------------------------------------------------------- */
    /*      DescribeCoverage                                                */
    /* -------------------------------------------------------------------- */
    if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE)) {
      psNode = msOWSCommonOperationsMetadataOperation(
                 psOwsNs, psXLinkNs,
                 "DescribeCoverage", OWS_METHOD_GETPOST, script_url_encoded);

      xmlAddChild(psMainNode, psNode);
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "service", "WCS"));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "identifiers", identifier_list ));
530 531
    }

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
    /* -------------------------------------------------------------------- */
    /*      GetCoverage                                                     */
    /* -------------------------------------------------------------------- */
    if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE)) {

      psNode = msOWSCommonOperationsMetadataOperation(
                 psOwsNs, psXLinkNs,
                 "GetCoverage", OWS_METHOD_GETPOST, script_url_encoded);

      format_list = msWCSGetFormatsList11( map, NULL );

      xmlAddChild(psMainNode, psNode);
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "service", "WCS"));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "version", (char *)params->version));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "Identifier", identifier_list ));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "InterpolationType",
                    "NEAREST_NEIGHBOUR,BILINEAR" ));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "format", format_list ));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "store", "false" ));
      xmlAddChild(psNode, msOWSCommonOperationsMetadataDomainType(
                    ows_version, psOwsNs, "Parameter", "GridBaseCRS",
                    "urn:ogc:def:crs:epsg::4326" ));

      msFree( format_list );
562
    }
563
  }
564

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
  /* -------------------------------------------------------------------- */
  /*      Contents section.                                               */
  /* -------------------------------------------------------------------- */
  if( params->section == NULL
      || strstr(params->section,"All") != NULL
      || strstr(params->section,"Contents") != NULL ) {
    psMainNode = xmlNewChild( psRootNode, NULL, BAD_CAST "Contents", NULL );

    if(ows_request->numlayers == 0) {
      xmlAddChild(psMainNode,
                  xmlNewComment(BAD_CAST "WARNING: No WCS layers are enabled. "
                                "Check wcs/ows_enable_request settings."));
    } else {
      for(i=0; i<map->numlayers; i++) {
        layerObj *layer = map->layers[i];
        int       status;

        if(!msWCSIsLayerSupported(layer))
          continue;

        if (!msIntegerInArray(layer->index, ows_request->enabled_layers, ows_request->numlayers))
          continue;

        status = msWCSGetCapabilities11_CoverageSummary(
                   map, params, req, psDoc, psMainNode, layer );
        if(status != MS_SUCCESS) return MS_FAILURE;
      }
592
    }
593
  }
594

595 596 597
  /* -------------------------------------------------------------------- */
  /*      Write out the document.                                         */
  /* -------------------------------------------------------------------- */
598

599 600
  if( msIO_needBinaryStdout() == MS_FAILURE )
    return MS_FAILURE;
601

602 603 604 605 606 607 608 609 610 611 612
  if (encoding)
    msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
  else
    msIO_setHeader("Content-Type","text/xml");
  msIO_sendHeaders();

  context = msIO_getHandler(stdout);

  xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
  msIO_contextWrite(context, buffer, size);
  xmlFree(buffer);
613

614 615 616
  /*free buffer and the document */
  /*xmlFree(buffer);*/
  xmlFreeDoc(psDoc);
617

618
  xmlCleanupParser();
619

620 621 622
  /* clean up */
  free( script_url_encoded );
  free( identifier_list );
623

624
  return(MS_SUCCESS);
625 626 627 628 629 630
}

/************************************************************************/
/*            msWCSDescribeCoverage_CoverageDescription11()             */
/************************************************************************/

631
static int
632
msWCSDescribeCoverage_CoverageDescription11(
633 634
  layerObj *layer, wcsParamsObj *params, xmlNodePtr psRootNode,
  xmlNsPtr psOwsNs )
635 636

{
637 638 639 640 641 642 643 644 645 646 647 648 649
  int status;
  coverageMetadataObj cm;
  xmlNodePtr psCD, psDomain, psSD, psGridCRS;
  const char *value;

  /* -------------------------------------------------------------------- */
  /*      Verify layer is processable.                                    */
  /* -------------------------------------------------------------------- */
  if( msCheckParentPointer(layer->map,"map") == MS_FAILURE )
    return MS_FAILURE;

  if(!msWCSIsLayerSupported(layer))
    return MS_SUCCESS;
650

651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
  /* -------------------------------------------------------------------- */
  /*      Setup coverage metadata.                                        */
  /* -------------------------------------------------------------------- */
  status = msWCSGetCoverageMetadata(layer, &cm);
  if(status != MS_SUCCESS) return status;

  /* fill in bands rangeset info, if required.  */
  msWCSSetDefaultBandsRangeSetInfo( params, &cm, layer );

  /* -------------------------------------------------------------------- */
  /*      Create CoverageDescription node.                                */
  /* -------------------------------------------------------------------- */
  psCD = xmlNewChild( psRootNode, NULL, BAD_CAST "CoverageDescription", NULL );

  /* -------------------------------------------------------------------- */
  /*      Title (from description)                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata( &(layer->metadata), "CO", "description");
  if( value == NULL )
    value = layer->name;
  xmlNewChild( psCD, psOwsNs, BAD_CAST "Title", BAD_CAST value );

  /* -------------------------------------------------------------------- */
  /*      Abstract                                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata( &(layer->metadata), "CO", "abstract");
  xmlNewChild( psCD, psOwsNs, BAD_CAST "Abstract", BAD_CAST value );

  /* -------------------------------------------------------------------- */
  /*      Keywords                                                        */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata(&(layer->metadata), "CO", "keywordlist");

  if (value)
    msLibXml2GenerateList(
      xmlNewChild(psCD, psOwsNs, BAD_CAST "Keywords", NULL),
      NULL, "Keyword", value, ',' );

  /* -------------------------------------------------------------------- */
  /*      Identifier (layer name)                                         */
  /* -------------------------------------------------------------------- */
  xmlNewChild( psCD, NULL, BAD_CAST "Identifier", BAD_CAST layer->name);

  /* -------------------------------------------------------------------- */
  /*      Domain                                                          */
  /* -------------------------------------------------------------------- */
  psDomain = xmlNewChild( psCD, NULL, BAD_CAST "Domain", NULL );

  /* -------------------------------------------------------------------- */
  /*      SpatialDomain                                                   */
  /* -------------------------------------------------------------------- */
  psSD = xmlNewChild( psDomain, NULL, BAD_CAST "SpatialDomain", NULL );

  /* -------------------------------------------------------------------- */
  /*      imageCRS bounding box.                                          */
  /* -------------------------------------------------------------------- */
  xmlAddChild(
    psSD,
    msOWSCommonBoundingBox( psOwsNs, "urn:ogc:def:crs:OGC::imageCRS",
                            2, 0, 0, cm.xsize-1, cm.ysize-1 ));

  /* -------------------------------------------------------------------- */
  /*      native CRS bounding box.                                        */
  /* -------------------------------------------------------------------- */
  xmlAddChild(
    psSD,
    msOWSCommonBoundingBox( psOwsNs, cm.srs_urn, 2,
                            cm.extent.minx, cm.extent.miny,
                            cm.extent.maxx, cm.extent.maxy ));

  /* -------------------------------------------------------------------- */
  /*      WGS84 bounding box.                                             */
  /* -------------------------------------------------------------------- */
  xmlAddChild(
    psSD,
    msOWSCommonWGS84BoundingBox( psOwsNs, 2,
                                 cm.llextent.minx, cm.llextent.miny,
                                 cm.llextent.maxx, cm.llextent.maxy ));

  /* -------------------------------------------------------------------- */
  /*      GridCRS                                                         */
  /* -------------------------------------------------------------------- */
  {
    char format_buf[500];

    psGridCRS = xmlNewChild( psSD, NULL, BAD_CAST "GridCRS", NULL );


    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridBaseCRS", BAD_CAST cm.srs_urn );
    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridType",
                 BAD_CAST "urn:ogc:def:method:WCS:1.1:2dSimpleGrid" );

    sprintf( format_buf, "%.15g %.15g",
             cm.geotransform[0]+cm.geotransform[1]/2+cm.geotransform[2]/2,
             cm.geotransform[3]+cm.geotransform[4]/2+cm.geotransform[5]/2);
    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOrigin", BAD_CAST format_buf );

    sprintf( format_buf, "%.15g %.15g",
             cm.geotransform[1], cm.geotransform[5] );
    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridOffsets", BAD_CAST format_buf );

    xmlNewChild( psGridCRS, NULL, BAD_CAST "GridCS",
                 BAD_CAST "urn:ogc:def:cs:OGC:0.0:Grid2dSquareCS" );
  }
755 756 757 758 759 760 761



#ifdef notdef
  /* TemporalDomain */

  /* TODO: figure out when a temporal domain is valid, for example only tiled rasters support time as a domain, plus we need a timeitem */
762
  if(msOWSLookupMetadata(&(layer->metadata), "CO", "timeposition") || msOWSLookupMetadata(&(layer->metadata), "CO", "timeperiod")) {
763 764 765
    msIO_printf("      <temporalDomain>\n");

    /* TimePosition (should support a value AUTO, then we could mine positions from the timeitem) */
766
    msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL, "        <gml:timePosition>%s</gml:timePosition>\n", NULL);
767 768 769 770 771

    /* TODO:  add TimePeriod (only one per layer)  */

    msIO_printf("      </temporalDomain>\n");
  }
772

773 774 775
  msIO_printf("    </domainSet>\n");
#endif

776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  /* -------------------------------------------------------------------- */
  /*      Range                                                           */
  /* -------------------------------------------------------------------- */
  {
    xmlNodePtr psField, psInterpMethods, psAxis;
    char *value;

    psField =
      xmlNewChild(
        xmlNewChild( psCD, NULL, BAD_CAST "Range", NULL ),
        NULL, BAD_CAST "Field", NULL );

    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
                                    "rangeset_label", NULL );
    if( value )
      xmlNewChild( psField, psOwsNs, BAD_CAST "Title", BAD_CAST value );
    msFree(value);

    /* ows:Abstract? TODO */

    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
                                    "rangeset_name", "raster" );
    xmlNewChild( psField, NULL, BAD_CAST "Identifier", BAD_CAST value );
    msFree(value);

    xmlNewChild(
        xmlNewChild( psField, NULL, BAD_CAST "Definition", NULL ),
        psOwsNs, BAD_CAST "AnyValue", NULL );

    /* NullValue */
    value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
                                    "rangeset_nullvalue", NULL);
    if( value )
      xmlNewChild( psField, NULL, BAD_CAST "NullValue",
                   BAD_CAST value );
    msFree(value);

    /* InterpolationMethods */
    psInterpMethods =
      xmlNewChild( psField, NULL, BAD_CAST "InterpolationMethods", NULL );

    xmlNewChild( psInterpMethods, NULL, BAD_CAST "InterpolationMethod", BAD_CAST "bilinear" );
    xmlNewChild( psInterpMethods, NULL,
                 BAD_CAST "Default", BAD_CAST "nearest neighbor" );

    /* -------------------------------------------------------------------- */
    /*      Bands axis.                                                     */
    /* -------------------------------------------------------------------- */
824
    {
825 826
      xmlNodePtr psKeys;
      int iBand;
827

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
      value = msOWSGetEncodeMetadata( &(layer->metadata), "CO",
                                      "bands_name", "bands" );
      psAxis = xmlNewChild( psField, NULL, BAD_CAST "Axis", NULL );
      xmlNewProp( psAxis, BAD_CAST "identifier", BAD_CAST value );
      msFree(value);

      psKeys = xmlNewChild( psAxis, NULL, BAD_CAST
                            "AvailableKeys",  NULL );

      for( iBand = 0; iBand < cm.bandcount; iBand++ ) {
        char szBandName[32];

        snprintf( szBandName, sizeof(szBandName), "%d", iBand+1 );
        xmlNewChild( psKeys, NULL, BAD_CAST "Key",
                     BAD_CAST szBandName );
      }
844
    }
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
  }

  /* -------------------------------------------------------------------- */
  /*      SupportedCRS                                                    */
  /* -------------------------------------------------------------------- */
  {
    char *owned_value;

    if( (owned_value =
           msOWSGetProjURN( &(layer->projection), &(layer->metadata),
                            "CO", MS_FALSE)) != NULL ) {
      /* ok */
    } else if((owned_value =
                 msOWSGetProjURN( &(layer->map->projection),
                                  &(layer->map->web.metadata),
                                  "CO", MS_FALSE)) != NULL ) {
      /* ok */
    } else
      msDebug( "mapwcs.c: missing required information, no SRSs defined.\n");

    if( owned_value != NULL && strlen(owned_value) > 0 )
      msLibXml2GenerateList( psCD, NULL, "SupportedCRS",
                             owned_value, ' ' );

    msFree( owned_value );
  }

  /* -------------------------------------------------------------------- */
  /*      SupportedFormats                                                */
  /* -------------------------------------------------------------------- */
  {
    char *format_list;

    format_list = msWCSGetFormatsList11( layer->map, layer );

    if (strlen(format_list) > 0 )
      msLibXml2GenerateList( psCD, NULL, "SupportedFormat",
                             format_list, ',' );

    msFree( format_list );
  }

  return MS_SUCCESS;
888 889 890 891 892 893
}

/************************************************************************/
/*                      msWCSDescribeCoverage11()                       */
/************************************************************************/

894
int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params, owsRequestObj *ows_request)
895
{
896 897 898 899 900 901 902 903 904 905
  xmlDocPtr psDoc = NULL;       /* document pointer */
  xmlNodePtr psRootNode;
  xmlNsPtr psOwsNs;
  char *schemaLocation = NULL;
  char *xsi_schemaLocation = NULL;
  const char *encoding;

  int i,j;

  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");
906

907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
  /* -------------------------------------------------------------------- */
  /*      We will actually get the coverages list as a single item in     */
  /*      a string list with that item having the comma delimited         */
  /*      coverage names.  Split it up now, and assign back in place      */
  /*      of the old coverages list.                                      */
  /* -------------------------------------------------------------------- */
  if( CSLCount(params->coverages) == 1 ) {
    char **old_coverages = params->coverages;
    params->coverages = CSLTokenizeStringComplex( old_coverages[0], ",",
                        FALSE, FALSE );
    CSLDestroy( old_coverages );
  }

  /* -------------------------------------------------------------------- */
  /*      Validate that the requested coverages exist as named layers.    */
  /* -------------------------------------------------------------------- */
  if(params->coverages) { /* use the list */
    for( j = 0; params->coverages[j]; j++ ) {
      i = msGetLayerIndex(map, params->coverages[j]);
      if ( (i == -1) ||
           (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers)) ) {
        msSetError( MS_WCSERR,
                    "COVERAGE %s cannot be opened / does not exist",
                    "msWCSDescribeCoverage()", params->coverages[j]);
        return msWCSException11(map, "coverage", "CoverageNotDefined", params->version);
      }
933
    }
934 935 936 937 938 939 940 941
  }

  /* -------------------------------------------------------------------- */
  /*      Create document.                                                */
  /* -------------------------------------------------------------------- */
  psDoc = xmlNewDoc(BAD_CAST "1.0");

  psRootNode = xmlNewNode(NULL, BAD_CAST "CoverageDescriptions");
942

943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
  xmlDocSetRootElement(psDoc, psRootNode);

  /* -------------------------------------------------------------------- */
  /*      Name spaces                                                     */
  /* -------------------------------------------------------------------- */
  xmlSetNs(psRootNode, xmlNewNs(psRootNode, BAD_CAST "http://www.opengis.net/wcs/1.1", NULL));
  psOwsNs = xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OWS_110_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OWS_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XLINK_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_W3C_XSI_NAMESPACE_PREFIX);
  xmlNewNs(psRootNode, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_URI, BAD_CAST MS_OWSCOMMON_OGC_NAMESPACE_PREFIX );

  schemaLocation = msEncodeHTMLEntities( msOWSGetSchemasLocation(map) );
  xsi_schemaLocation = msStrdup("http://www.opengis.net/wcs/1.1");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/wcs/1.1/wcsDescribeCoverage.xsd ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, MS_OWSCOMMON_OWS_110_NAMESPACE_URI);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, " ");
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, schemaLocation);
  xsi_schemaLocation = msStringConcatenate(xsi_schemaLocation, "/ows/1.1.0/owsAll.xsd");
  xmlNewNsProp(psRootNode, NULL, BAD_CAST "xsi:schemaLocation", BAD_CAST xsi_schemaLocation);
  msFree(schemaLocation);
  msFree(xsi_schemaLocation);

  /* -------------------------------------------------------------------- */
  /*      Generate a CoverageDescription for each requested coverage.     */
  /* -------------------------------------------------------------------- */

  if(params->coverages) { /* use the list */
    for( j = 0; params->coverages[j]; j++ ) {
      i = msGetLayerIndex(map, params->coverages[j]);
      msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)),
          params, psRootNode,
          psOwsNs );
977
    }
978 979 980 981 982 983 984 985 986
  } else { /* return all layers */
    for(i=0; i<map->numlayers; i++) {

      if (!msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers, ows_request->numlayers))
        continue;

      msWCSDescribeCoverage_CoverageDescription11((GET_LAYER(map, i)),
          params, psRootNode,
          psOwsNs );
987
    }
988
  }
989

990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  /* -------------------------------------------------------------------- */
  /*      Write out the document.                                         */
  /* -------------------------------------------------------------------- */
  {
    xmlChar *buffer = NULL;
    int size = 0;
    msIOContext *context = NULL;

    if( msIO_needBinaryStdout() == MS_FAILURE )
      return MS_FAILURE;

    if (encoding)
      msIO_setHeader("Content-Type","text/xml; charset=%s", encoding);
    else
      msIO_setHeader("Content-Type","text/xml");
    msIO_sendHeaders();

    context = msIO_getHandler(stdout);

    xmlDocDumpFormatMemoryEnc(psDoc, &buffer, &size, (encoding ? encoding : "ISO-8859-1"), 1);
    msIO_contextWrite(context, buffer, size);
    xmlFree(buffer);
  }

  /* -------------------------------------------------------------------- */
  /*      Cleanup                                                         */
  /* -------------------------------------------------------------------- */
  xmlFreeDoc(psDoc);
  xmlCleanupParser();

  return MS_SUCCESS;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
}

#endif /* defined(USE_WCS_SVR) && defined(USE_LIBXML2) */

/************************************************************************/
/*                      msWCSGetCoverageBands11()                       */
/*                                                                      */
/*      We expect input to be of the form:                              */
/*      RangeSubset=raster:interpolation[bands[1]].                     */
/*                                                                      */
/*      RangeSet=raster:[bands[1,2]]                                    */
/*       or                                                             */
/*      RangeSet=raster:bilinear                                        */
/*                                                                      */
/*      This function tries to return a bandlist if found, and will     */
/*      also push an INTERPOLATION keyword into the parameters list     */
/*      if found in the RangeSubset.                                    */
/************************************************************************/

#if defined(USE_WCS_SVR)
1041
int msWCSGetCoverageBands11( mapObj *map, cgiRequestObj *request,
1042 1043 1044 1045
                             wcsParamsObj *params, layerObj *lp,
                             char **p_bandlist )

{
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  char *rangesubset, *field_id;
  const char *axis_id, *value;
  int i;

  /* -------------------------------------------------------------------- */
  /*      Fetch the RangeSubset from the parameters, skip building a      */
  /*      bands list if not found.                                        */
  /* -------------------------------------------------------------------- */
  value = msWCSGetRequestParameter(request, "RangeSubset");
  if( value == NULL )
    return MS_SUCCESS;
1057

1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
  rangesubset = msStrdup(value);

  /* -------------------------------------------------------------------- */
  /*      What is the <Field identifier=...> (rangeset_name)?             */
  /* -------------------------------------------------------------------- */
  value = msOWSLookupMetadata( &(lp->metadata), "CO", "rangeset_name" );
  if( value == NULL )
    value = "raster";
  field_id = msStrdup(value);

  /* -------------------------------------------------------------------- */
  /*      What is the <Axis identifier=...> (bands_name)?                 */
  /* -------------------------------------------------------------------- */
  axis_id = msOWSLookupMetadata( &(lp->metadata), "CO", "bands_name" );
  if( axis_id == NULL )
    axis_id = "bands";

  /* -------------------------------------------------------------------- */
  /*      Parse out the field identifier from the request and verify.     */
  /* -------------------------------------------------------------------- */
  value = rangesubset + strlen(field_id);

  if( strcasecmp(rangesubset,field_id) == 0 )
    return MS_SUCCESS; /* we only got field ... default options */

  if( strlen(rangesubset) <= strlen(field_id)+1
      || strncasecmp(rangesubset,field_id,strlen(field_id)) != 0
      || (*value != '[' && *value != ':') ) {
    msSetError( MS_WCSERR,
                "RangeSubset field name malformed, expected '%s', got RangeSubset=%s",
                "msWCSGetCoverageBands11()",
                field_id, rangesubset );
    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
  }

  free( field_id );
  field_id = NULL;

  /* -------------------------------------------------------------------- */
  /*      Parse out the interpolation, if found.                          */
  /* -------------------------------------------------------------------- */
  if( *value == ':' ) {
    assert( params->interpolation == NULL );
    params->interpolation = msStrdup(value+1);
    for( i = 0; params->interpolation[i] != '\0'; i++ ) {
      if( params->interpolation[i] == '[' ) {
        params->interpolation[i] = '\0';
        break;
      }
1107 1108
    }

1109 1110
    value += strlen(params->interpolation) + 1;
  }
1111

1112 1113 1114 1115 1116
  /* -------------------------------------------------------------------- */
  /*      Parse out the axis name, and verify.                            */
  /* -------------------------------------------------------------------- */
  if( *value != '[' )
    return MS_SUCCESS;
1117

1118
  value++;
1119

1120 1121 1122 1123 1124 1125 1126 1127 1128
  if( strlen(value) <= strlen(axis_id)+1
      || strncasecmp(value,axis_id,strlen(axis_id)) != 0
      || value[strlen(axis_id)] != '[' ) {
    msSetError( MS_WCSERR,
                "RangeSubset axis name malformed, expected '%s', got RangeSubset=%s",
                "msWCSGetCoverageBands11()",
                axis_id, rangesubset );
    return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
  }
1129

1130 1131 1132 1133 1134
  /* -------------------------------------------------------------------- */
  /*      Parse the band list.  Basically assuming the band list is       */
  /*      everything from here to a close ';'.                            */
  /* -------------------------------------------------------------------- */
  value += strlen(axis_id) + 1;
1135

1136 1137 1138 1139 1140 1141
  *p_bandlist = msStrdup(value);

  for( i = 0; (*p_bandlist)[i] != '\0'; i++ ) {
    if( (*p_bandlist)[i] == '[' ) {
      (*p_bandlist)[i] = '\0';
      break;
1142
    }
1143
  }
1144

1145 1146
  return MS_SUCCESS;
}
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
#endif

/************************************************************************/
/*                       msWCSReturnCoverage11()                        */
/*                                                                      */
/*      Return a render image as a coverage to the caller with WCS      */
/*      1.1 "mime" wrapping.                                            */
/************************************************************************/

#if defined(USE_WCS_SVR)
1157
int  msWCSReturnCoverage11( wcsParamsObj *params, mapObj *map,
1158 1159
                            imageObj *image )
{
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
  int status, i;
  char *filename = NULL;
  char *base_dir = NULL;
  const char *encoding;
  const char *fo_filename;

  encoding = msOWSLookupMetadata(&(map->web.metadata), "CO", "encoding");

  fo_filename = msGetOutputFormatOption( image->format, "FILENAME", NULL );

  /* -------------------------------------------------------------------- */
  /*      Fetch the driver we will be using and check if it supports      */
  /*      VSIL IO.                                                        */
  /* -------------------------------------------------------------------- */
  if( EQUALN(image->format->driver,"GDAL/",5) ) {
    GDALDriverH hDriver;
    const char *pszExtension = image->format->extension;

    msAcquireLock( TLOCK_GDAL );
    hDriver = GDALGetDriverByName( image->format->driver+5 );
    if( hDriver == NULL ) {
      msReleaseLock( TLOCK_GDAL );
      msSetError( MS_MISCERR,
                  "Failed to find %s driver.",
                  "msWCSReturnCoverage11()",
                  image->format->driver+5 );
      return msWCSException11(map, "mapserv", "NoApplicableCode",
                              params->version);
1188 1189
    }

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    if( pszExtension == NULL )
      pszExtension = "img.tmp";

    if( GDALGetMetadataItem( hDriver, GDAL_DCAP_VIRTUALIO, NULL )
        != NULL ) {
      base_dir = msTmpFile(map, map->mappath, "/vsimem/wcsout", NULL);
      if( fo_filename )
        filename = msStrdup(CPLFormFilename(base_dir,
                                            fo_filename,NULL));
      else
        filename = msStrdup(CPLFormFilename(base_dir,
                                            "out", pszExtension ));

      /*            CleanVSIDir( "/vsimem/wcsout" ); */

      msReleaseLock( TLOCK_GDAL );
      status = msSaveImage(map, image, filename);
      if( status != MS_SUCCESS ) {
        msFree(filename);
        msSetError(MS_MISCERR, "msSaveImage() failed",
                   "msWCSReturnCoverage11()");
        return msWCSException11(map, "mapserv", "NoApplicableCode",
                                params->version);
      }
1214
    }
1215 1216
    msReleaseLock( TLOCK_GDAL );
  }
1217

1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
  /* -------------------------------------------------------------------- */
  /*      Output stock header.                                            */
  /* -------------------------------------------------------------------- */
  if (encoding) {
    msIO_setHeader("Content-Type","multipart/mixed; boundary=wcs");
    msIO_sendHeaders();
    msIO_fprintf(
      stdout,
      "\r\n--wcs\r\n"
      "Content-Type: text/xml; charset=%s\r\n"
      "Content-ID: wcs.xml\r\n\r\n"
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      "<Coverages\n"
      "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
      "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
      "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
      "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
      "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
      "  <Coverage>\n",
      encoding);
  } else {
    msIO_setHeader("Content-Type","multipart/mixed; boundary=wcs");
    msIO_sendHeaders();
    msIO_fprintf(
      stdout,
      "\r\n--wcs\r\n"
      "Content-Type: text/xml\r\n"
      "Content-ID: wcs.xml\r\n\r\n"
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
      "<Coverages\n"
      "     xmlns=\"http://www.opengis.net/wcs/1.1\"\n"
      "     xmlns:ows=\"http://www.opengis.net/ows/1.1\"\n"
      "     xmlns:xlink=\"http://www.w3.org/1999/xlink\"\n"
      "     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
      "     xsi:schemaLocation=\"http://www.opengis.net/ows/1.1 ../owsCoverages.xsd\">\n"
      "  <Coverage>\n");
  }

  /* -------------------------------------------------------------------- */
  /*      If we weren't able to write data under /vsimem, then we just    */
  /*      output a single "stock" filename.                               */
  /* -------------------------------------------------------------------- */
  if( filename == NULL ) {
    msIO_fprintf(
      stdout,
      "    <ows:Reference xlink:href=\"cid:coverage/wcs.%s\"/>\n"
      "  </Coverage>\n"
      "</Coverages>\n"
      "\r\n--wcs\r\n"
      "Content-Type: %s\r\n"
      "Content-Description: coverage data\r\n"
      "Content-Transfer-Encoding: binary\r\n"
      "Content-ID: coverage/wcs.%s\r\n"
      "Content-Disposition: INLINE\r\n\r\n",
      MS_IMAGE_EXTENSION(map->outputformat),
      MS_IMAGE_MIME_TYPE(map->outputformat),
      MS_IMAGE_EXTENSION(map->outputformat));

    status = msSaveImage(map, image, NULL);
    if( status != MS_SUCCESS ) {
      msSetError( MS_MISCERR, "msSaveImage() failed", "msWCSReturnCoverage11()");
      return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
    }

    msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
    return MS_SUCCESS;
  }

  /* -------------------------------------------------------------------- */
  /*      When potentially listing multiple files, we take great care     */
  /*      to identify the "primary" file and list it first.  In fact      */
  /*      it is the only file listed in the coverages document.           */
  /* -------------------------------------------------------------------- */
  {
    char **all_files = CPLReadDir( base_dir );
    int count = CSLCount(all_files);

    if( msIO_needBinaryStdout() == MS_FAILURE )
      return MS_FAILURE;

    msAcquireLock( TLOCK_GDAL );
    for( i = count-1; i >= 0; i-- ) {
      const char *this_file = all_files[i];

      if( EQUAL(this_file,".") || EQUAL(this_file,"..") ) {
        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
        continue;
      }

      if( i > 0 && EQUAL(this_file,CPLGetFilename(filename)) ) {
        all_files = CSLRemoveStrings( all_files, i, 1, NULL );
        all_files = CSLInsertString(all_files,0,CPLGetFilename(filename));
        i++;
      }
    }

    msIO_fprintf(
      stdout,
      "    <ows:Reference xlink:href=\"cid:coverage/%s\"/>\n"
      "  </Coverage>\n"
      "</Coverages>\n",
      CPLGetFilename(filename) );

    /* -------------------------------------------------------------------- */
    /*      Dump all the files in the memory directory as mime sections.    */
    /* -------------------------------------------------------------------- */
    count = CSLCount(all_files);

    for( i = 0; i < count; i++ ) {
      const char *mimetype = NULL;
      FILE *fp;
      unsigned char block[4000];
      int bytes_read;

      if( i == 0 )
        mimetype = MS_IMAGE_MIME_TYPE(map->outputformat);

      if( mimetype == NULL )
        mimetype = "application/octet-stream";

      msIO_fprintf(
        stdout,
        "\r\n--wcs\r\n"
        "Content-Type: %s\r\n"
        "Content-Description: coverage data\r\n"
        "Content-Transfer-Encoding: binary\r\n"
        "Content-ID: coverage/%s\r\n"
        "Content-Disposition: INLINE\r\n\r\n",
        mimetype,
        all_files[i]);

      fp = VSIFOpenL(
             CPLFormFilename(base_dir, all_files[i], NULL),
             "rb" );
      if( fp == NULL ) {
1353
        msReleaseLock( TLOCK_GDAL );
1354 1355 1356 1357 1358 1359 1360 1361
        msSetError( MS_MISCERR,
                    "Failed to open %s for streaming to stdout.",
                    "msWCSReturnCoverage11()", all_files[i] );
        return MS_FAILURE;
      }

      while( (bytes_read = VSIFReadL(block, 1, sizeof(block), fp)) > 0 )
        msIO_fwrite( block, 1, bytes_read, stdout );
1362

1363 1364 1365
      VSIFCloseL( fp );

      VSIUnlink( CPLFormFilename(base_dir, all_files[i], NULL) );
1366
    }
1367 1368 1369 1370 1371 1372 1373

    msFree(base_dir);
    msFree(filename);
    CSLDestroy( all_files );
    msReleaseLock( TLOCK_GDAL );

    msIO_fprintf( stdout, "\r\n--wcs--\r\n" );
1374
    return MS_SUCCESS;
1375
  }
1376 1377 1378 1379 1380
}
#endif /* defined(USE_WCS_SVR) && defined(USE_LIBXML2) */

/************************************************************************/
/* ==================================================================== */
1381
/*  If we don't have libxml2 but WCS SVR was selected, then         */
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
/*      report WCS 1.1 requests as unsupported.                         */
/* ==================================================================== */
/************************************************************************/

#if defined(USE_WCS_SVR) && !defined(USE_LIBXML2)

#include "mapwcs.h"

/* ==================================================================== */

1392 1393
int msWCSDescribeCoverage11(mapObj *map, wcsParamsObj *params,
                            owsRequestObj *ows_request)
1394
{
1395 1396 1397 1398
  msSetError( MS_WCSERR,
              "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
              "msWCSDescribeCoverage11()", "NoApplicableCode" );
  return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
1399 1400 1401 1402
}

/* ==================================================================== */

1403 1404
int msWCSGetCapabilities11(mapObj *map, wcsParamsObj *params,
                           cgiRequestObj *req, owsRequestObj *ows_request)
1405
{
1406 1407 1408
  msSetError( MS_WCSERR,
              "WCS 1.1 request made, but mapserver requires libxml2 for WCS 1.1 services and this is not configured.",
              "msWCSGetCapabilities11()", "NoApplicableCode" );
1409

1410
  return msWCSException11(map, "mapserv", "NoApplicableCode", params->version);
1411 1412
}

1413 1414 1415 1416
int msWCSException11(mapObj *map, const char *locator, const char *exceptionCode, const char *version)
{
  /* fallback to reporting using 1.0 style exceptions. */
  return msWCSException( map, locator, exceptionCode, "1.0.0" );
1417 1418 1419
}

#endif /* defined(USE_WCS_SVR) && !defined(USE_LIBXML2) */