Coverage Report

Created: 2026-07-25 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/MapServer/src/mapwcs.cpp
Line
Count
Source
1
/******************************************************************************
2
 * $Id$
3
 *
4
 * Project:  MapServer
5
 * Purpose:  OpenGIS Web Coverage Server (WCS) Implementation.
6
 * Author:   Steve Lime and the MapServer team.
7
 *
8
 ******************************************************************************
9
 * Copyright (c) 1996-2005 Regents of the University of Minnesota.
10
 *
11
 * Permission is hereby granted, free of charge, to any person obtaining a
12
 * copy of this software and associated documentation files (the "Software"),
13
 * to deal in the Software without restriction, including without limitation
14
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15
 * and/or sell copies of the Software, and to permit persons to whom the
16
 * Software is furnished to do so, subject to the following conditions:
17
 *
18
 * The above copyright notice and this permission notice shall be included in
19
 * all copies of this Software or works derived from this Software.
20
 *
21
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27
 * DEALINGS IN THE SOFTWARE.
28
 *****************************************************************************/
29
30
#include "mapserver.h"
31
#include "maperror.h"
32
#include "mapthread.h"
33
#include "mapows.h"
34
#include <assert.h>
35
36
#include <map>
37
#include <string>
38
39
#if defined(USE_WCS_SVR)
40
41
#include "mapwcs.h"
42
43
#include "maptime.h"
44
#include <time.h>
45
46
#include "gdal.h"
47
#include "cpl_string.h" /* GDAL string handling */
48
49
/************************************************************************/
50
/*                    msWCSValidateRangeSetParam()                      */
51
/************************************************************************/
52
static int msWCSValidateRangeSetParam(layerObj *lp, char *name,
53
0
                                      const char *value) {
54
0
  char **allowed_ri_values;
55
0
  char **client_ri_values;
56
0
  int allowed_count, client_count;
57
0
  int i_client, i, all_match = 1;
58
0
  char *tmpname = NULL;
59
0
  const char *ri_values_list;
60
61
0
  if (name == NULL)
62
0
    return MS_FAILURE;
63
64
  /* Fetch the available values list for the rangeset item and tokenize */
65
0
  const size_t nSize = strlen(name) + strlen("_values") + 1;
66
0
  tmpname = (char *)msSmallMalloc(nSize);
67
0
  snprintf(tmpname, nSize, "%s_values", name);
68
0
  ri_values_list = msOWSLookupMetadata(&(lp->metadata), "CO", tmpname);
69
0
  msFree(tmpname);
70
71
0
  if (ri_values_list == NULL)
72
0
    return MS_FAILURE;
73
74
0
  allowed_ri_values = msStringSplit(ri_values_list, ',', &allowed_count);
75
76
  /* Parse the client value list into tokens. */
77
0
  client_ri_values = msStringSplit(value, ',', &client_count);
78
79
  /* test each client value against the allowed list. */
80
81
0
  for (i_client = 0; all_match && i_client < client_count; i_client++) {
82
0
    for (i = 0; i < allowed_count && strcasecmp(client_ri_values[i_client],
83
0
                                                allowed_ri_values[i]) != 0;
84
0
         i++) {
85
0
    }
86
87
0
    if (i == allowed_count)
88
0
      all_match = 0;
89
0
  }
90
91
0
  msFreeCharArray(allowed_ri_values, allowed_count);
92
0
  msFreeCharArray(client_ri_values, client_count);
93
94
0
  if (all_match == 0)
95
0
    return MS_FAILURE;
96
0
  else
97
0
    return MS_SUCCESS;
98
0
}
99
100
/************************************************************************/
101
/*                    msWCSConvertRangeSetToString()                    */
102
/************************************************************************/
103
0
static char *msWCSConvertRangeSetToString(const char *value) {
104
0
  char **tokens;
105
0
  int numtokens;
106
0
  double min, max, res;
107
0
  double val;
108
0
  char buf1[128], *buf2 = NULL;
109
110
0
  if (strchr(value, '/')) { /* value is min/max/res */
111
0
    tokens = msStringSplit(value, '/', &numtokens);
112
0
    if (tokens == NULL || numtokens != 3) {
113
0
      msFreeCharArray(tokens, numtokens);
114
0
      return NULL; /* not a set of equally spaced intervals */
115
0
    }
116
117
0
    min = atof(tokens[0]);
118
0
    max = atof(tokens[1]);
119
0
    res = atof(tokens[2]);
120
0
    msFreeCharArray(tokens, numtokens);
121
122
0
    for (val = min; val <= max; val += res) {
123
0
      if (val == min)
124
0
        snprintf(buf1, sizeof(buf1), "%g", val);
125
0
      else
126
0
        snprintf(buf1, sizeof(buf1), ",%g", val);
127
0
      buf2 = msStringConcatenate(buf2, buf1);
128
0
    }
129
130
0
    return buf2;
131
0
  } else
132
0
    return msStrdup(value);
133
0
}
134
135
/************************************************************************/
136
/*                           msWCSException()                           */
137
/************************************************************************/
138
int msWCSException(mapObj *map, const char *code, const char *locator,
139
0
                   const char *version) {
140
0
  char *pszEncodedVal = NULL;
141
0
  char version_string[OWS_VERSION_MAXLEN];
142
143
0
  if (version == NULL)
144
0
    version = "1.0.0";
145
146
0
#if defined(USE_LIBXML2)
147
0
  if (msOWSParseVersionString(version) >= OWS_2_0_0)
148
0
    return msWCSException20(
149
0
        map, code, locator,
150
0
        msOWSGetVersionString(msOWSParseVersionString(version),
151
0
                              version_string));
152
0
#endif
153
154
0
  if (msOWSParseVersionString(version) >= OWS_1_1_0)
155
0
    return msWCSException11(
156
0
        map, code, locator,
157
0
        msOWSGetVersionString(msOWSParseVersionString(version),
158
0
                              version_string));
159
160
0
  msIO_setHeader("Content-Type", "application/vnd.ogc.se_xml; charset=UTF-8");
161
0
  msIO_sendHeaders();
162
163
  /* msIO_printf("Content-Type: text/xml%c%c",10,10); */
164
165
0
  msIO_printf("<?xml version='1.0' encoding=\"UTF-8\" ?>\n");
166
167
0
  msIO_printf("<ServiceExceptionReport version=\"1.2.0\"\n");
168
0
  msIO_printf("xmlns=\"http://www.opengis.net/ogc\" ");
169
0
  msIO_printf("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
170
0
  pszEncodedVal = msEncodeHTMLEntities(msOWSGetSchemasLocation(map));
171
0
  msIO_printf("xsi:schemaLocation=\"http://www.opengis.net/ogc "
172
0
              "%s/wcs/1.0.0/OGC-exception.xsd\">\n",
173
0
              pszEncodedVal);
174
0
  msFree(pszEncodedVal);
175
0
  msIO_printf("  <ServiceException");
176
0
  if (code) {
177
0
    msIO_printf(" code=\"%s\"", code);
178
0
  }
179
0
  if (locator) {
180
0
    msIO_printf(" locator=\"%s\"", locator);
181
0
  }
182
0
  msIO_printf(">");
183
0
  msWriteErrorXML(stdout);
184
0
  msIO_printf("  </ServiceException>\n");
185
0
  msIO_printf("</ServiceExceptionReport>\n");
186
187
0
  msResetErrorList();
188
189
0
  return MS_FAILURE;
190
0
}
191
192
/************************************************************************/
193
/*                    msWCSPrintRequestCapability()                     */
194
/************************************************************************/
195
196
static void msWCSPrintRequestCapability(const char *request_tag,
197
0
                                        const char *script_url) {
198
0
  msIO_printf("    <%s>\n", request_tag);
199
200
0
  msIO_printf("      <DCPType>\n");
201
0
  msIO_printf("        <HTTP>\n");
202
0
  msIO_printf("          <Get><OnlineResource xlink:type=\"simple\" "
203
0
              "xlink:href=\"%s\" /></Get>\n",
204
0
              script_url);
205
0
  msIO_printf("        </HTTP>\n");
206
0
  msIO_printf("      </DCPType>\n");
207
0
  msIO_printf("      <DCPType>\n");
208
0
  msIO_printf("        <HTTP>\n");
209
0
  msIO_printf("          <Post><OnlineResource xlink:type=\"simple\" "
210
0
              "xlink:href=\"%s\" /></Post>\n",
211
0
              script_url);
212
0
  msIO_printf("        </HTTP>\n");
213
0
  msIO_printf("      </DCPType>\n");
214
215
0
  msIO_printf("    </%s>\n", request_tag);
216
0
}
217
218
/************************************************************************/
219
/*                         msWCSCreateParams()                          */
220
/************************************************************************/
221
0
static wcsParamsObj *msWCSCreateParams() {
222
0
  wcsParamsObj *params;
223
224
0
  params = (wcsParamsObj *)calloc(1, sizeof(wcsParamsObj));
225
0
  MS_CHECK_ALLOC(params, sizeof(wcsParamsObj), NULL);
226
227
0
  return params;
228
0
}
229
230
/************************************************************************/
231
/*                          msWCSFreeParams()                           */
232
/************************************************************************/
233
0
void msWCSFreeParams(wcsParamsObj *params) {
234
0
  if (params) {
235
    /* TODO */
236
0
    if (params->version)
237
0
      free(params->version);
238
0
    if (params->updatesequence)
239
0
      free(params->updatesequence);
240
0
    if (params->request)
241
0
      free(params->request);
242
0
    if (params->service)
243
0
      free(params->service);
244
0
    if (params->section)
245
0
      free(params->section);
246
0
    if (params->crs)
247
0
      free(params->crs);
248
0
    if (params->response_crs)
249
0
      free(params->response_crs);
250
0
    if (params->format)
251
0
      free(params->format);
252
0
    if (params->exceptions)
253
0
      free(params->exceptions);
254
0
    if (params->time)
255
0
      free(params->time);
256
0
    if (params->interpolation)
257
0
      free(params->interpolation);
258
0
    CSLDestroy(params->coverages);
259
0
  }
260
0
}
261
262
/************************************************************************/
263
/*                       msWCSIsLayerSupported()                        */
264
/************************************************************************/
265
266
0
int msWCSIsLayerSupported(layerObj *layer) {
267
  /* only raster layers, are elligible to be served via WCS, WMS rasters are not
268
   * ok */
269
0
  if ((layer->type == MS_LAYER_RASTER) && layer->connectiontype != MS_WMS &&
270
0
      layer->name != NULL)
271
0
    return MS_TRUE;
272
273
0
  return MS_FALSE;
274
0
}
275
276
/************************************************************************/
277
/*                      msWCSGetRequestParameter()                      */
278
/*                                                                      */
279
/************************************************************************/
280
281
0
const char *msWCSGetRequestParameter(cgiRequestObj *request, const char *name) {
282
0
  int i;
283
284
0
  if (!request || !name) /* nothing to do */
285
0
    return NULL;
286
287
0
  if (request->NumParams > 0) {
288
0
    for (i = 0; i < request->NumParams; i++) {
289
0
      if (strcasecmp(request->ParamNames[i], name) == 0)
290
0
        return request->ParamValues[i];
291
0
    }
292
0
  }
293
294
0
  return NULL;
295
0
}
296
297
/************************************************************************/
298
/*                  msWCSSetDefaultBandsRangeSetInfo()                  */
299
/************************************************************************/
300
301
void msWCSSetDefaultBandsRangeSetInfo(wcsParamsObj *params,
302
0
                                      coverageMetadataObj *cm, layerObj *lp) {
303
0
  (void)params;
304
305
  /* This function will provide default rangeset information for the "special"
306
   */
307
  /* "bands" rangeset if it appears in the axes list but has no specifics
308
   * provided */
309
  /* in the metadata.   */
310
311
0
  const char *value;
312
0
  char *bandlist;
313
0
  size_t bufferSize = 0;
314
0
  int i;
315
316
  /* Does this item exist in the axes list?  */
317
318
0
  value = msOWSLookupMetadata(&(lp->metadata), "CO", "rangeset_axes");
319
0
  if (value == NULL)
320
0
    return;
321
322
0
  value = strstr(value, "bands");
323
0
  if (value == NULL || (value[5] != '\0' && value[5] != ' '))
324
0
    return;
325
326
  /* Are there any w*s_bands_ metadata already? If so, skip out. */
327
0
  if (msOWSLookupMetadata(&(lp->metadata), "CO", "bands_description") != NULL ||
328
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_name") != NULL ||
329
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_label") != NULL ||
330
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values") != NULL ||
331
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_semantic") !=
332
0
          NULL ||
333
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_values_type") != NULL ||
334
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_rangeitem") != NULL ||
335
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_semantic") != NULL ||
336
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsys") != NULL ||
337
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_refsyslabel") != NULL ||
338
0
      msOWSLookupMetadata(&(lp->metadata), "CO", "bands_interval") != NULL)
339
0
    return;
340
341
  /* OK, we have decided to fill in the information. */
342
343
0
  msInsertHashTable(&(lp->metadata), "wcs_bands_name", "bands");
344
0
  msInsertHashTable(&(lp->metadata), "wcs_bands_label",
345
0
                    "Bands/Channels/Samples");
346
0
  msInsertHashTable(&(lp->metadata), "wcs_bands_rangeitem", "_bands"); /* ? */
347
348
0
  bufferSize = cm->bandcount * 30 + 30;
349
0
  bandlist = (char *)msSmallMalloc(bufferSize);
350
0
  strcpy(bandlist, "1");
351
0
  for (i = 1; i < cm->bandcount; i++)
352
0
    snprintf(bandlist + strlen(bandlist), bufferSize - strlen(bandlist), ",%d",
353
0
             i + 1);
354
355
0
  msInsertHashTable(&(lp->metadata), "wcs_bands_values", bandlist);
356
0
  free(bandlist);
357
0
}
358
359
/************************************************************************/
360
/*                             msWCSSetParam                            */
361
/************************************************************************/
362
363
static int msWCSSetParam(char **ppszOut, cgiRequestObj *request, int i,
364
0
                         const char *pszExpectedParamName) {
365
0
  if (strcasecmp(request->ParamNames[i], pszExpectedParamName) == 0) {
366
    /* Keep the first value supplied and ignore later duplicates. This avoids
367
       leaking the previously allocated value when the same parameter appears
368
       multiple times in a request (consistent with msWFSSetParam()). */
369
0
    if (*ppszOut == NULL)
370
0
      *ppszOut = msStrdup(request->ParamValues[i]);
371
0
    return 1;
372
0
  }
373
0
  return 0;
374
0
}
375
376
/************************************************************************/
377
/*                         msWCSParseRequest()                          */
378
/************************************************************************/
379
380
static int msWCSParseRequest(cgiRequestObj *request, wcsParamsObj *params,
381
0
                             mapObj *map) {
382
0
  int i, n;
383
0
  char **tokens;
384
385
0
  if (!request || !params) /* nothing to do */
386
0
    return MS_SUCCESS;
387
388
  /* -------------------------------------------------------------------- */
389
  /*      Check if this appears to be an XML POST WCS request.            */
390
  /* -------------------------------------------------------------------- */
391
392
0
  msDebug("msWCSParseRequest(): request is %s.\n",
393
0
          (request->type == MS_POST_REQUEST) ? "POST" : "KVP");
394
395
0
  if (request->type == MS_POST_REQUEST && request->postrequest) {
396
0
#if defined(USE_LIBXML2)
397
0
    xmlDocPtr doc = NULL;
398
0
    xmlNodePtr root = NULL, child = NULL;
399
0
    char *tmp = NULL;
400
401
    /* parse to DOM-Structure and get root element */
402
0
    if ((doc = xmlParseMemory(request->postrequest,
403
0
                              strlen(request->postrequest))) == NULL) {
404
0
      const xmlError *error = xmlGetLastError();
405
0
      msSetError(MS_WCSERR, "XML parsing error: %s", "msWCSParseRequest()",
406
0
                 error->message);
407
0
      return MS_FAILURE;
408
0
    }
409
0
    root = xmlDocGetRootElement(doc);
410
411
    /* Get service, version and request from root */
412
0
    params->request = msStrdup((char *)root->name);
413
0
    if ((tmp = (char *)xmlGetProp(root, BAD_CAST "service")) != NULL)
414
0
      params->service = tmp;
415
0
    if ((tmp = (char *)xmlGetProp(root, BAD_CAST "version")) != NULL)
416
0
      params->version = tmp;
417
418
    /* search first level children, either CoverageID,  */
419
0
    for (child = root->children; child != NULL; child = child->next) {
420
0
      if (EQUAL((char *)child->name, "AcceptVersions")) {
421
        /* will be overridden to 1.1.1 anyway */
422
0
      } else if (EQUAL((char *)child->name, "UpdateSequence")) {
423
0
        params->updatesequence = (char *)xmlNodeGetContent(child);
424
0
      } else if (EQUAL((char *)child->name, "Sections")) {
425
0
        xmlNodePtr sectionNode = NULL;
426
        /* concatenate all sections by ',' */
427
0
        for (sectionNode = child->children; sectionNode != NULL;
428
0
             sectionNode = sectionNode->next) {
429
0
          char *content;
430
0
          if (!EQUAL((char *)sectionNode->name, "Section"))
431
0
            continue;
432
0
          content = (char *)xmlNodeGetContent(sectionNode);
433
0
          if (!params->section) {
434
0
            params->section = content;
435
0
          } else {
436
0
            params->section = msStringConcatenate(params->section, ",");
437
0
            params->section = msStringConcatenate(params->section, content);
438
0
            xmlFree(content);
439
0
          }
440
0
        }
441
0
      } else if (EQUAL((char *)child->name, "AcceptFormats")) {
442
        /* TODO: implement */
443
0
      } else if (EQUAL((char *)child->name, "Identifier")) {
444
0
        char *content = (char *)xmlNodeGetContent(child);
445
0
        params->coverages = CSLAddString(params->coverages, content);
446
0
        xmlFree(content);
447
0
      } else if (EQUAL((char *)child->name, "DomainSubset")) {
448
0
        xmlNodePtr tmpNode = NULL;
449
0
        for (tmpNode = child->children; tmpNode != NULL;
450
0
             tmpNode = tmpNode->next) {
451
0
          if (EQUAL((char *)tmpNode->name, "BoundingBox")) {
452
0
            xmlNodePtr cornerNode = NULL;
453
0
            params->crs = (char *)xmlGetProp(tmpNode, BAD_CAST "crs");
454
0
            if (!params->crs) {
455
0
              msSetError(MS_WCSERR, "Required parameter CRS was not supplied.",
456
0
                         "msWCSGetCoverage()");
457
0
              msWCSException(map, "MissingParameterValue", "crs",
458
0
                             params->version);
459
0
              xmlFreeDoc(doc);
460
0
              xmlCleanupParser();
461
0
              return MS_DONE;
462
0
            }
463
0
            if (strncasecmp(params->crs, "urn:ogc:def:crs:", 16) == 0 &&
464
0
                strncasecmp(params->crs + strlen(params->crs) - 8, "imageCRS",
465
0
                            8) == 0)
466
0
              strcpy(params->crs, "imageCRS");
467
0
            for (cornerNode = tmpNode->children; cornerNode != NULL;
468
0
                 cornerNode = cornerNode->next) {
469
0
              if (EQUAL((char *)cornerNode->name, "LowerCorner")) {
470
0
                char *value = (char *)xmlNodeGetContent(cornerNode);
471
0
                tokens = msStringSplit(value, ' ', &n);
472
0
                if (tokens == NULL || n < 2) {
473
0
                  msSetError(MS_WCSERR,
474
0
                             "Wrong number of arguments for LowerCorner",
475
0
                             "msWCSParseRequest()");
476
0
                  msWCSException(map, "InvalidParameterValue", "LowerCorner",
477
0
                                 params->version);
478
0
                  msFreeCharArray(tokens, n);
479
0
                  xmlFree(value);
480
0
                  xmlFreeDoc(doc);
481
0
                  xmlCleanupParser();
482
0
                  return MS_DONE;
483
0
                }
484
0
                params->bbox.minx = atof(tokens[0]);
485
0
                params->bbox.miny = atof(tokens[1]);
486
0
                msFreeCharArray(tokens, n);
487
0
                xmlFree(value);
488
0
              }
489
0
              if (EQUAL((char *)cornerNode->name, "UpperCorner")) {
490
0
                char *value = (char *)xmlNodeGetContent(cornerNode);
491
0
                tokens = msStringSplit(value, ' ', &n);
492
0
                if (tokens == NULL || n < 2) {
493
0
                  msSetError(MS_WCSERR,
494
0
                             "Wrong number of arguments for UpperCorner",
495
0
                             "msWCSParseRequest()");
496
0
                  msWCSException(map, "InvalidParameterValue", "UpperCorner",
497
0
                                 params->version);
498
0
                  msFreeCharArray(tokens, n);
499
0
                  xmlFree(value);
500
0
                  xmlFreeDoc(doc);
501
0
                  xmlCleanupParser();
502
0
                  return MS_DONE;
503
0
                }
504
0
                params->bbox.maxx = atof(tokens[0]);
505
0
                params->bbox.maxy = atof(tokens[1]);
506
0
                msFreeCharArray(tokens, n);
507
0
                xmlFree(value);
508
0
              }
509
0
            }
510
0
          }
511
0
        }
512
0
      } else if (EQUAL((char *)child->name, "RangeSubset")) {
513
        /* TODO: not implemented in mapserver WCS 1.1? */
514
0
      } else if (EQUAL((char *)child->name, "Output")) {
515
0
        xmlNodePtr tmpNode = NULL;
516
0
        params->format = (char *)xmlGetProp(child, BAD_CAST "format");
517
0
        for (tmpNode = child->children; tmpNode != NULL;
518
0
             tmpNode = tmpNode->next) {
519
0
          if (EQUAL((char *)tmpNode->name, "GridCRS")) {
520
0
            xmlNodePtr crsNode = NULL;
521
0
            for (crsNode = tmpNode->children; crsNode != NULL;
522
0
                 crsNode = crsNode->next) {
523
0
              if (EQUAL((char *)crsNode->name, "GridBaseCRS")) {
524
0
                params->response_crs = (char *)xmlNodeGetContent(crsNode);
525
0
              } else if (EQUAL((char *)crsNode->name, "GridOrigin")) {
526
0
                char *value = (char *)xmlNodeGetContent(crsNode);
527
0
                tokens = msStringSplit(value, ' ', &n);
528
0
                if (tokens == NULL || n < 2) {
529
0
                  msSetError(MS_WCSERR,
530
0
                             "Wrong number of arguments for GridOrigin",
531
0
                             "msWCSParseRequest()");
532
0
                  msWCSException(map, "InvalidParameterValue", "GridOffsets",
533
0
                                 params->version);
534
0
                  msFreeCharArray(tokens, n);
535
0
                  xmlFree(value);
536
0
                  xmlFreeDoc(doc);
537
0
                  xmlCleanupParser();
538
0
                  return MS_DONE;
539
0
                }
540
0
                params->originx = atof(tokens[0]);
541
0
                params->originy = atof(tokens[1]);
542
0
                msFreeCharArray(tokens, n);
543
0
                xmlFree(value);
544
0
              } else if (EQUAL((char *)crsNode->name, "GridOffsets")) {
545
0
                char *value = (char *)xmlNodeGetContent(crsNode);
546
0
                tokens = msStringSplit(value, ' ', &n);
547
0
                if (tokens == NULL || n < 2) {
548
0
                  msSetError(MS_WCSERR,
549
0
                             "Wrong number of arguments for GridOffsets",
550
0
                             "msWCSParseRequest()");
551
0
                  msWCSException(map, "InvalidParameterValue", "GridOffsets",
552
0
                                 params->version);
553
0
                  msFreeCharArray(tokens, n);
554
0
                  xmlFree(value);
555
0
                  xmlFreeDoc(doc);
556
0
                  xmlCleanupParser();
557
0
                  return MS_DONE;
558
0
                }
559
                /* take absolute values to convert to positive RESX/RESY style
560
                WCS 1.0 behavior.  *but* this does break some possibilities! */
561
0
                params->resx = fabs(atof(tokens[0]));
562
0
                params->resy = fabs(atof(tokens[1]));
563
0
                msFreeCharArray(tokens, n);
564
0
                xmlFree(value);
565
0
              }
566
0
            }
567
0
          }
568
0
        }
569
0
      }
570
0
    }
571
0
    xmlFreeDoc(doc);
572
0
    xmlCleanupParser();
573
0
    return MS_SUCCESS;
574
#else  /* defined(USE_LIBXML2) */
575
    msSetError(MS_WCSERR,
576
               "To enable POST requests, MapServer has to "
577
               "be compiled with libxml2.",
578
               "msWCSParseRequest()");
579
    return MS_FAILURE;
580
#endif /* defined(USE_LIBXML2) */
581
0
  }
582
583
  /* -------------------------------------------------------------------- */
584
  /*      Extract WCS KVP Parameters.                                     */
585
  /* -------------------------------------------------------------------- */
586
0
  if (request->NumParams > 0) {
587
0
    for (i = 0; i < request->NumParams; i++) {
588
589
0
      if (msWCSSetParam(&(params->version), request, i, "VERSION")) {
590
0
      } else if (msWCSSetParam(&(params->updatesequence), request, i,
591
0
                               "UPDATESEQUENCE")) {
592
0
      } else if (msWCSSetParam(&(params->request), request, i, "REQUEST")) {
593
0
      } else if (msWCSSetParam(&(params->interpolation), request, i,
594
0
                               "INTERPOLATION")) {
595
0
      } else if (msWCSSetParam(&(params->service), request, i, "SERVICE")) {
596
0
      } else if (msWCSSetParam(&(params->section), request, i,
597
0
                               "SECTION")) { /* 1.0 */
598
        /* TODO: validate value here */
599
0
      } else if (msWCSSetParam(&(params->section), request, i,
600
0
                               "SECTIONS")) { /* 1.1 */
601
        /* TODO: validate value here */
602
0
      }
603
604
      /* GetCoverage parameters. */
605
0
      else if (strcasecmp(request->ParamNames[i], "BBOX") == 0) {
606
0
        tokens = msStringSplit(request->ParamValues[i], ',', &n);
607
0
        if (tokens == NULL || n != 4) {
608
0
          msSetError(MS_WCSERR, "Wrong number of arguments for BBOX.",
609
0
                     "msWCSParseRequest()");
610
0
          return msWCSException(map, "InvalidParameterValue", "bbox",
611
0
                                params->version);
612
0
        }
613
0
        params->bbox.minx = atof(tokens[0]);
614
0
        params->bbox.miny = atof(tokens[1]);
615
0
        params->bbox.maxx = atof(tokens[2]);
616
0
        params->bbox.maxy = atof(tokens[3]);
617
618
0
        msFreeCharArray(tokens, n);
619
0
      } else if (strcasecmp(request->ParamNames[i], "RESX") == 0)
620
0
        params->resx = atof(request->ParamValues[i]);
621
0
      else if (strcasecmp(request->ParamNames[i], "RESY") == 0)
622
0
        params->resy = atof(request->ParamValues[i]);
623
0
      else if (strcasecmp(request->ParamNames[i], "WIDTH") == 0)
624
0
        params->width = atoi(request->ParamValues[i]);
625
0
      else if (strcasecmp(request->ParamNames[i], "HEIGHT") == 0)
626
0
        params->height = atoi(request->ParamValues[i]);
627
0
      else if (strcasecmp(request->ParamNames[i], "COVERAGE") == 0)
628
0
        params->coverages =
629
0
            CSLAddString(params->coverages, request->ParamValues[i]);
630
0
      else if (msWCSSetParam(&(params->time), request, i, "TIME")) {
631
0
      } else if (msWCSSetParam(&(params->format), request, i, "FORMAT")) {
632
0
      } else if (msWCSSetParam(&(params->crs), request, i, "CRS")) {
633
0
      } else if (msWCSSetParam(&(params->response_crs), request, i,
634
0
                               "RESPONSE_CRS")) {
635
0
      }
636
637
      /* WCS 1.1 DescribeCoverage and GetCoverage ... */
638
0
      else if (strcasecmp(request->ParamNames[i], "IDENTIFIER") == 0 ||
639
0
               strcasecmp(request->ParamNames[i], "IDENTIFIERS") == 0) {
640
0
        msDebug("msWCSParseRequest(): Whole String: %s\n",
641
0
                request->ParamValues[i]);
642
0
        params->coverages =
643
0
            CSLAddString(params->coverages, request->ParamValues[i]);
644
0
      }
645
      /* WCS 1.1 style BOUNDINGBOX */
646
0
      else if (strcasecmp(request->ParamNames[i], "BOUNDINGBOX") == 0) {
647
0
        tokens = msStringSplit(request->ParamValues[i], ',', &n);
648
0
        if (tokens == NULL || n < 5) {
649
0
          msSetError(MS_WCSERR, "Wrong number of arguments for BOUNDINGBOX.",
650
0
                     "msWCSParseRequest()");
651
0
          msWCSException(map, "InvalidParameterValue", "boundingbox",
652
0
                         params->version);
653
0
          msFreeCharArray(tokens, n);
654
0
          return MS_DONE;
655
0
        }
656
657
        /* NOTE: WCS 1.1 boundingbox is center of pixel oriented, not edge
658
           like in WCS 1.0.  So bbox semantics are wonky till this is fixed
659
           later in the GetCoverage processing. */
660
0
        params->bbox.minx = atof(tokens[0]);
661
0
        params->bbox.miny = atof(tokens[1]);
662
0
        params->bbox.maxx = atof(tokens[2]);
663
0
        params->bbox.maxy = atof(tokens[3]);
664
665
0
        msFree(params->crs);
666
0
        params->crs = msStrdup(tokens[4]);
667
0
        msFreeCharArray(tokens, n);
668
        /* normalize imageCRS urns to simply "imageCRS" */
669
0
        if (strncasecmp(params->crs, "urn:ogc:def:crs:", 16) == 0 &&
670
0
            strncasecmp(params->crs + strlen(params->crs) - 8, "imageCRS", 8) ==
671
0
                0)
672
0
          strcpy(params->crs, "imageCRS");
673
0
      } else if (strcasecmp(request->ParamNames[i], "GridOffsets") == 0) {
674
0
        tokens = msStringSplit(request->ParamValues[i], ',', &n);
675
0
        if (tokens == NULL || n < 2) {
676
0
          msSetError(MS_WCSERR, "Wrong number of arguments for GridOffsets",
677
0
                     "msWCSParseRequest()");
678
0
          msWCSException(map, "InvalidParameterValue", "GridOffsets",
679
0
                         params->version);
680
0
          msFreeCharArray(tokens, n);
681
0
          return MS_DONE;
682
0
        }
683
        /* take absolute values to convert to positive RESX/RESY style
684
           WCS 1.0 behavior.  *but* this does break some possibilities! */
685
0
        params->resx = fabs(atof(tokens[0]));
686
0
        params->resy = fabs(atof(tokens[1]));
687
0
        msFreeCharArray(tokens, n);
688
0
      } else if (strcasecmp(request->ParamNames[i], "GridOrigin") == 0) {
689
0
        tokens = msStringSplit(request->ParamValues[i], ',', &n);
690
0
        if (tokens == NULL || n < 2) {
691
0
          msSetError(MS_WCSERR, "Wrong number of arguments for GridOrigin",
692
0
                     "msWCSParseRequest()");
693
0
          msWCSException(map, "InvalidParameterValue", "GridOffsets",
694
0
                         params->version);
695
0
          msFreeCharArray(tokens, n);
696
0
          return MS_DONE;
697
0
        }
698
0
        params->originx = atof(tokens[0]);
699
0
        params->originy = atof(tokens[1]);
700
0
        msFreeCharArray(tokens, n);
701
0
      }
702
703
      /* and so on... */
704
0
    }
705
0
  }
706
  /* we are not dealing with an XML encoded request at this point */
707
0
  return MS_SUCCESS;
708
0
}
709
710
/************************************************************************/
711
/*           msWCSGetCapabilities_Service_ResponsibleParty()            */
712
/************************************************************************/
713
714
0
static void msWCSGetCapabilities_Service_ResponsibleParty(mapObj *map) {
715
0
  int bEnableTelephone = MS_FALSE, bEnableAddress = MS_FALSE,
716
0
      bEnableOnlineResource = MS_FALSE;
717
718
  /* the WCS-specific way */
719
0
  if (msOWSLookupMetadata(&(map->web.metadata), "CO",
720
0
                          "responsibleparty_individualname") ||
721
0
      msOWSLookupMetadata(&(map->web.metadata), "CO",
722
0
                          "responsibleparty_organizationname")) {
723
724
0
    msIO_printf("<responsibleParty>\n");
725
0
    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
726
0
                             "responsibleparty_individualname", OWS_NOERR,
727
0
                             "    <individualName>%s</individualName>\n", NULL);
728
0
    msOWSPrintEncodeMetadata(
729
0
        stdout, &(map->web.metadata), "CO", "responsibleparty_organizationname",
730
0
        OWS_NOERR, "    <organisationName>%s</organisationName>\n", NULL);
731
0
    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
732
0
                             "responsibleparty_positionname", OWS_NOERR,
733
0
                             "    <positionName>%s</positionName>\n", NULL);
734
735
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO",
736
0
                            "responsibleparty_phone_voice") ||
737
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
738
0
                            "responsibleparty_phone_facsimile"))
739
0
      bEnableTelephone = MS_TRUE;
740
741
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO",
742
0
                            "responsibleparty_address_deliverypoint") ||
743
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
744
0
                            "responsibleparty_address_city") ||
745
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
746
0
                            "responsibleparty_address_administrativearea") ||
747
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
748
0
                            "responsibleparty_address_postalcode") ||
749
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
750
0
                            "responsibleparty_address_country") ||
751
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
752
0
                            "responsibleparty_address_electronicmailaddress"))
753
0
      bEnableAddress = MS_TRUE;
754
755
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO",
756
0
                            "responsibleparty_onlineresource"))
757
0
      bEnableOnlineResource = MS_TRUE;
758
759
0
    if (bEnableTelephone || bEnableAddress || bEnableOnlineResource) {
760
0
      msIO_printf("  <contactInfo>\n");
761
0
      if (bEnableTelephone) {
762
0
        msIO_printf("    <phone>\n");
763
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
764
0
                                 "responsibleparty_phone_voice", OWS_NOERR,
765
0
                                 "    <voice>%s</voice>\n", NULL);
766
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
767
0
                                 "responsibleparty_phone_facsimile", OWS_NOERR,
768
0
                                 "    <facsimile>%s</facsimile>\n", NULL);
769
0
        msIO_printf("    </phone>\n");
770
0
      }
771
0
      if (bEnableAddress) {
772
0
        msIO_printf("    <address>\n");
773
0
        msOWSPrintEncodeMetadata(
774
0
            stdout, &(map->web.metadata), "CO",
775
0
            "responsibleparty_address_deliverypoint", OWS_NOERR,
776
0
            "    <deliveryPoint>%s</deliveryPoint>\n", NULL);
777
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
778
0
                                 "responsibleparty_address_city", OWS_NOERR,
779
0
                                 "    <city>%s</city>\n", NULL);
780
0
        msOWSPrintEncodeMetadata(
781
0
            stdout, &(map->web.metadata), "CO",
782
0
            "responsibleparty_address_administrativearea", OWS_NOERR,
783
0
            "    <administrativeArea>%s</administrativeArea>\n", NULL);
784
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
785
0
                                 "responsibleparty_address_postalcode",
786
0
                                 OWS_NOERR, "    <postalCode>%s</postalCode>\n",
787
0
                                 NULL);
788
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
789
0
                                 "responsibleparty_address_country", OWS_NOERR,
790
0
                                 "    <country>%s</country>\n", NULL);
791
0
        msOWSPrintEncodeMetadata(
792
0
            stdout, &(map->web.metadata), "CO",
793
0
            "responsibleparty_address_electronicmailaddress", OWS_NOERR,
794
0
            "    <electronicMailAddress>%s</electronicMailAddress>\n", NULL);
795
0
        msIO_printf("    </address>\n");
796
0
      }
797
0
      msOWSPrintEncodeMetadata(
798
0
          stdout, &(map->web.metadata), "CO", "responsibleparty_onlineresource",
799
0
          OWS_NOERR,
800
0
          "    <onlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
801
0
          NULL);
802
0
      msIO_printf("  </contactInfo>\n");
803
0
    }
804
805
0
    msIO_printf("</responsibleParty>\n");
806
807
0
  } else if (msOWSLookupMetadata(&(map->web.metadata), "CO", "contactperson") ||
808
0
             msOWSLookupMetadata(
809
0
                 &(map->web.metadata), "CO",
810
0
                 "contactorganization")) { /* leverage WMS contact information
811
                                            */
812
813
0
    msIO_printf("<responsibleParty>\n");
814
0
    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
815
0
                             "contactperson", OWS_NOERR,
816
0
                             "    <individualName>%s</individualName>\n", NULL);
817
0
    msOWSPrintEncodeMetadata(
818
0
        stdout, &(map->web.metadata), "CO", "contactorganization", OWS_NOERR,
819
0
        "    <organisationName>%s</organisationName>\n", NULL);
820
0
    msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
821
0
                             "contactposition", OWS_NOERR,
822
0
                             "    <positionName>%s</positionName>\n", NULL);
823
824
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO",
825
0
                            "contactvoicetelephone") ||
826
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
827
0
                            "contactfacsimiletelephone"))
828
0
      bEnableTelephone = MS_TRUE;
829
830
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO", "address") ||
831
0
        msOWSLookupMetadata(&(map->web.metadata), "CO", "city") ||
832
0
        msOWSLookupMetadata(&(map->web.metadata), "CO", "stateorprovince") ||
833
0
        msOWSLookupMetadata(&(map->web.metadata), "CO", "postcode") ||
834
0
        msOWSLookupMetadata(&(map->web.metadata), "CO", "country") ||
835
0
        msOWSLookupMetadata(&(map->web.metadata), "CO",
836
0
                            "contactelectronicmailaddress"))
837
0
      bEnableAddress = MS_TRUE;
838
839
0
    if (msOWSLookupMetadata(&(map->web.metadata), "CO",
840
0
                            "service_onlineresource"))
841
0
      bEnableOnlineResource = MS_TRUE;
842
843
0
    if (bEnableTelephone || bEnableAddress || bEnableOnlineResource) {
844
0
      msIO_printf("  <contactInfo>\n");
845
0
      if (bEnableTelephone) {
846
0
        msIO_printf("    <phone>\n");
847
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
848
0
                                 "contactvoicetelephone", OWS_NOERR,
849
0
                                 "    <voice>%s</voice>\n", NULL);
850
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO",
851
0
                                 "contactfacsimiletelephone", OWS_NOERR,
852
0
                                 "    <facsimile>%s</facsimile>\n", NULL);
853
0
        msIO_printf("    </phone>\n");
854
0
      }
855
0
      if (bEnableAddress) {
856
0
        msIO_printf("    <address>\n");
857
0
        msOWSPrintEncodeMetadata(
858
0
            stdout, &(map->web.metadata), "CO", "address", OWS_NOERR,
859
0
            "    <deliveryPoint>%s</deliveryPoint>\n", NULL);
860
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "city",
861
0
                                 OWS_NOERR, "    <city>%s</city>\n", NULL);
862
0
        msOWSPrintEncodeMetadata(
863
0
            stdout, &(map->web.metadata), "CO", "stateorprovince", OWS_NOERR,
864
0
            "    <administrativeArea>%s</administrativeArea>\n", NULL);
865
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "postcode",
866
0
                                 OWS_NOERR, "    <postalCode>%s</postalCode>\n",
867
0
                                 NULL);
868
0
        msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "country",
869
0
                                 OWS_NOERR, "    <country>%s</country>\n",
870
0
                                 NULL);
871
0
        msOWSPrintEncodeMetadata(
872
0
            stdout, &(map->web.metadata), "CO", "contactelectronicmailaddress",
873
0
            OWS_NOERR,
874
0
            "    <electronicMailAddress>%s</electronicMailAddress>\n", NULL);
875
0
        msIO_printf("    </address>\n");
876
0
      }
877
0
      msOWSPrintEncodeMetadata(
878
0
          stdout, &(map->web.metadata), "CO", "service_onlineresource",
879
0
          OWS_NOERR,
880
0
          "    <onlineResource xlink:type=\"simple\" xlink:href=\"%s\"/>\n",
881
0
          NULL);
882
0
      msIO_printf("  </contactInfo>\n");
883
0
    }
884
0
    msIO_printf("</responsibleParty>\n");
885
0
  }
886
887
0
  return;
888
0
}
889
890
/************************************************************************/
891
/*                    msWCSGetCapabilities_Service()                    */
892
/************************************************************************/
893
894
0
static int msWCSGetCapabilities_Service(mapObj *map, wcsParamsObj *params) {
895
  /* start the Service section, only need the full start tag if this is the only
896
   * section requested */
897
0
  if (!params->section ||
898
0
      (params->section && strcasecmp(params->section, "/") == 0))
899
0
    msIO_printf("<Service>\n");
900
0
  else
901
0
    msIO_printf("<Service\n"
902
0
                "   version=\"%s\" \n"
903
0
                "   updateSequence=\"%s\" \n"
904
0
                "   xmlns=\"http://www.opengis.net/wcs\" \n"
905
0
                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
906
0
                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
907
0
                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
908
0
                "   xsi:schemaLocation=\"http://www.opengis.net/wcs "
909
0
                "%s/wcs/%s/wcsCapabilities.xsd\">\n",
910
0
                params->version, params->updatesequence,
911
0
                msOWSGetSchemasLocation(map), params->version);
912
913
  /* optional metadataLink */
914
0
  msOWSPrintURLType(stdout, &(map->web.metadata), "CO", "metadatalink",
915
0
                    OWS_NOERR,
916
0
                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>", NULL,
917
0
                    " metadataType=\"%s\"", NULL, NULL, NULL,
918
0
                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE,
919
0
                    MS_FALSE, MS_TRUE, "other", NULL, NULL, NULL, NULL, NULL);
920
921
0
  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "description",
922
0
                           OWS_NOERR, "  <description>%s</description>\n",
923
0
                           NULL);
924
0
  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "name",
925
0
                           OWS_NOERR, "  <name>%s</name>\n", "MapServer WCS");
926
0
  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "label",
927
0
                           OWS_WARN, "  <label>%s</label>\n", NULL);
928
929
  /* we are not supporting the optional keyword type, at least not yet */
930
0
  msOWSPrintEncodeMetadataList(
931
0
      stdout, &(map->web.metadata), "CO", "keywordlist", "  <keywords>\n",
932
0
      "  </keywords>\n", "    <keyword>%s</keyword>\n", NULL);
933
934
0
  msWCSGetCapabilities_Service_ResponsibleParty(map);
935
936
0
  msOWSPrintEncodeMetadata(stdout, &(map->web.metadata), "CO", "fees",
937
0
                           OWS_NOERR, "  <fees>%s</fees>\n", "NONE");
938
0
  msOWSPrintEncodeMetadataList(stdout, &(map->web.metadata), "CO",
939
0
                               "accessconstraints", "  <accessConstraints>\n",
940
0
                               "  </accessConstraints>\n", "    %s\n", "NONE");
941
942
  /* done */
943
0
  msIO_printf("</Service>\n");
944
945
0
  return MS_SUCCESS;
946
0
}
947
948
/************************************************************************/
949
/*                  msWCSGetCapabilities_Capability()                   */
950
/************************************************************************/
951
952
static int msWCSGetCapabilities_Capability(mapObj *map, wcsParamsObj *params,
953
0
                                           cgiRequestObj *req) {
954
0
  char *script_url = NULL, *script_url_encoded = NULL;
955
956
  /* we need this server's onlineresource for the request section */
957
0
  if ((script_url = msOWSGetOnlineResource(map, "CO", "onlineresource", req)) ==
958
0
          NULL ||
959
0
      (script_url_encoded = msEncodeHTMLEntities(script_url)) == NULL) {
960
0
    free(script_url);
961
0
    free(script_url_encoded);
962
0
    return msWCSException(map, NULL, NULL, params->version);
963
0
  }
964
965
  /* start the Capability section, only need the full start tag if this is the
966
   * only section requested */
967
0
  if (!params->section ||
968
0
      (params->section && strcasecmp(params->section, "/") == 0))
969
0
    msIO_printf("<Capability>\n");
970
0
  else
971
0
    msIO_printf("<Capability\n"
972
0
                "   version=\"%s\" \n"
973
0
                "   updateSequence=\"%s\" \n"
974
0
                "   xmlns=\"http://www.opengis.net/wcs\" \n"
975
0
                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
976
0
                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
977
0
                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
978
0
                "   xsi:schemaLocation=\"http://www.opengis.net/wcs "
979
0
                "%s/wcs/%s/wcsCapabilities.xsd\">\n",
980
0
                params->version, params->updatesequence,
981
0
                msOWSGetSchemasLocation(map), params->version);
982
983
  /* describe the types of requests the server can handle */
984
0
  msIO_printf("  <Request>\n");
985
986
0
  msWCSPrintRequestCapability("GetCapabilities", script_url_encoded);
987
0
  if (msOWSRequestIsEnabled(map, NULL, "C", "DescribeCoverage", MS_FALSE))
988
0
    msWCSPrintRequestCapability("DescribeCoverage", script_url_encoded);
989
0
  if (msOWSRequestIsEnabled(map, NULL, "C", "GetCoverage", MS_FALSE))
990
0
    msWCSPrintRequestCapability("GetCoverage", script_url_encoded);
991
992
0
  msIO_printf("  </Request>\n");
993
994
  /* describe the exception formats the server can produce */
995
0
  msIO_printf("  <Exception>\n");
996
0
  msIO_printf("    <Format>application/vnd.ogc.se_xml</Format>\n");
997
0
  msIO_printf("  </Exception>\n");
998
999
  /* describe any vendor specific capabilities */
1000
  /* msIO_printf("  <VendorSpecificCapabilities />\n"); */ /* none yet */
1001
1002
  /* done */
1003
0
  msIO_printf("</Capability>\n");
1004
1005
0
  free(script_url);
1006
0
  free(script_url_encoded);
1007
1008
0
  return MS_SUCCESS;
1009
0
}
1010
1011
/************************************************************************/
1012
/*                    msWCSPrintMetadataLink()                          */
1013
/************************************************************************/
1014
1015
static void msWCSPrintMetadataLink(layerObj *layer,
1016
0
                                   const char *script_url_encoded) {
1017
0
  const char *list =
1018
0
      msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_list");
1019
0
  if (list) {
1020
0
    int ntokens = 0;
1021
0
    char **tokens = msStringSplit(list, ' ', &ntokens);
1022
0
    for (int i = 0; i < ntokens; i++) {
1023
0
      std::string key("metadatalink_");
1024
0
      key += tokens[i];
1025
0
      msOWSPrintURLType(
1026
0
          stdout, &(layer->metadata), "CO", key.c_str(), OWS_NOERR,
1027
0
          "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>", NULL,
1028
0
          " metadataType=\"%s\"", NULL, NULL, NULL, " xlink:href=\"%s\"",
1029
0
          MS_FALSE, MS_FALSE, MS_FALSE, MS_FALSE, MS_TRUE, "other", NULL, NULL,
1030
0
          NULL, NULL, NULL);
1031
0
    }
1032
0
    msFreeCharArray(tokens, ntokens);
1033
0
    return;
1034
0
  }
1035
1036
  /* optional metadataLink */
1037
0
  if (!msOWSLookupMetadata(&(layer->metadata), "CO", "metadatalink_href"))
1038
0
    msMetadataSetGetMetadataURL(layer, script_url_encoded);
1039
1040
0
  msOWSPrintURLType(stdout, &(layer->metadata), "CO", "metadatalink", OWS_NOERR,
1041
0
                    "  <metadataLink%s%s%s%s xlink:type=\"simple\"%s/>", NULL,
1042
0
                    " metadataType=\"%s\"", NULL, NULL, NULL,
1043
0
                    " xlink:href=\"%s\"", MS_FALSE, MS_FALSE, MS_FALSE,
1044
0
                    MS_FALSE, MS_TRUE, "other", NULL, NULL, NULL, NULL, NULL);
1045
0
}
1046
1047
/************************************************************************/
1048
/*             msWCSGetCapabilities_CoverageOfferingBrief()             */
1049
/************************************************************************/
1050
1051
static int
1052
msWCSGetCapabilities_CoverageOfferingBrief(layerObj *layer,
1053
0
                                           const char *script_url_encoded) {
1054
0
  coverageMetadataObj cm;
1055
0
  int status;
1056
1057
0
  if ((layer->status == MS_DELETE) || !msWCSIsLayerSupported(layer))
1058
0
    return MS_SUCCESS; /* not an error, this layer cannot be served via WCS */
1059
1060
0
  status = msWCSGetCoverageMetadata(layer, &cm);
1061
0
  if (status != MS_SUCCESS)
1062
0
    return MS_FAILURE;
1063
1064
  /* start the CoverageOfferingBrief section */
1065
0
  msIO_printf(
1066
0
      "  <CoverageOfferingBrief>\n"); /* is this tag right? (I hate schemas
1067
                                         without ANY examples) */
1068
1069
0
  msWCSPrintMetadataLink(layer, script_url_encoded);
1070
1071
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "description",
1072
0
                           OWS_NOERR, "    <description>%s</description>\n",
1073
0
                           NULL);
1074
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "name", OWS_NOERR,
1075
0
                           "    <name>%s</name>\n", layer->name);
1076
1077
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "label", OWS_WARN,
1078
0
                           "    <label>%s</label>\n", NULL);
1079
1080
  /* TODO: add elevation ranges to lonLatEnvelope (optional) */
1081
0
  msIO_printf(
1082
0
      "    <lonLatEnvelope srsName=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n");
1083
0
  msIO_printf("      <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.minx,
1084
0
              cm.llextent.miny); /* TODO: don't know if this is right */
1085
0
  msIO_printf("      <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.maxx,
1086
0
              cm.llextent.maxy);
1087
1088
0
  msOWSPrintEncodeMetadataList(
1089
0
      stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL,
1090
0
      "      <gml:timePosition>%s</gml:timePosition>\n", NULL);
1091
1092
0
  msIO_printf("    </lonLatEnvelope>\n");
1093
1094
  /* we are not supporting the optional keyword type, at least not yet */
1095
0
  msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "keywordlist",
1096
0
                               "  <keywords>\n", "  </keywords>\n",
1097
0
                               "    <keyword>%s</keyword>\n", NULL);
1098
1099
  /* done */
1100
0
  msIO_printf("  </CoverageOfferingBrief>\n");
1101
1102
0
  msWCSFreeCoverageMetadata(&cm);
1103
1104
0
  return MS_SUCCESS;
1105
0
}
1106
1107
/************************************************************************/
1108
/*                msWCSGetCapabilities_ContentMetadata()                */
1109
/************************************************************************/
1110
1111
static int msWCSGetCapabilities_ContentMetadata(mapObj *map,
1112
                                                wcsParamsObj *params,
1113
                                                owsRequestObj *ows_request,
1114
0
                                                cgiRequestObj *req) {
1115
0
  int i;
1116
0
  char *script_url_encoded = NULL;
1117
1118
0
  {
1119
0
    char *pszTmp = msOWSGetOnlineResource(map, "CO", "onlineresource", req);
1120
0
    script_url_encoded = msEncodeHTMLEntities(pszTmp);
1121
0
    msFree(pszTmp);
1122
0
  }
1123
1124
  /* start the ContentMetadata section, only need the full start tag if this is
1125
   * the only section requested */
1126
  /* TODO: add Xlink attributes for other sources of this information  */
1127
0
  if (!params->section ||
1128
0
      (params->section && strcasecmp(params->section, "/") == 0))
1129
0
    msIO_printf("<ContentMetadata>\n");
1130
0
  else
1131
0
    msIO_printf("<ContentMetadata\n"
1132
0
                "   version=\"%s\" \n"
1133
0
                "   updateSequence=\"%s\" \n"
1134
0
                "   xmlns=\"http://www.opengis.net/wcs\" \n"
1135
0
                "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
1136
0
                "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
1137
0
                "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
1138
0
                "   xsi:schemaLocation=\"http://www.opengis.net/wcs "
1139
0
                "%s/wcs/%s/wcsCapabilities.xsd\">\n",
1140
0
                params->version, params->updatesequence,
1141
0
                msOWSGetSchemasLocation(map), params->version);
1142
1143
0
  if (ows_request->numlayers == 0) {
1144
0
    msIO_printf("  <!-- WARNING: No WCS layers are enabled. Check "
1145
0
                "wcs/ows_enable_request settings. -->\n");
1146
0
  } else {
1147
0
    for (i = 0; i < map->numlayers; i++) {
1148
0
      if (!msIntegerInArray(GET_LAYER(map, i)->index,
1149
0
                            ows_request->enabled_layers,
1150
0
                            ows_request->numlayers))
1151
0
        continue;
1152
1153
0
      if (msWCSGetCapabilities_CoverageOfferingBrief(
1154
0
              (GET_LAYER(map, i)), script_url_encoded) != MS_SUCCESS) {
1155
0
        msIO_printf("  <!-- WARNING: There was a problem with one of layers. "
1156
0
                    "See server log for details. -->\n");
1157
0
      }
1158
0
    }
1159
0
  }
1160
1161
0
  msFree(script_url_encoded);
1162
1163
  /* done */
1164
0
  msIO_printf("</ContentMetadata>\n");
1165
1166
0
  return MS_SUCCESS;
1167
0
}
1168
1169
/************************************************************************/
1170
/*                        msWCSGetCapabilities()                        */
1171
/************************************************************************/
1172
1173
static int msWCSGetCapabilities(mapObj *map, wcsParamsObj *params,
1174
                                cgiRequestObj *req,
1175
0
                                owsRequestObj *ows_request) {
1176
0
  char tmpString[OWS_VERSION_MAXLEN];
1177
0
  int i, tmpInt = 0;
1178
0
  int wcsSupportedVersions[] = {OWS_1_1_2, OWS_1_1_1, OWS_1_1_0, OWS_1_0_0};
1179
0
  int wcsNumSupportedVersions = 4;
1180
0
  const char *updatesequence = NULL;
1181
1182
  /* check version is valid */
1183
0
  tmpInt = msOWSParseVersionString(params->version);
1184
0
  if (tmpInt == OWS_VERSION_BADFORMAT) {
1185
0
    return msWCSException(map, "InvalidParameterValue", "version", "1.0.0 ");
1186
0
  }
1187
1188
  /* negotiate version */
1189
0
  tmpInt = msOWSNegotiateVersion(tmpInt, wcsSupportedVersions,
1190
0
                                 wcsNumSupportedVersions);
1191
1192
  /* set result as string and carry on */
1193
0
  free(params->version);
1194
0
  params->version = msStrdup(msOWSGetVersionString(tmpInt, tmpString));
1195
1196
  /* -------------------------------------------------------------------- */
1197
  /*      1.1.x is sufficiently different we have a whole case for        */
1198
  /*      it.  The remainder of this function is for 1.0.0.               */
1199
  /* -------------------------------------------------------------------- */
1200
0
  if (strncmp(params->version, "1.1", 3) == 0)
1201
0
    return msWCSGetCapabilities11(map, params, req, ows_request);
1202
1203
0
  updatesequence =
1204
0
      msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
1205
1206
0
  if (params->updatesequence != NULL) {
1207
0
    i = msOWSNegotiateUpdateSequence(params->updatesequence, updatesequence);
1208
0
    if (i == 0) { /* current */
1209
0
      msSetError(
1210
0
          MS_WCSERR, "UPDATESEQUENCE parameter (%s) is equal to server (%s)",
1211
0
          "msWCSGetCapabilities()", params->updatesequence, updatesequence);
1212
0
      return msWCSException(map, "CurrentUpdateSequence", "updatesequence",
1213
0
                            params->version);
1214
0
    }
1215
0
    if (i > 0) { /* invalid */
1216
0
      msSetError(
1217
0
          MS_WCSERR, "UPDATESEQUENCE parameter (%s) is higher than server (%s)",
1218
0
          "msWCSGetCapabilities()", params->updatesequence, updatesequence);
1219
0
      return msWCSException(map, "InvalidUpdateSequence", "updatesequence",
1220
0
                            params->version);
1221
0
    }
1222
0
  }
1223
1224
0
  else { /* set default updatesequence */
1225
0
    if (!updatesequence)
1226
0
      updatesequence = "0";
1227
0
    params->updatesequence = msStrdup(updatesequence);
1228
0
  }
1229
1230
  /* if a bum section param is passed, throw exception */
1231
0
  if (params->section &&
1232
0
      strcasecmp(params->section, "/WCS_Capabilities/Service") != 0 &&
1233
0
      strcasecmp(params->section, "/WCS_Capabilities/Capability") != 0 &&
1234
0
      strcasecmp(params->section, "/WCS_Capabilities/ContentMetadata") != 0 &&
1235
0
      strcasecmp(params->section, "/") != 0) {
1236
0
    msSetError(MS_WCSERR, "Invalid SECTION parameter \"%s\"",
1237
0
               "msWCSGetCapabilities()", params->section);
1238
0
    return msWCSException(map, "InvalidParameterValue", "section",
1239
0
                          params->version);
1240
0
  }
1241
1242
0
  else {
1243
0
    msIO_setHeader("Content-Type", "text/xml; charset=UTF-8");
1244
0
    msIO_sendHeaders();
1245
1246
    /* print common capability elements  */
1247
    /* TODO: DocType? */
1248
1249
0
    if (!updatesequence)
1250
0
      updatesequence = "0";
1251
1252
0
    msIO_printf(
1253
0
        "<?xml version='1.0' encoding=\"UTF-8\" standalone=\"no\" ?>\n");
1254
1255
0
    if (!params->section ||
1256
0
        (params->section && strcasecmp(params->section, "/") == 0))
1257
0
      msIO_printf("<WCS_Capabilities\n"
1258
0
                  "   version=\"%s\" \n"
1259
0
                  "   updateSequence=\"%s\" \n"
1260
0
                  "   xmlns=\"http://www.opengis.net/wcs\" \n"
1261
0
                  "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
1262
0
                  "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
1263
0
                  "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
1264
0
                  "   xsi:schemaLocation=\"http://www.opengis.net/wcs "
1265
0
                  "%s/wcs/%s/wcsCapabilities.xsd\">\n",
1266
0
                  params->version, updatesequence, msOWSGetSchemasLocation(map),
1267
0
                  params->version);
1268
1269
    /* print the various capability sections */
1270
0
    if (!params->section ||
1271
0
        strcasecmp(params->section, "/WCS_Capabilities/Service") == 0)
1272
0
      msWCSGetCapabilities_Service(map, params);
1273
1274
0
    if (!params->section ||
1275
0
        strcasecmp(params->section, "/WCS_Capabilities/Capability") == 0)
1276
0
      msWCSGetCapabilities_Capability(map, params, req);
1277
1278
0
    if (!params->section ||
1279
0
        strcasecmp(params->section, "/WCS_Capabilities/ContentMetadata") == 0)
1280
0
      msWCSGetCapabilities_ContentMetadata(map, params, ows_request, req);
1281
1282
0
    if (params->section && strcasecmp(params->section, "/") == 0) {
1283
0
      msWCSGetCapabilities_Service(map, params);
1284
0
      msWCSGetCapabilities_Capability(map, params, req);
1285
0
      msWCSGetCapabilities_ContentMetadata(map, params, ows_request, req);
1286
0
    }
1287
1288
    /* done */
1289
0
    if (!params->section ||
1290
0
        (params->section && strcasecmp(params->section, "/") == 0))
1291
0
      msIO_printf("</WCS_Capabilities>\n");
1292
0
  }
1293
1294
0
  return MS_SUCCESS;
1295
0
}
1296
1297
/************************************************************************/
1298
/*               msWCSDescribeCoverage_AxisDescription()                */
1299
/************************************************************************/
1300
1301
0
static int msWCSDescribeCoverage_AxisDescription(layerObj *layer, char *name) {
1302
0
  const char *value;
1303
0
  char tag[100]; /* should be plenty of space */
1304
1305
0
  msIO_printf("        <axisDescription>\n");
1306
0
  msIO_printf("          <AxisDescription");
1307
0
  snprintf(tag, sizeof(tag), "%s_semantic",
1308
0
           name); /* optional attributes follow (should escape?) */
1309
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1310
0
                           " semantic=\"%s\"", NULL);
1311
0
  snprintf(tag, sizeof(tag), "%s_refsys", name);
1312
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1313
0
                           " refSys=\"%s\"", NULL);
1314
0
  snprintf(tag, sizeof(tag), "%s_refsyslabel", name);
1315
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1316
0
                           " refSysLabel=\"%s\"", NULL);
1317
0
  msIO_printf(">\n");
1318
1319
  /* TODO: add metadataLink (optional) */
1320
1321
0
  snprintf(tag, sizeof(tag), "%s_description", name);
1322
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1323
0
                           "            <description>%s</description>\n", NULL);
1324
  /* snprintf(tag, sizeof(tag), "%s_name", name); */
1325
  /* msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_WARN, "
1326
   * <name>%s</name>\n", NULL); */
1327
0
  msIO_printf("            <name>%s</name>\n", name);
1328
1329
0
  snprintf(tag, sizeof(tag), "%s_label", name);
1330
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_WARN,
1331
0
                           "            <label>%s</label>\n", NULL);
1332
1333
  /* Values */
1334
0
  msIO_printf("            <values");
1335
0
  snprintf(tag, sizeof(tag), "%s_values_semantic",
1336
0
           name); /* optional attributes follow (should escape?) */
1337
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1338
0
                           " semantic=\"%s\"", NULL);
1339
0
  snprintf(tag, sizeof(tag), "%s_values_type", name);
1340
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", tag, OWS_NOERR,
1341
0
                           " type=\"%s\"", NULL);
1342
0
  msIO_printf(">\n");
1343
1344
  /* single values, we do not support optional type and semantic attributes */
1345
0
  snprintf(tag, sizeof(tag), "%s_values", name);
1346
0
  if (msOWSLookupMetadata(&(layer->metadata), "CO", tag))
1347
0
    msOWSPrintEncodeMetadataList(
1348
0
        stdout, &(layer->metadata), "CO", tag, NULL, NULL,
1349
0
        "              <singleValue>%s</singleValue>\n", NULL);
1350
1351
  /* intervals, only one per axis for now, we do not support optional type,
1352
   * atomic and semantic attributes */
1353
0
  snprintf(tag, sizeof(tag), "%s_interval", name);
1354
0
  if ((value = msOWSLookupMetadata(&(layer->metadata), "CO", tag)) != NULL) {
1355
0
    int numtokens = 0;
1356
0
    char **tokens = msStringSplit(value, '/', &numtokens);
1357
0
    if (tokens && numtokens > 0) {
1358
0
      msIO_printf("            <interval>\n");
1359
0
      if (numtokens >= 1)
1360
0
        msIO_printf("            <min>%s</min>\n",
1361
0
                    tokens[0]); /* TODO: handle closure */
1362
0
      if (numtokens >= 2)
1363
0
        msIO_printf("            <max>%s</max>\n", tokens[1]);
1364
0
      if (numtokens >= 3)
1365
0
        msIO_printf("            <res>%s</res>\n", tokens[2]);
1366
0
      msIO_printf("            </interval>\n");
1367
0
    }
1368
0
    msFreeCharArray(tokens, numtokens);
1369
0
  }
1370
1371
  /* TODO: add default (optional) */
1372
1373
0
  msIO_printf("            </values>\n");
1374
1375
0
  msIO_printf("          </AxisDescription>\n");
1376
0
  msIO_printf("        </axisDescription>\n");
1377
1378
0
  return MS_SUCCESS;
1379
0
}
1380
1381
/************************************************************************/
1382
/*               msWCSDescribeCoverage_CoverageOffering()               */
1383
/************************************************************************/
1384
1385
static int msWCSDescribeCoverage_CoverageOffering(layerObj *layer,
1386
                                                  wcsParamsObj *params,
1387
0
                                                  char *script_url_encoded) {
1388
0
  const char *value;
1389
0
  char *epsg_buf, *encoded_format;
1390
0
  coverageMetadataObj cm;
1391
0
  int i, status;
1392
1393
0
  if (msCheckParentPointer(layer->map, "map") == MS_FAILURE)
1394
0
    return MS_FAILURE;
1395
1396
0
  if (!msWCSIsLayerSupported(layer))
1397
0
    return MS_SUCCESS; /* not an error, this layer cannot be served via WCS */
1398
1399
0
  status = msWCSGetCoverageMetadata(layer, &cm);
1400
0
  if (status != MS_SUCCESS)
1401
0
    return MS_FAILURE;
1402
1403
  /* fill in bands rangeset info, if required.  */
1404
0
  msWCSSetDefaultBandsRangeSetInfo(params, &cm, layer);
1405
1406
  /* start the Coverage section */
1407
0
  msIO_printf("  <CoverageOffering>\n");
1408
1409
0
  msWCSPrintMetadataLink(layer, script_url_encoded);
1410
1411
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "description",
1412
0
                           OWS_NOERR, "  <description>%s</description>\n",
1413
0
                           NULL);
1414
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "name", OWS_NOERR,
1415
0
                           "  <name>%s</name>\n", layer->name);
1416
1417
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "label", OWS_WARN,
1418
0
                           "  <label>%s</label>\n", NULL);
1419
1420
  /* TODO: add elevation ranges to lonLatEnvelope (optional) */
1421
0
  msIO_printf(
1422
0
      "    <lonLatEnvelope srsName=\"urn:ogc:def:crs:OGC:1.3:CRS84\">\n");
1423
0
  msIO_printf("      <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.minx,
1424
0
              cm.llextent.miny);
1425
0
  msIO_printf("      <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.maxx,
1426
0
              cm.llextent.maxy);
1427
1428
0
  msOWSPrintEncodeMetadataList(
1429
0
      stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL,
1430
0
      "      <gml:timePosition>%s</gml:timePosition>\n", NULL);
1431
1432
0
  msIO_printf("    </lonLatEnvelope>\n");
1433
1434
  /* we are not supporting the optional keyword type, at least not yet */
1435
0
  msOWSPrintEncodeMetadataList(stdout, &(layer->metadata), "CO", "keywordlist",
1436
0
                               "  <keywords>\n", "  </keywords>\n",
1437
0
                               "    <keyword>%s</keyword>\n", NULL);
1438
1439
  /* DomainSet: starting simple, just a spatial domain (gml:envelope) and
1440
   * optionally a temporal domain */
1441
0
  msIO_printf("    <domainSet>\n");
1442
1443
  /* SpatialDomain */
1444
0
  msIO_printf("      <spatialDomain>\n");
1445
1446
  /* envelope in lat/lon */
1447
0
  msIO_printf("        <gml:Envelope srsName=\"EPSG:4326\">\n");
1448
0
  msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.minx,
1449
0
              cm.llextent.miny);
1450
0
  msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.llextent.maxx,
1451
0
              cm.llextent.maxy);
1452
0
  msIO_printf("        </gml:Envelope>\n");
1453
1454
  /* envelope in the native srs */
1455
0
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE,
1456
0
                   &epsg_buf);
1457
0
  if (!epsg_buf) {
1458
0
    msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata),
1459
0
                     "CO", MS_TRUE, &epsg_buf);
1460
0
  }
1461
0
  if (epsg_buf) {
1462
0
    msIO_printf("        <gml:Envelope srsName=\"%s\">\n", epsg_buf);
1463
0
    msFree(epsg_buf);
1464
0
  } else {
1465
0
    msIO_printf("        <!-- NativeCRSs ERROR: missing required information, "
1466
0
                "no SRSs defined -->\n");
1467
0
  }
1468
0
  msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.extent.minx,
1469
0
              cm.extent.miny);
1470
0
  msIO_printf("          <gml:pos>%.15g %.15g</gml:pos>\n", cm.extent.maxx,
1471
0
              cm.extent.maxy);
1472
0
  msIO_printf("        </gml:Envelope>\n");
1473
1474
  /* gml:rectifiedGrid */
1475
0
  msIO_printf("        <gml:RectifiedGrid dimension=\"2\">\n");
1476
0
  msIO_printf("          <gml:limits>\n");
1477
0
  msIO_printf("            <gml:GridEnvelope>\n");
1478
0
  msIO_printf("              <gml:low>0 0</gml:low>\n");
1479
0
  msIO_printf("              <gml:high>%d %d</gml:high>\n", cm.xsize - 1,
1480
0
              cm.ysize - 1);
1481
0
  msIO_printf("            </gml:GridEnvelope>\n");
1482
0
  msIO_printf("          </gml:limits>\n");
1483
0
  msIO_printf("          <gml:axisName>x</gml:axisName>\n");
1484
0
  msIO_printf("          <gml:axisName>y</gml:axisName>\n");
1485
0
  msIO_printf("          <gml:origin>\n");
1486
0
  msIO_printf("            <gml:pos>%.15g %.15g</gml:pos>\n",
1487
0
              cm.geotransform[0], cm.geotransform[3]);
1488
0
  msIO_printf("          </gml:origin>\n");
1489
0
  msIO_printf("          <gml:offsetVector>%.15g %.15g</gml:offsetVector>\n",
1490
0
              cm.geotransform[1],
1491
0
              cm.geotransform[2]); /* offset vector in X direction */
1492
0
  msIO_printf("          <gml:offsetVector>%.15g %.15g</gml:offsetVector>\n",
1493
0
              cm.geotransform[4],
1494
0
              cm.geotransform[5]); /* offset vector in Y direction */
1495
0
  msIO_printf("        </gml:RectifiedGrid>\n");
1496
1497
0
  msIO_printf("      </spatialDomain>\n");
1498
1499
0
  msWCSFreeCoverageMetadata(&cm);
1500
1501
  /* TemporalDomain */
1502
1503
  /* TODO: figure out when a temporal domain is valid, for example only tiled
1504
   * rasters support time as a domain, plus we need a timeitem */
1505
0
  if (msOWSLookupMetadata(&(layer->metadata), "CO", "timeposition") ||
1506
0
      msOWSLookupMetadata(&(layer->metadata), "CO", "timeperiod")) {
1507
0
    msIO_printf("      <temporalDomain>\n");
1508
1509
    /* TimePosition (should support a value AUTO, then we could mine positions
1510
     * from the timeitem) */
1511
0
    msOWSPrintEncodeMetadataList(
1512
0
        stdout, &(layer->metadata), "CO", "timeposition", NULL, NULL,
1513
0
        "        <gml:timePosition>%s</gml:timePosition>\n", NULL);
1514
1515
    /* TODO:  add TimePeriod (only one per layer)  */
1516
1517
0
    msIO_printf("      </temporalDomain>\n");
1518
0
  }
1519
1520
0
  msIO_printf("    </domainSet>\n");
1521
1522
  /* rangeSet */
1523
0
  msIO_printf("    <rangeSet>\n");
1524
0
  msIO_printf(
1525
0
      "      <RangeSet>\n"); /* TODO: there are some optional attributes */
1526
1527
  /* TODO: add metadataLink (optional) */
1528
1529
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO",
1530
0
                           "rangeset_description", OWS_NOERR,
1531
0
                           "        <description>%s</description>\n", NULL);
1532
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "rangeset_name",
1533
0
                           OWS_WARN, "        <name>%s</name>\n", NULL);
1534
1535
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "rangeset_label",
1536
0
                           OWS_WARN, "        <label>%s</label>\n", NULL);
1537
1538
  /* compound range sets */
1539
0
  if ((value = msOWSLookupMetadata(&(layer->metadata), "CO",
1540
0
                                   "rangeset_axes")) != NULL) {
1541
0
    int numtokens = 0;
1542
0
    char **tokens = msStringSplit(value, ',', &numtokens);
1543
0
    if (tokens && numtokens > 0) {
1544
0
      for (i = 0; i < numtokens; i++)
1545
0
        msWCSDescribeCoverage_AxisDescription(layer, tokens[i]);
1546
0
    }
1547
0
    msFreeCharArray(tokens, numtokens);
1548
0
  }
1549
1550
0
  if ((value = msOWSLookupMetadata(&(layer->metadata), "CO",
1551
0
                                   "rangeset_nullvalue")) != NULL) {
1552
0
    msIO_printf("        <nullValues>\n");
1553
0
    msIO_printf("          <singleValue>%s</singleValue>\n", value);
1554
0
    msIO_printf("        </nullValues>\n");
1555
0
  }
1556
1557
0
  msIO_printf("      </RangeSet>\n");
1558
0
  msIO_printf("    </rangeSet>\n");
1559
1560
  /* supportedCRSs */
1561
0
  msIO_printf("    <supportedCRSs>\n");
1562
1563
  /* requestResponseCRSs: check the layer metadata/projection, and then the map
1564
   * metadata/projection if necessary (should never get to the error message) */
1565
0
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_FALSE,
1566
0
                   &epsg_buf);
1567
0
  if (!epsg_buf) {
1568
0
    msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata),
1569
0
                     "CO", MS_FALSE, &epsg_buf);
1570
0
  }
1571
0
  if (epsg_buf) {
1572
0
    int numtokens = 0;
1573
0
    char **tokens = msStringSplit(epsg_buf, ' ', &numtokens);
1574
0
    if (tokens && numtokens > 0) {
1575
0
      for (i = 0; i < numtokens; i++)
1576
0
        msIO_printf("      <requestResponseCRSs>%s</requestResponseCRSs>\n",
1577
0
                    tokens[i]);
1578
0
    }
1579
0
    msFreeCharArray(tokens, numtokens);
1580
0
    msFree(epsg_buf);
1581
0
  } else {
1582
0
    msIO_printf("      <!-- requestResponseCRSs ERROR: missing required "
1583
0
                "information, no SRSs defined -->\n");
1584
0
  }
1585
1586
  /* nativeCRSs (only one in our case) */
1587
0
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE,
1588
0
                   &epsg_buf);
1589
0
  if (!epsg_buf) {
1590
0
    msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata),
1591
0
                     "CO", MS_TRUE, &epsg_buf);
1592
0
  }
1593
0
  if (epsg_buf) {
1594
0
    msIO_printf("      <nativeCRSs>%s</nativeCRSs>\n", epsg_buf);
1595
0
    msFree(epsg_buf);
1596
0
  } else {
1597
0
    msIO_printf("      <!-- nativeCRSs ERROR: missing required information, no "
1598
0
                "SRSs defined -->\n");
1599
0
  }
1600
1601
0
  msIO_printf("    </supportedCRSs>\n");
1602
1603
  /* supportedFormats */
1604
0
  msIO_printf("    <supportedFormats");
1605
0
  msOWSPrintEncodeMetadata(stdout, &(layer->metadata), "CO", "nativeformat",
1606
0
                           OWS_NOERR, " nativeFormat=\"%s\"", NULL);
1607
0
  msIO_printf(">\n");
1608
1609
0
  if ((encoded_format = msOWSGetEncodeMetadata(&(layer->metadata), "CO",
1610
0
                                               "formats", "GTiff")) != NULL) {
1611
0
    int numtokens = 0;
1612
0
    char **tokens = msStringSplit(encoded_format, ' ', &numtokens);
1613
0
    if (tokens && numtokens > 0) {
1614
0
      for (i = 0; i < numtokens; i++)
1615
0
        msIO_printf("      <formats>%s</formats>\n", tokens[i]);
1616
0
    }
1617
0
    msFreeCharArray(tokens, numtokens);
1618
0
    msFree(encoded_format);
1619
0
  }
1620
0
  msIO_printf("    </supportedFormats>\n");
1621
1622
0
  msIO_printf("    <supportedInterpolations default=\"nearest neighbor\">\n");
1623
0
  msIO_printf(
1624
0
      "      <interpolationMethod>nearest neighbor</interpolationMethod>\n");
1625
0
  msIO_printf("      <interpolationMethod>bilinear</interpolationMethod>\n");
1626
  /*  msIO_printf("      <interpolationMethod>bicubic</interpolationMethod>\n"
1627
   * ); */
1628
0
  msIO_printf("    </supportedInterpolations>\n");
1629
1630
  /* done */
1631
0
  msIO_printf("  </CoverageOffering>\n");
1632
1633
0
  return MS_SUCCESS;
1634
0
}
1635
1636
/************************************************************************/
1637
/*                       msWCSDescribeCoverage()                        */
1638
/************************************************************************/
1639
1640
static int msWCSDescribeCoverage(mapObj *map, wcsParamsObj *params,
1641
                                 owsRequestObj *ows_request,
1642
0
                                 cgiRequestObj *req) {
1643
0
  int i = 0, j = 0, k = 0;
1644
0
  const char *updatesequence = NULL;
1645
0
  char **coverages = NULL;
1646
0
  int numcoverages = 0;
1647
1648
0
  char *coverageName = NULL;
1649
0
  char *script_url_encoded = NULL;
1650
1651
  /* -------------------------------------------------------------------- */
1652
  /*      1.1.x is sufficiently different we have a whole case for        */
1653
  /*      it.  The remainder of this function is for 1.0.0.               */
1654
  /* -------------------------------------------------------------------- */
1655
0
  if (strncmp(params->version, "1.1", 3) == 0)
1656
0
    return msWCSDescribeCoverage11(map, params, ows_request);
1657
1658
  /* -------------------------------------------------------------------- */
1659
  /*      Process 1.0.0...                                                */
1660
  /* -------------------------------------------------------------------- */
1661
1662
0
  if (params->coverages) { /* use the list, but validate it first */
1663
0
    for (j = 0; params->coverages[j]; j++) {
1664
0
      coverages = msStringSplit(params->coverages[j], ',', &numcoverages);
1665
0
      for (k = 0; k < numcoverages; k++) {
1666
1667
0
        for (i = 0; i < map->numlayers; i++) {
1668
0
          coverageName =
1669
0
              msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO",
1670
0
                                     "name", GET_LAYER(map, i)->name);
1671
0
          if (coverageName != NULL && EQUAL(coverageName, coverages[k]) &&
1672
0
              (msIntegerInArray(GET_LAYER(map, i)->index,
1673
0
                                ows_request->enabled_layers,
1674
0
                                ows_request->numlayers))) {
1675
0
            msFree(coverageName);
1676
0
            break;
1677
0
          }
1678
0
          msFree(coverageName);
1679
0
        }
1680
1681
        /* i = msGetLayerIndex(map, coverages[k]); */
1682
0
        if (i == map->numlayers) { /* coverage not found */
1683
0
          msSetError(
1684
0
              MS_WCSERR,
1685
0
              "COVERAGE %s cannot be opened / does not exist. A layer might be disabled for \
1686
0
this request. Check wcs/ows_enable_request settings.",
1687
0
              "msWCSDescribeCoverage()", coverages[k]);
1688
0
          return msWCSException(map, "CoverageNotDefined", "coverage",
1689
0
                                params->version);
1690
0
        }
1691
0
      } /* next coverage */
1692
0
      msFreeCharArray(coverages, numcoverages);
1693
0
    }
1694
0
  }
1695
1696
0
  updatesequence =
1697
0
      msOWSLookupMetadata(&(map->web.metadata), "CO", "updatesequence");
1698
0
  if (!updatesequence)
1699
0
    updatesequence = "0";
1700
1701
  /* printf("Content-Type: application/vnd.ogc.se_xml%c%c",10,10); */
1702
0
  msIO_setHeader("Content-Type", "text/xml; charset=UTF-8");
1703
0
  msIO_sendHeaders();
1704
1705
  /* print common capability elements  */
1706
0
  msIO_printf("<?xml version='1.0' encoding=\"UTF-8\" ?>\n");
1707
1708
  /* start the DescribeCoverage section */
1709
0
  msIO_printf("<CoverageDescription\n"
1710
0
              "   version=\"%s\" \n"
1711
0
              "   updateSequence=\"%s\" \n"
1712
0
              "   xmlns=\"http://www.opengis.net/wcs\" \n"
1713
0
              "   xmlns:xlink=\"http://www.w3.org/1999/xlink\" \n"
1714
0
              "   xmlns:gml=\"http://www.opengis.net/gml\" \n"
1715
0
              "   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
1716
0
              "   xsi:schemaLocation=\"http://www.opengis.net/wcs "
1717
0
              "%s/wcs/%s/describeCoverage.xsd\">\n",
1718
0
              params->version, updatesequence, msOWSGetSchemasLocation(map),
1719
0
              params->version);
1720
1721
0
  {
1722
0
    char *pszTmp = msOWSGetOnlineResource(map, "CO", "onlineresource", req);
1723
0
    script_url_encoded = msEncodeHTMLEntities(pszTmp);
1724
0
    msFree(pszTmp);
1725
0
  }
1726
1727
0
  if (params->coverages) { /* use the list */
1728
0
    for (j = 0; params->coverages[j]; j++) {
1729
0
      coverages = msStringSplit(params->coverages[j], ',', &numcoverages);
1730
0
      for (k = 0; k < numcoverages; k++) {
1731
0
        for (i = 0; i < map->numlayers; i++) {
1732
0
          coverageName =
1733
0
              msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO",
1734
0
                                     "name", GET_LAYER(map, i)->name);
1735
0
          if (coverageName != NULL && EQUAL(coverageName, coverages[k])) {
1736
0
            msFree(coverageName);
1737
0
            break;
1738
0
          }
1739
0
          msFree(coverageName);
1740
0
        }
1741
0
        msWCSDescribeCoverage_CoverageOffering((GET_LAYER(map, i)), params,
1742
0
                                               script_url_encoded);
1743
0
      }
1744
0
      msFreeCharArray(coverages, numcoverages);
1745
0
    }
1746
0
  } else { /* return all layers */
1747
0
    for (i = 0; i < map->numlayers; i++) {
1748
0
      if (!msIntegerInArray(GET_LAYER(map, i)->index,
1749
0
                            ows_request->enabled_layers,
1750
0
                            ows_request->numlayers))
1751
0
        continue;
1752
1753
0
      msWCSDescribeCoverage_CoverageOffering((GET_LAYER(map, i)), params,
1754
0
                                             script_url_encoded);
1755
0
    }
1756
0
  }
1757
1758
0
  msFree(script_url_encoded);
1759
1760
  /* done */
1761
0
  msIO_printf("</CoverageDescription>\n");
1762
1763
0
  return MS_SUCCESS;
1764
0
}
1765
1766
/************************************************************************/
1767
/*                       msWCSGetCoverageBands10()                      */
1768
/************************************************************************/
1769
1770
static int msWCSGetCoverageBands10(mapObj *map, cgiRequestObj *request,
1771
                                   wcsParamsObj *params, layerObj *lp,
1772
                                   char **p_bandlist)
1773
1774
0
{
1775
0
  const char *value = NULL;
1776
0
  int i;
1777
1778
  /* Are there any non-spatio/temporal ranges to do subsetting on (e.g. bands)
1779
   */
1780
0
  value = msOWSLookupMetadata(
1781
0
      &(lp->metadata), "CO",
1782
0
      "rangeset_axes"); /* this will get all the compound range sets */
1783
0
  if (value) {
1784
0
    char **tokens;
1785
0
    int numtokens;
1786
0
    char tag[100];
1787
0
    const char *rangeitem;
1788
1789
0
    tokens = msStringSplit(value, ',', &numtokens);
1790
1791
0
    for (i = 0; i < numtokens; i++) {
1792
0
      if ((value = msWCSGetRequestParameter(request, tokens[i])) == NULL)
1793
0
        continue; /* next rangeset parameter */
1794
1795
      /* ok, a parameter has been passed which matches a token in
1796
       * wcs_rangeset_axes */
1797
0
      if (msWCSValidateRangeSetParam(lp, tokens[i], value) != MS_SUCCESS) {
1798
0
        int ret;
1799
0
        msSetError(MS_WCSERR, "Error specifying \"%s\" parameter value(s).",
1800
0
                   "msWCSGetCoverage()", tokens[i]);
1801
0
        ret = msWCSException(map, "InvalidParameterValue", tokens[i],
1802
0
                             params->version);
1803
0
        msFreeCharArray(tokens, numtokens);
1804
0
        return ret;
1805
0
      }
1806
1807
      /* xxxxx_rangeitem tells us how to subset */
1808
0
      snprintf(tag, sizeof(tag), "%s_rangeitem", tokens[i]);
1809
0
      if ((rangeitem = msOWSLookupMetadata(&(lp->metadata), "CO", tag)) ==
1810
0
          NULL) {
1811
0
        msSetError(MS_WCSERR,
1812
0
                   "Missing required metadata element \"%s\", unable to "
1813
0
                   "process %s=%s.",
1814
0
                   "msWCSGetCoverage()", tag, tokens[i], value);
1815
0
        msFreeCharArray(tokens, numtokens);
1816
0
        return msWCSException(map, NULL, NULL, params->version);
1817
0
      }
1818
1819
0
      if (strcasecmp(rangeitem, "_bands") ==
1820
0
          0) { /* special case, subset bands */
1821
0
        *p_bandlist = msWCSConvertRangeSetToString(value);
1822
1823
0
        if (!*p_bandlist) {
1824
0
          msSetError(MS_WCSERR, "Error specifying \"%s\" parameter value(s).",
1825
0
                     "msWCSGetCoverage()", tokens[i]);
1826
0
          msFreeCharArray(tokens, numtokens);
1827
0
          return msWCSException(map, NULL, NULL, params->version);
1828
0
        }
1829
0
      } else if (strcasecmp(rangeitem, "_pixels") ==
1830
0
                 0) { /* special case, subset pixels */
1831
0
        msFreeCharArray(tokens, numtokens);
1832
0
        msSetError(
1833
0
            MS_WCSERR,
1834
0
            "Arbitrary range sets based on pixel values are not yet supported.",
1835
0
            "msWCSGetCoverage()");
1836
0
        return msWCSException(map, NULL, NULL, params->version);
1837
0
      } else {
1838
0
        msFreeCharArray(tokens, numtokens);
1839
0
        msSetError(MS_WCSERR,
1840
0
                   "Arbitrary range sets based on tile (i.e. image) attributes "
1841
0
                   "are not yet supported.",
1842
0
                   "msWCSGetCoverage()");
1843
0
        return msWCSException(map, NULL, NULL, params->version);
1844
0
      }
1845
0
    }
1846
    /* clean-up */
1847
0
    msFreeCharArray(tokens, numtokens);
1848
0
  }
1849
1850
0
  return MS_SUCCESS;
1851
0
}
1852
1853
/************************************************************************/
1854
/*                   msWCSGetCoverage_ImageCRSSetup()                   */
1855
/*                                                                      */
1856
/*      The request was in imageCRS - update the map projection to      */
1857
/*      map the native projection of the layer, and reset the           */
1858
/*      bounding box to match the projected bounds corresponding to     */
1859
/*      the imageCRS request.                                           */
1860
/************************************************************************/
1861
1862
static int msWCSGetCoverage_ImageCRSSetup(mapObj *map, wcsParamsObj *params,
1863
                                          coverageMetadataObj *cm,
1864
                                          layerObj *layer)
1865
1866
0
{
1867
  /* -------------------------------------------------------------------- */
1868
  /*      Load map with the layer (coverage) coordinate system.  We       */
1869
  /*      really need a set projectionObj from projectionObj function!    */
1870
  /* -------------------------------------------------------------------- */
1871
0
  char *layer_proj = msGetProjectionString(&(layer->projection));
1872
1873
0
  if (msLoadProjectionString(&(map->projection), layer_proj) != 0) {
1874
0
    msFree(layer_proj);
1875
0
    return msWCSException(map, NULL, NULL, params->version);
1876
0
  }
1877
1878
0
  free(layer_proj);
1879
0
  layer_proj = NULL;
1880
1881
  /* -------------------------------------------------------------------- */
1882
  /*      Reset bounding box.                                             */
1883
  /* -------------------------------------------------------------------- */
1884
0
  if (params->bbox.maxx != params->bbox.minx) {
1885
0
    rectObj orig_bbox = params->bbox;
1886
1887
0
    params->bbox.minx = cm->geotransform[0] +
1888
0
                        orig_bbox.minx * cm->geotransform[1] +
1889
0
                        orig_bbox.miny * cm->geotransform[2];
1890
0
    params->bbox.maxy = cm->geotransform[3] +
1891
0
                        orig_bbox.minx * cm->geotransform[4] +
1892
0
                        orig_bbox.miny * cm->geotransform[5];
1893
0
    params->bbox.maxx = cm->geotransform[0] +
1894
0
                        (orig_bbox.maxx + 1) * cm->geotransform[1] +
1895
0
                        (orig_bbox.maxy + 1) * cm->geotransform[2];
1896
0
    params->bbox.miny = cm->geotransform[3] +
1897
0
                        (orig_bbox.maxx + 1) * cm->geotransform[4] +
1898
0
                        (orig_bbox.maxy + 1) * cm->geotransform[5];
1899
1900
    /* WCS 1.1 boundbox is center of pixel oriented. */
1901
0
    if (strncasecmp(params->version, "1.1", 3) == 0) {
1902
0
      params->bbox.minx += cm->geotransform[1] / 2 + cm->geotransform[2] / 2;
1903
0
      params->bbox.maxx -= cm->geotransform[1] / 2 + cm->geotransform[2] / 2;
1904
0
      params->bbox.maxy += cm->geotransform[4] / 2 + cm->geotransform[5] / 2;
1905
0
      params->bbox.miny -= cm->geotransform[4] / 2 + cm->geotransform[5] / 2;
1906
0
    }
1907
0
  }
1908
1909
  /* -------------------------------------------------------------------- */
1910
  /*      Reset resolution.                                               */
1911
  /* -------------------------------------------------------------------- */
1912
0
  if (params->resx != 0.0) {
1913
0
    params->resx = cm->geotransform[1] * params->resx;
1914
0
    params->resy = fabs(cm->geotransform[5] * params->resy);
1915
0
  }
1916
1917
0
  return MS_SUCCESS;
1918
0
}
1919
1920
/************************************************************************/
1921
/*                    msWCSApplyLayerCreationOptions()                  */
1922
/************************************************************************/
1923
1924
void msWCSApplyLayerCreationOptions(layerObj *lp, outputFormatObj *format,
1925
                                    const char *bandlist)
1926
1927
0
{
1928
0
  const char *pszKey;
1929
0
  char szKeyBeginning[256];
1930
0
  size_t nKeyBeginningLength;
1931
0
  int nBands = 0;
1932
0
  char **papszBandNumbers = msStringSplit(bandlist, ',', &nBands);
1933
1934
0
  snprintf(szKeyBeginning, sizeof(szKeyBeginning),
1935
0
           "wcs_outputformat_%s_creationoption_", format->name);
1936
0
  nKeyBeginningLength = strlen(szKeyBeginning);
1937
1938
0
  pszKey = msFirstKeyFromHashTable(&(lp->metadata));
1939
0
  for (; pszKey != NULL;
1940
0
       pszKey = msNextKeyFromHashTable(&(lp->metadata), pszKey)) {
1941
0
    if (strncmp(pszKey, szKeyBeginning, nKeyBeginningLength) == 0) {
1942
0
      const char *pszValue = msLookupHashTable(&(lp->metadata), pszKey);
1943
0
      const char *pszGDALKey = pszKey + nKeyBeginningLength;
1944
0
      if (EQUALN(pszGDALKey, "BAND_", strlen("BAND_"))) {
1945
        /* Remap BAND specific creation option to the real output
1946
         * band number, given the band subset of the request */
1947
0
        int nKeyOriBandNumber = atoi(pszGDALKey + strlen("BAND_"));
1948
0
        int nTargetBandNumber = -1;
1949
0
        int i;
1950
0
        for (i = 0; i < nBands; i++) {
1951
0
          if (nKeyOriBandNumber == atoi(papszBandNumbers[i])) {
1952
0
            nTargetBandNumber = i + 1;
1953
0
            break;
1954
0
          }
1955
0
        }
1956
0
        if (nTargetBandNumber > 0) {
1957
0
          char szModKey[256];
1958
0
          const char *pszAfterBand = strchr(pszGDALKey + strlen("BAND_"), '_');
1959
0
          if (pszAfterBand != NULL) {
1960
0
            snprintf(szModKey, sizeof(szModKey), "BAND_%d%s", nTargetBandNumber,
1961
0
                     pszAfterBand);
1962
0
            if (lp->debug >= MS_DEBUGLEVEL_VVV) {
1963
0
              msDebug("Setting GDAL %s=%s creation option\n", szModKey,
1964
0
                      pszValue);
1965
0
            }
1966
0
            msSetOutputFormatOption(format, szModKey, pszValue);
1967
0
          }
1968
0
        }
1969
0
      } else {
1970
0
        if (lp->debug >= MS_DEBUGLEVEL_VVV) {
1971
0
          msDebug("Setting GDAL %s=%s creation option\n", pszGDALKey, pszValue);
1972
0
        }
1973
0
        msSetOutputFormatOption(format, pszGDALKey, pszValue);
1974
0
      }
1975
0
    }
1976
0
  }
1977
1978
0
  msFreeCharArray(papszBandNumbers, nBands);
1979
0
}
1980
1981
/************************************************************************/
1982
/*               msWCSApplyDatasetMetadataAsCreationOptions()           */
1983
/************************************************************************/
1984
1985
void msWCSApplyDatasetMetadataAsCreationOptions(layerObj *lp,
1986
                                                outputFormatObj *format,
1987
                                                const char *bandlist,
1988
0
                                                void *hDSIn) {
1989
  /* Requires GDAL 2.3 in practice. */
1990
  /* Automatic forwarding of input dataset metadata if it is GRIB and the */
1991
  /* output is GRIB as well, and wcs_outputformat_GRIB_creationoption* are */
1992
  /* not defined. */
1993
0
  GDALDatasetH hDS = (GDALDatasetH)hDSIn;
1994
0
  if (hDS && GDALGetDatasetDriver(hDS) &&
1995
0
      EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hDS)), "GRIB") &&
1996
0
      EQUAL(format->driver, "GDAL/GRIB")) {
1997
0
    const char *pszKey;
1998
0
    char szKeyBeginning[256];
1999
0
    size_t nKeyBeginningLength;
2000
0
    int bWCSMetadataFound = MS_FALSE;
2001
2002
0
    snprintf(szKeyBeginning, sizeof(szKeyBeginning),
2003
0
             "wcs_outputformat_%s_creationoption_", format->name);
2004
0
    nKeyBeginningLength = strlen(szKeyBeginning);
2005
2006
0
    for (pszKey = msFirstKeyFromHashTable(&(lp->metadata)); pszKey != NULL;
2007
0
         pszKey = msNextKeyFromHashTable(&(lp->metadata), pszKey)) {
2008
0
      if (strncmp(pszKey, szKeyBeginning, nKeyBeginningLength) == 0) {
2009
0
        bWCSMetadataFound = MS_TRUE;
2010
0
        break;
2011
0
      }
2012
0
    }
2013
0
    if (!bWCSMetadataFound) {
2014
0
      int nBands = 0;
2015
0
      char **papszBandNumbers = msStringSplit(bandlist, ',', &nBands);
2016
0
      int i;
2017
0
      for (i = 0; i < nBands; i++) {
2018
0
        int nSrcBand = atoi(papszBandNumbers[i]);
2019
0
        int nDstBand = i + 1;
2020
0
        GDALRasterBandH hBand = GDALGetRasterBand(hDS, nSrcBand);
2021
0
        if (hBand) {
2022
0
          CSLConstList papszMD = GDALGetMetadata(hBand, NULL);
2023
0
          const char *pszMDI = CSLFetchNameValue(papszMD, "GRIB_IDS");
2024
          // Make sure it is a GRIB2 band
2025
0
          if (pszMDI) {
2026
0
            char szKey[256];
2027
0
            snprintf(szKey, sizeof(szKey), "BAND_%d_IDS", nDstBand);
2028
0
            msSetOutputFormatOption(format, szKey, pszMDI);
2029
2030
0
            snprintf(szKey, sizeof(szKey), "BAND_%d_DISCIPLINE", nDstBand);
2031
0
            msSetOutputFormatOption(format, szKey,
2032
0
                                    CSLFetchNameValue(papszMD, "DISCIPLINE"));
2033
2034
0
            snprintf(szKey, sizeof(szKey), "BAND_%d_PDS_PDTN", nDstBand);
2035
0
            msSetOutputFormatOption(
2036
0
                format, szKey, CSLFetchNameValue(papszMD, "GRIB_PDS_PDTN"));
2037
2038
0
            snprintf(szKey, sizeof(szKey), "BAND_%d_PDS_TEMPLATE_NUMBERS",
2039
0
                     nDstBand);
2040
0
            msSetOutputFormatOption(
2041
0
                format, szKey,
2042
0
                CSLFetchNameValue(papszMD, "GRIB_PDS_TEMPLATE_NUMBERS"));
2043
0
          }
2044
0
        }
2045
0
      }
2046
0
      msFreeCharArray(papszBandNumbers, nBands);
2047
0
    }
2048
0
  }
2049
0
}
2050
2051
/************************************************************************/
2052
/*                  msWCSApplyLayerMetadataItemOptions()                */
2053
/************************************************************************/
2054
2055
void msWCSApplyLayerMetadataItemOptions(layerObj *lp, outputFormatObj *format,
2056
                                        const char *bandlist)
2057
2058
0
{
2059
0
  if (!STARTS_WITH(format->driver, "GDAL/"))
2060
0
    return;
2061
2062
0
  const bool bIsNetCDFOutput = EQUAL(format->driver, "GDAL/netCDF");
2063
0
  const char *pszKey;
2064
0
  char szKeyBeginning[256];
2065
0
  size_t nKeyBeginningLength;
2066
0
  int nBands = 0;
2067
0
  char **papszBandNumbers = msStringSplit(bandlist, ',', &nBands);
2068
2069
0
  snprintf(szKeyBeginning, sizeof(szKeyBeginning), "wcs_outputformat_%s_mdi_",
2070
0
           format->name);
2071
0
  nKeyBeginningLength = strlen(szKeyBeginning);
2072
2073
  // Transform wcs_outputformat_{formatname}_mdi_{key} to mdi_{key}
2074
  // and Transform wcs_outputformat_{formatname}_mdi_BAND_X_{key} to
2075
  // mdi_BAND_Y_{key} MDI stands for MetaDataItem
2076
2077
  // For netCDF 3D output
2078
0
  std::map<int, std::string> oMapExtraDimValues;
2079
0
  std::string osExtraDimName;
2080
0
  bool bExtraDimValid = false;
2081
2082
0
  pszKey = msFirstKeyFromHashTable(&(lp->metadata));
2083
0
  for (; pszKey != NULL;
2084
0
       pszKey = msNextKeyFromHashTable(&(lp->metadata), pszKey)) {
2085
0
    if (strncmp(pszKey, szKeyBeginning, nKeyBeginningLength) == 0) {
2086
0
      const char *pszValue = msLookupHashTable(&(lp->metadata), pszKey);
2087
0
      const char *pszGDALKey = pszKey + nKeyBeginningLength;
2088
2089
0
      if (EQUALN(pszGDALKey, "BAND_", strlen("BAND_"))) {
2090
        /* Remap BAND specific creation option to the real output
2091
         * band number, given the band subset of the request */
2092
0
        int nKeyOriBandNumber = atoi(pszGDALKey + strlen("BAND_"));
2093
0
        int nTargetBandNumber = -1;
2094
0
        int i;
2095
0
        for (i = 0; i < nBands; i++) {
2096
0
          if (nKeyOriBandNumber == atoi(papszBandNumbers[i])) {
2097
0
            nTargetBandNumber = i + 1;
2098
0
            break;
2099
0
          }
2100
0
        }
2101
0
        if (nTargetBandNumber > 0) {
2102
0
          char szModKey[256];
2103
0
          const char *pszAfterBand = strchr(pszGDALKey + strlen("BAND_"), '_');
2104
0
          if (pszAfterBand != NULL) {
2105
            // Special case to generate 3D netCDF files
2106
0
            if (bIsNetCDFOutput &&
2107
0
                strncmp(pszAfterBand, "_default_NETCDF_DIM_",
2108
0
                        strlen("_default_NETCDF_DIM_")) == 0) {
2109
0
              const char *pszDimName =
2110
0
                  pszAfterBand + strlen("_default_NETCDF_DIM_");
2111
0
              if (osExtraDimName.empty()) {
2112
0
                bExtraDimValid = true;
2113
0
                osExtraDimName = pszDimName;
2114
0
                oMapExtraDimValues[nTargetBandNumber] = pszValue;
2115
0
              } else if (bExtraDimValid) {
2116
0
                if (osExtraDimName != pszDimName) {
2117
0
                  msDebug("One band has several %sdefault_NETCDF_DIM_ metadata "
2118
0
                          "items, "
2119
0
                          "or different bands have a different value. "
2120
0
                          "Only a single extra dimension is supported.",
2121
0
                          szKeyBeginning);
2122
0
                  bExtraDimValid = false;
2123
0
                } else {
2124
0
                  oMapExtraDimValues[nTargetBandNumber] = pszValue;
2125
0
                }
2126
0
              }
2127
0
            } else {
2128
0
              snprintf(szModKey, sizeof(szModKey), "mdi_BAND_%d%s",
2129
0
                       nTargetBandNumber, pszAfterBand);
2130
0
              if (lp->debug >= MS_DEBUGLEVEL_VVV) {
2131
0
                msDebug("Setting GDAL %s=%s metadata item option\n", szModKey,
2132
0
                        pszValue);
2133
0
              }
2134
0
              msSetOutputFormatOption(format, szModKey, pszValue);
2135
0
            }
2136
0
          }
2137
0
        }
2138
0
      } else {
2139
0
        char szModKey[256];
2140
0
        snprintf(szModKey, sizeof(szModKey), "mdi_%s", pszGDALKey);
2141
0
        if (lp->debug >= MS_DEBUGLEVEL_VVV) {
2142
0
          msDebug("Setting GDAL %s=%s metadata item option\n", szModKey,
2143
0
                  pszValue);
2144
0
        }
2145
0
        msSetOutputFormatOption(format, szModKey, pszValue);
2146
0
      }
2147
0
    }
2148
0
  }
2149
2150
  // netCDF 3D output
2151
  // Tested in msautotest/wxs/wcs_netcdf_3d_output.map
2152
0
  std::string osExtraDimDataType;
2153
0
  if (bExtraDimValid && static_cast<int>(oMapExtraDimValues.size()) != nBands) {
2154
0
    msDebug("One of the band lack a NETCDF_DIM_%s metadata item.",
2155
0
            osExtraDimName.c_str());
2156
0
    bExtraDimValid = false;
2157
0
  }
2158
0
  if (bExtraDimValid) {
2159
0
    for (const auto &keyValue : oMapExtraDimValues) {
2160
0
      const auto &osVal = keyValue.second;
2161
0
      const CPLValueType eType = CPLGetValueType(osVal.c_str());
2162
0
      if (eType == CPL_VALUE_STRING) {
2163
0
        osExtraDimDataType = "string";
2164
0
        break;
2165
0
      } else if (eType == CPL_VALUE_INTEGER) {
2166
0
        if (osExtraDimDataType.empty() || osExtraDimDataType == "integer") {
2167
0
          osExtraDimDataType = "integer";
2168
0
          const GIntBig nVal = CPLAtoGIntBig(osVal.c_str());
2169
0
          if (nVal > INT_MAX || nVal < INT_MIN) {
2170
0
            osExtraDimDataType = "integer64";
2171
0
          }
2172
0
        }
2173
0
      } else {
2174
0
        osExtraDimDataType = "double";
2175
0
      }
2176
0
    }
2177
0
    if (osExtraDimDataType == "string") {
2178
0
      msDebug("One of the value for the NETCDF_DIM_%s metadata is a string. "
2179
0
              "This is not supported",
2180
0
              osExtraDimName.c_str());
2181
0
      bExtraDimValid = false;
2182
0
    }
2183
0
  }
2184
0
  if (bExtraDimValid) {
2185
    // Cf
2186
    // https://gdal.org/drivers/raster/netcdf.html#creation-of-multidimensional-files-with-createcopy-2d-raster-api
2187
2188
    // Define the name of the extra dimensions
2189
0
    {
2190
0
      std::string osValue;
2191
0
      osValue = '{';
2192
0
      osValue += osExtraDimName;
2193
0
      osValue += '}';
2194
2195
0
      msSetOutputFormatOption(format, "mdi_default_NETCDF_DIM_EXTRA",
2196
0
                              osValue.c_str());
2197
0
    }
2198
2199
    // Define the size (in number of samples) and type of the extra dimension
2200
0
    {
2201
0
      std::string osKey;
2202
0
      osKey = "mdi_default_NETCDF_DIM_";
2203
0
      osKey += osExtraDimName;
2204
0
      osKey += "_DEF";
2205
2206
0
      std::string osValue;
2207
0
      osValue = '{';
2208
0
      osValue += CPLSPrintf("%d", nBands);
2209
0
      osValue += ',';
2210
0
      if (osExtraDimDataType == "integer")
2211
0
        osValue += '4';
2212
0
      else if (osExtraDimDataType == "integer64")
2213
0
        osValue += "10";
2214
0
      else /* if ( osExtraDimDataType == "double" ) */
2215
0
        osValue += '6';
2216
0
      osValue += '}';
2217
2218
0
      msSetOutputFormatOption(format, osKey.c_str(), osValue.c_str());
2219
0
    }
2220
2221
    // Define the values along the extra dimension
2222
0
    {
2223
0
      std::string osKey;
2224
0
      osKey = "mdi_default_NETCDF_DIM_";
2225
0
      osKey += osExtraDimName;
2226
0
      osKey += "_VALUES";
2227
0
      std::string osValue;
2228
0
      osValue = '{';
2229
0
      bool bFirstVal = true;
2230
0
      for (const auto &keyValue : oMapExtraDimValues) {
2231
0
        const auto &osVal = keyValue.second;
2232
0
        if (!bFirstVal)
2233
0
          osValue += ',';
2234
0
        else
2235
0
          bFirstVal = false;
2236
0
        osValue += osVal;
2237
0
      }
2238
0
      osValue += '}';
2239
2240
0
      msSetOutputFormatOption(format, osKey.c_str(), osValue.c_str());
2241
0
    }
2242
0
  }
2243
2244
0
  msFreeCharArray(papszBandNumbers, nBands);
2245
0
}
2246
2247
/************************************************************************/
2248
/*               msWCSApplySourceDatasetMetadata()                      */
2249
/************************************************************************/
2250
2251
void msWCSApplySourceDatasetMetadata(layerObj *lp, outputFormatObj *format,
2252
0
                                     const char *bandlist, void *hDSIn) {
2253
  /* Automatic forwarding of input dataset metadata if it is netCDF and the */
2254
  /* output is netCDF as well, and wcs_outputformat_netCDF_mdi* are */
2255
  /* not defined. */
2256
0
  GDALDatasetH hDS = (GDALDatasetH)hDSIn;
2257
0
  if (hDS && GDALGetDatasetDriver(hDS) &&
2258
0
      EQUAL(GDALGetDriverShortName(GDALGetDatasetDriver(hDS)), "netCDF") &&
2259
0
      EQUAL(format->driver, "GDAL/netCDF")) {
2260
0
    const char *pszKey;
2261
0
    char szKeyBeginning[256];
2262
0
    size_t nKeyBeginningLength;
2263
0
    int bWCSMetadataFound = MS_FALSE;
2264
2265
0
    snprintf(szKeyBeginning, sizeof(szKeyBeginning), "wcs_outputformat_%s_mdi_",
2266
0
             format->name);
2267
0
    nKeyBeginningLength = strlen(szKeyBeginning);
2268
2269
0
    for (pszKey = msFirstKeyFromHashTable(&(lp->metadata)); pszKey != NULL;
2270
0
         pszKey = msNextKeyFromHashTable(&(lp->metadata), pszKey)) {
2271
0
      if (strncmp(pszKey, szKeyBeginning, nKeyBeginningLength) == 0) {
2272
0
        bWCSMetadataFound = MS_TRUE;
2273
0
        break;
2274
0
      }
2275
0
    }
2276
0
    if (!bWCSMetadataFound) {
2277
0
      int nBands = 0;
2278
0
      char **papszBandNumbers = msStringSplit(bandlist, ',', &nBands);
2279
2280
0
      std::string osExtraDimName;
2281
      // Special processing if the input dataset is a 3D one
2282
0
      {
2283
        // Check if extra dimensions are declared on the source dataset,
2284
        // and if so, if there's just a single one.
2285
0
        const char *pszDimExtraWithCurl =
2286
0
            GDALGetMetadataItem(hDS, "NETCDF_DIM_EXTRA", nullptr);
2287
0
        if (pszDimExtraWithCurl &&
2288
0
            strchr(pszDimExtraWithCurl, ',') == nullptr &&
2289
0
            pszDimExtraWithCurl[0] == '{' &&
2290
0
            pszDimExtraWithCurl[strlen(pszDimExtraWithCurl) - 1] == '}') {
2291
0
          osExtraDimName.append(pszDimExtraWithCurl + 1,
2292
0
                                strlen(pszDimExtraWithCurl) - 2);
2293
2294
          // Declare the extra dimension name
2295
0
          msSetOutputFormatOption(format, "mdi_default_NETCDF_DIM_EXTRA",
2296
0
                                  pszDimExtraWithCurl);
2297
2298
          // Declare the extra dimension definition: size + data type
2299
0
          const char *pszDimExtraDef = GDALGetMetadataItem(
2300
0
              hDS, ("NETCDF_DIM_" + osExtraDimName + "_DEF").c_str(), nullptr);
2301
0
          if (pszDimExtraDef && pszDimExtraDef[0] == '{' &&
2302
0
              pszDimExtraDef[strlen(pszDimExtraDef) - 1] == '}') {
2303
0
            const auto tokens = msStringSplit(
2304
0
                std::string(pszDimExtraDef + 1, strlen(pszDimExtraDef) - 2)
2305
0
                    .c_str(),
2306
0
                ',');
2307
0
            if (tokens.size() == 2) {
2308
0
              const auto &varType = tokens[1];
2309
0
              msSetOutputFormatOption(
2310
0
                  format,
2311
0
                  ("mdi_default_NETCDF_DIM_" + osExtraDimName + "_DEF").c_str(),
2312
0
                  (std::string("{") + CPLSPrintf("%d", nBands) + ',' + varType +
2313
0
                   '}')
2314
0
                      .c_str());
2315
0
            }
2316
0
          }
2317
2318
          // Declare the extra dimension values
2319
0
          const char *pszDimExtraValues = GDALGetMetadataItem(
2320
0
              hDS, ("NETCDF_DIM_" + osExtraDimName + "_VALUES").c_str(),
2321
0
              nullptr);
2322
0
          if (pszDimExtraValues && pszDimExtraValues[0] == '{' &&
2323
0
              pszDimExtraValues[strlen(pszDimExtraValues) - 1] == '}') {
2324
0
            const auto tokens =
2325
0
                msStringSplit(std::string(pszDimExtraValues + 1,
2326
0
                                          strlen(pszDimExtraValues) - 2)
2327
0
                                  .c_str(),
2328
0
                              ',');
2329
0
            if (static_cast<int>(tokens.size()) == GDALGetRasterCount(hDS)) {
2330
0
              std::string osValue = "{";
2331
0
              for (int i = 0; i < nBands; i++) {
2332
0
                int nSrcBand = atoi(papszBandNumbers[i]);
2333
0
                assert(nSrcBand >= 1 &&
2334
0
                       nSrcBand <= static_cast<int>(tokens.size()));
2335
0
                if (i > 0)
2336
0
                  osValue += ',';
2337
0
                osValue += tokens[nSrcBand - 1];
2338
0
              }
2339
0
              osValue += '}';
2340
2341
0
              msSetOutputFormatOption(
2342
0
                  format,
2343
0
                  ("mdi_default_NETCDF_DIM_" + osExtraDimName + "_VALUES")
2344
0
                      .c_str(),
2345
0
                  osValue.c_str());
2346
0
            }
2347
0
          } else if (pszDimExtraValues) {
2348
            // If there's a single value
2349
0
            msSetOutputFormatOption(
2350
0
                format,
2351
0
                ("mdi_default_NETCDF_DIM_" + osExtraDimName + "_VALUES")
2352
0
                    .c_str(),
2353
0
                pszDimExtraValues);
2354
0
          }
2355
0
        }
2356
0
      }
2357
2358
0
      {
2359
0
        CSLConstList papszMD = GDALGetMetadata(hDS, NULL);
2360
0
        if (papszMD) {
2361
0
          for (CSLConstList papszIter = papszMD; *papszIter; ++papszIter) {
2362
            // Copy netCDF global attributes, as well as the ones
2363
            // of the extra dimension for 3D netCDF files
2364
0
            if (STARTS_WITH(*papszIter, "NC_GLOBAL#") ||
2365
0
                (!osExtraDimName.empty() &&
2366
0
                 STARTS_WITH(*papszIter, osExtraDimName.c_str()) &&
2367
0
                 (*papszIter)[osExtraDimName.size()] == '#')) {
2368
0
              char *pszKey = nullptr;
2369
0
              const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
2370
0
              if (pszKey && pszValue) {
2371
0
                char szKey[256];
2372
0
                snprintf(szKey, sizeof(szKey), "mdi_default_%s", pszKey);
2373
0
                msSetOutputFormatOption(format, szKey, pszValue);
2374
0
              }
2375
0
              CPLFree(pszKey);
2376
0
            }
2377
0
          }
2378
0
        }
2379
0
      }
2380
2381
0
      for (int i = 0; i < nBands; i++) {
2382
0
        int nSrcBand = atoi(papszBandNumbers[i]);
2383
0
        int nDstBand = i + 1;
2384
0
        GDALRasterBandH hBand = GDALGetRasterBand(hDS, nSrcBand);
2385
0
        if (hBand) {
2386
0
          CSLConstList papszMD = GDALGetMetadata(hBand, NULL);
2387
0
          if (papszMD) {
2388
0
            for (CSLConstList papszIter = papszMD; *papszIter; ++papszIter) {
2389
0
              char *pszKey = nullptr;
2390
0
              const char *pszValue = CPLParseNameValue(*papszIter, &pszKey);
2391
0
              if (pszKey && pszValue && !EQUAL(pszKey, "grid_name") &&
2392
0
                  !EQUAL(pszKey, "grid_mapping")) {
2393
0
                char szKey[256];
2394
0
                snprintf(szKey, sizeof(szKey), "mdi_BAND_%d_default_%s",
2395
0
                         nDstBand, pszKey);
2396
0
                msSetOutputFormatOption(format, szKey, pszValue);
2397
0
              }
2398
0
              CPLFree(pszKey);
2399
0
            }
2400
0
          }
2401
0
        }
2402
0
      }
2403
0
      msFreeCharArray(papszBandNumbers, nBands);
2404
0
    }
2405
0
  }
2406
0
}
2407
2408
/************************************************************************/
2409
/*                          msWCSGetCoverage()                          */
2410
/************************************************************************/
2411
2412
static int msWCSGetCoverage(mapObj *map, cgiRequestObj *request,
2413
0
                            wcsParamsObj *params, owsRequestObj *ows_request) {
2414
0
  imageObj *image;
2415
0
  layerObj *lp;
2416
0
  int status, i;
2417
0
  const char *value;
2418
0
  outputFormatObj *format;
2419
0
  char *bandlist = NULL;
2420
0
  size_t bufferSize = 0;
2421
0
  char numbands[12]; /* should be large enough to hold the number of bands in
2422
                        the bandlist */
2423
0
  coverageMetadataObj cm;
2424
0
  rectObj reqextent;
2425
0
  rectObj covextent;
2426
0
  rasterBufferObj rb;
2427
0
  int doDrawRasterLayerDraw = MS_TRUE;
2428
0
  GDALDatasetH hDS = NULL;
2429
2430
0
  char *coverageName;
2431
2432
  /* make sure all required parameters are available (at least the easy ones) */
2433
0
  if (!params->crs) {
2434
0
    msSetError(MS_WCSERR, "Required parameter CRS was not supplied.",
2435
0
               "msWCSGetCoverage()");
2436
0
    return msWCSException(map, "MissingParameterValue", "crs", params->version);
2437
0
  }
2438
2439
0
  if (!params->time && !params->bbox.minx && !params->bbox.miny &&
2440
0
      !params->bbox.maxx && !params->bbox.maxy) {
2441
0
    msSetError(MS_WCSERR, "One of BBOX or TIME is required",
2442
0
               "msWCSGetCoverage()");
2443
0
    return msWCSException(map, "MissingParameterValue", "bbox/time",
2444
0
                          params->version);
2445
0
  }
2446
2447
0
  if (params->coverages == NULL || params->coverages[0] == NULL) {
2448
0
    msSetError(MS_WCSERR, "Required parameter COVERAGE was not supplied.",
2449
0
               "msWCSGetCoverage()");
2450
0
    return msWCSException(map, "MissingParameterValue", "coverage",
2451
0
                          params->version);
2452
0
  }
2453
2454
  /* For WCS 1.1, we need to normalize the axis order of the BBOX and
2455
     resolution values some coordinate systems (eg. EPSG geographic) */
2456
0
  if (strncasecmp(params->version, "1.0", 3) != 0 && params->crs != NULL &&
2457
0
      strncasecmp(params->crs, "urn:", 4) == 0) {
2458
0
    projectionObj proj;
2459
2460
0
    msInitProjection(&proj);
2461
0
    msProjectionInheritContextFrom(&proj, &(map->projection));
2462
0
    if (msLoadProjectionString(&proj, (char *)params->crs) == 0) {
2463
0
      msAxisNormalizePoints(&proj, 1, &(params->bbox.minx),
2464
0
                            &(params->bbox.miny));
2465
0
      msAxisNormalizePoints(&proj, 1, &(params->bbox.maxx),
2466
0
                            &(params->bbox.maxy));
2467
0
      msAxisNormalizePoints(&proj, 1, &(params->resx), &(params->resy));
2468
0
      msAxisNormalizePoints(&proj, 1, &(params->originx), &(params->originy));
2469
0
    } else
2470
0
      msResetErrorList();
2471
0
    msFreeProjection(&proj);
2472
0
  }
2473
2474
  /* find the layer we are working with */
2475
0
  lp = NULL;
2476
0
  for (i = 0; i < map->numlayers; i++) {
2477
0
    coverageName = msOWSGetEncodeMetadata(&(GET_LAYER(map, i)->metadata), "CO",
2478
0
                                          "name", GET_LAYER(map, i)->name);
2479
0
    if (coverageName != NULL && EQUAL(coverageName, params->coverages[0]) &&
2480
0
        (msIntegerInArray(GET_LAYER(map, i)->index, ows_request->enabled_layers,
2481
0
                          ows_request->numlayers))) {
2482
0
      lp = GET_LAYER(map, i);
2483
0
      free(coverageName);
2484
0
      break;
2485
0
    }
2486
0
    free(coverageName);
2487
0
  }
2488
2489
0
  if (lp == NULL) {
2490
0
    msSetError(
2491
0
        MS_WCSERR,
2492
0
        "COVERAGE=%s not found, not in supported layer list. A layer might be disabled for \
2493
0
this request. Check wcs/ows_enable_request settings.",
2494
0
        "msWCSGetCoverage()", params->coverages[0]);
2495
0
    return msWCSException(map, "InvalidParameterValue", "coverage",
2496
0
                          params->version);
2497
0
  }
2498
2499
  /* make sure the layer is on */
2500
0
  lp->status = MS_ON;
2501
2502
  /* If the layer has no projection set, set it to the map's projection (#4079)
2503
   */
2504
0
  if (lp->projection.numargs <= 0) {
2505
0
    char *map_original_srs = msGetProjectionString(&(map->projection));
2506
0
    if (msLoadProjectionString(&(lp->projection), map_original_srs) != 0) {
2507
0
      msSetError(
2508
0
          MS_WCSERR,
2509
0
          "Error when setting map projection to a layer with no projection",
2510
0
          "msWCSGetCoverage()");
2511
0
      free(map_original_srs);
2512
0
      return msWCSException(map, NULL, NULL, params->version);
2513
0
    }
2514
0
    free(map_original_srs);
2515
0
  }
2516
2517
  /* we need the coverage metadata, since things like numbands may not be
2518
   * available otherwise */
2519
0
  status = msWCSGetCoverageMetadata(lp, &cm);
2520
0
  if (status != MS_SUCCESS)
2521
0
    return MS_FAILURE;
2522
2523
  /* fill in bands rangeset info, if required.  */
2524
0
  msWCSSetDefaultBandsRangeSetInfo(params, &cm, lp);
2525
2526
  /* handle the response CRS, that is, set the map object projection */
2527
0
  if (params->response_crs || params->crs) {
2528
0
    int iUnits;
2529
0
    const char *crs_to_use = params->response_crs;
2530
0
    if (crs_to_use == NULL)
2531
0
      crs_to_use = params->crs;
2532
2533
0
    if (strcasecmp(crs_to_use, "imageCRS") == 0) {
2534
      /* use layer native CRS, and rework bounding box accordingly */
2535
0
      if (msWCSGetCoverage_ImageCRSSetup(map, params, &cm, lp) != MS_SUCCESS) {
2536
0
        msWCSFreeCoverageMetadata(&cm);
2537
0
        return MS_FAILURE;
2538
0
      }
2539
0
    } else if (strncasecmp(crs_to_use, "urn:ogc:def:crs:", 16) == 0 ||
2540
0
               strncasecmp(crs_to_use, "http://www.opengis.net/def/crs/", 31) ==
2541
0
                   0 ||
2542
0
               strchr(crs_to_use, ':') != NULL) {
2543
      /* Handles URNs, OGC URIs, and any AUTHORITY:CODE pattern
2544
      ** e.g. EPSG:4326, ESRI:54052, CRS:84, IAU_2015:30100 */
2545
0
      if (msLoadProjectionString(&(map->projection), (char *)crs_to_use) != 0) {
2546
0
        msSetError(MS_WCSERR, "Unsupported or unknown CRS '%s'.",
2547
0
                   "msWCSGetCoverage()", crs_to_use);
2548
0
        return msWCSException(map, "InvalidParameterValue", "srs",
2549
0
                              params->version);
2550
0
      }
2551
0
    } else {
2552
0
      msSetError(
2553
0
          MS_WCSERR,
2554
0
          "Unsupported SRS format '%s' (expected AUTHORITY:CODE, URN, or URI).",
2555
0
          "msWCSGetCoverage()", crs_to_use);
2556
0
      return msWCSException(map, "InvalidParameterValue", "srs",
2557
0
                            params->version);
2558
0
    }
2559
2560
0
    iUnits = GetMapserverUnitUsingProj(&(map->projection));
2561
0
    if (iUnits != -1)
2562
0
      map->units = static_cast<MS_UNITS>(iUnits);
2563
0
  }
2564
2565
  /* did we get a TIME value (support only a single value for now) */
2566
0
  if (params->time) {
2567
0
    int tli;
2568
0
    layerObj *tlp = NULL;
2569
2570
    /* need to handle NOW case */
2571
2572
    /* check format of TIME parameter */
2573
0
    if (strchr(params->time, ',')) {
2574
0
      msWCSFreeCoverageMetadata(&cm);
2575
0
      msSetError(MS_WCSERR,
2576
0
                 "Temporal lists are not supported, only individual values.",
2577
0
                 "msWCSGetCoverage()");
2578
0
      return msWCSException(map, "InvalidParameterValue", "time",
2579
0
                            params->version);
2580
0
    }
2581
0
    if (strchr(params->time, '/')) {
2582
0
      msWCSFreeCoverageMetadata(&cm);
2583
0
      msSetError(MS_WCSERR,
2584
0
                 "Temporal ranges are not supported, only individual values.",
2585
0
                 "msWCSGetCoverage()");
2586
0
      return msWCSException(map, "InvalidParameterValue", "time",
2587
0
                            params->version);
2588
0
    }
2589
2590
    /* TODO: will need to expand this check if a time period is supported */
2591
0
    value = msOWSLookupMetadata(&(lp->metadata), "CO", "timeposition");
2592
0
    if (!value) {
2593
0
      msWCSFreeCoverageMetadata(&cm);
2594
0
      msSetError(MS_WCSERR,
2595
0
                 "The coverage does not support temporal subsetting.",
2596
0
                 "msWCSGetCoverage()");
2597
0
      return msWCSException(map, "InvalidParameterValue", "time",
2598
0
                            params->version);
2599
0
    }
2600
2601
    /* check if timestamp is covered by the wcs_timeposition definition */
2602
0
    if (msValidateTimeValue(params->time, value) == MS_FALSE) {
2603
0
      msWCSFreeCoverageMetadata(&cm);
2604
0
      msSetError(MS_WCSERR, "The coverage does not have a time position of %s.",
2605
0
                 "msWCSGetCoverage()", params->time);
2606
0
      return msWCSException(map, "InvalidParameterValue", "time",
2607
0
                            params->version);
2608
0
    }
2609
2610
    /* make sure layer is tiled appropriately */
2611
0
    if (!lp->tileindex) {
2612
0
      msWCSFreeCoverageMetadata(&cm);
2613
0
      msSetError(
2614
0
          MS_WCSERR,
2615
0
          "Underlying layer is not tiled, unable to do temporal subsetting.",
2616
0
          "msWCSGetCoverage()");
2617
0
      return msWCSException(map, NULL, NULL, params->version);
2618
0
    }
2619
0
    tli = msGetLayerIndex(map, lp->tileindex);
2620
0
    if (tli == -1) {
2621
0
      msWCSFreeCoverageMetadata(&cm);
2622
0
      msSetError(MS_WCSERR,
2623
0
                 "Underlying layer does not use appropriate tiling mechanism.",
2624
0
                 "msWCSGetCoverage()");
2625
0
      return msWCSException(map, NULL, NULL, params->version);
2626
0
    }
2627
2628
0
    tlp = (GET_LAYER(map, tli));
2629
2630
    /* make sure there is enough information to filter */
2631
0
    value = msOWSLookupMetadata(&(lp->metadata), "CO", "timeitem");
2632
0
    if (!tlp->filteritem && !value) {
2633
0
      msWCSFreeCoverageMetadata(&cm);
2634
0
      msSetError(MS_WCSERR, "Not enough information available to filter.",
2635
0
                 "msWCSGetCoverage()");
2636
0
      return msWCSException(map, NULL, NULL, params->version);
2637
0
    }
2638
2639
    /* override filteritem if specified in metadata */
2640
0
    if (value) {
2641
0
      if (tlp->filteritem)
2642
0
        free(tlp->filteritem);
2643
0
      tlp->filteritem = msStrdup(value);
2644
0
    }
2645
2646
    /* finally set the filter */
2647
0
    msLayerSetTimeFilter(tlp, params->time, value);
2648
0
  }
2649
2650
0
  if (strncasecmp(params->version, "1.0", 3) == 0)
2651
0
    status = msWCSGetCoverageBands10(map, request, params, lp, &bandlist);
2652
0
  else
2653
0
    status = msWCSGetCoverageBands11(map, request, params, lp, &bandlist);
2654
0
  if (status != MS_SUCCESS) {
2655
0
    msWCSFreeCoverageMetadata(&cm);
2656
0
    return status;
2657
0
  }
2658
2659
  /* did we get BBOX values? if not use the extent stored in the
2660
   * coverageMetadataObj */
2661
0
  if (fabs((params->bbox.maxx - params->bbox.minx)) < 0.000000000001 ||
2662
0
      fabs(params->bbox.maxy - params->bbox.miny) < 0.000000000001) {
2663
0
    params->bbox = cm.extent;
2664
2665
    /* WCS 1.1 boundbox is center of pixel oriented. */
2666
0
    if (strncasecmp(params->version, "1.1", 3) == 0) {
2667
0
      params->bbox.minx += cm.geotransform[1] / 2 + cm.geotransform[2] / 2;
2668
0
      params->bbox.maxx -= cm.geotransform[1] / 2 + cm.geotransform[2] / 2;
2669
0
      params->bbox.maxy += cm.geotransform[4] / 2 + cm.geotransform[5] / 2;
2670
0
      params->bbox.miny -= cm.geotransform[4] / 2 + cm.geotransform[5] / 2;
2671
0
    }
2672
0
  }
2673
2674
  /* WCS 1.1+ GridOrigin is effectively resetting the minx/maxy
2675
     BOUNDINGBOX values, so apply that here */
2676
0
  if (params->originx != 0.0 || params->originy != 0.0) {
2677
0
    assert(strncasecmp(params->version, "1.0", 3) !=
2678
0
           0); /* should always be 1.0 in this logic. */
2679
0
    params->bbox.minx = params->originx;
2680
0
    params->bbox.maxy = params->originy;
2681
0
  }
2682
2683
  /* if necessary, project the BBOX to the map->projection */
2684
0
  if (params->response_crs && params->crs) {
2685
0
    projectionObj tmp_proj;
2686
2687
0
    msInitProjection(&tmp_proj);
2688
0
    msProjectionInheritContextFrom(&tmp_proj, &(map->projection));
2689
0
    if (msLoadProjectionString(&tmp_proj, (char *)params->crs) != 0) {
2690
0
      msFreeProjection(&tmp_proj);
2691
0
      msWCSFreeCoverageMetadata(&cm);
2692
0
      return msWCSException(map, NULL, NULL, params->version);
2693
0
    }
2694
0
    msProjectRect(&tmp_proj, &map->projection, &(params->bbox));
2695
0
    msFreeProjection(&tmp_proj);
2696
0
  }
2697
2698
  /* in WCS 1.1 the default is full resolution */
2699
0
  if (strncasecmp(params->version, "1.1", 3) == 0 && params->resx == 0.0 &&
2700
0
      params->resy == 0.0) {
2701
0
    params->resx = cm.geotransform[1];
2702
0
    params->resy = fabs(cm.geotransform[5]);
2703
0
  }
2704
2705
  /* compute width/height from BBOX and cellsize.  */
2706
0
  if ((params->resx == 0.0 || params->resy == 0.0) && params->width != 0 &&
2707
0
      params->height != 0) {
2708
0
    assert(strncasecmp(params->version, "1.0", 3) ==
2709
0
           0); /* should always be 1.0 in this logic. */
2710
0
    params->resx = (params->bbox.maxx - params->bbox.minx) / params->width;
2711
0
    params->resy = (params->bbox.maxy - params->bbox.miny) / params->height;
2712
0
  }
2713
2714
  /* compute cellsize/res from bbox and raster size. */
2715
0
  if ((params->width == 0 || params->height == 0) && params->resx != 0 &&
2716
0
      params->resy != 0) {
2717
2718
    /* WCS 1.0 boundbox is edge of pixel oriented. */
2719
0
    if (strncasecmp(params->version, "1.0", 3) == 0) {
2720
0
      params->width =
2721
0
          (int)((params->bbox.maxx - params->bbox.minx) / params->resx + 0.5);
2722
0
      params->height =
2723
0
          (int)((params->bbox.maxy - params->bbox.miny) / params->resy + 0.5);
2724
0
    } else {
2725
0
      params->width =
2726
0
          (int)((params->bbox.maxx - params->bbox.minx) / params->resx +
2727
0
                1.000001);
2728
0
      params->height =
2729
0
          (int)((params->bbox.maxy - params->bbox.miny) / params->resy +
2730
0
                1.000001);
2731
2732
      /* recompute bounding box so we get exactly the origin and
2733
         resolution requested. */
2734
0
      params->bbox.maxx =
2735
0
          params->bbox.minx + (params->width - 1) * params->resx;
2736
0
      params->bbox.miny =
2737
0
          params->bbox.maxy - (params->height - 1) * params->resy;
2738
0
    }
2739
0
  }
2740
2741
  /* are we still underspecified?  */
2742
0
  if ((params->width == 0 || params->height == 0) &&
2743
0
      (params->resx == 0.0 || params->resy == 0.0)) {
2744
0
    msWCSFreeCoverageMetadata(&cm);
2745
0
    msSetError(MS_WCSERR,
2746
0
               "A non-zero RESX/RESY or WIDTH/HEIGHT is required but neither "
2747
0
               "was provided.",
2748
0
               "msWCSGetCoverage()");
2749
0
    return msWCSException(map, "MissingParameterValue",
2750
0
                          "width/height/resx/resy", params->version);
2751
0
  }
2752
2753
0
  map->cellsize = params->resx;
2754
2755
  /* Do we need to force special handling?  */
2756
0
  if (fabs(params->resx / params->resy - 1.0) > 0.001) {
2757
0
    map->gt.need_geotransform = MS_TRUE;
2758
0
    if (map->debug)
2759
0
      msDebug("RESX and RESY don't match.  Using geotransform/resample.\n");
2760
0
  }
2761
2762
  /* Do we have a specified interpolation method */
2763
0
  if (params->interpolation != NULL) {
2764
0
    if (strncasecmp(params->interpolation, "NEAREST", 7) == 0)
2765
0
      msLayerSetProcessingKey(lp, "RESAMPLE", "NEAREST");
2766
0
    else if (strcasecmp(params->interpolation, "BILINEAR") == 0)
2767
0
      msLayerSetProcessingKey(lp, "RESAMPLE", "BILINEAR");
2768
0
    else if (strcasecmp(params->interpolation, "AVERAGE") == 0)
2769
0
      msLayerSetProcessingKey(lp, "RESAMPLE", "AVERAGE");
2770
0
    else {
2771
0
      msWCSFreeCoverageMetadata(&cm);
2772
0
      msSetError(
2773
0
          MS_WCSERR,
2774
0
          "INTERPOLATION=%s specifies an unsupported interpolation method.",
2775
0
          "msWCSGetCoverage()", params->interpolation);
2776
0
      return msWCSException(map, "InvalidParameterValue", "interpolation",
2777
0
                            params->version);
2778
0
    }
2779
0
  }
2780
2781
  /* apply region and size to map object.  */
2782
0
  map->width = params->width;
2783
0
  map->height = params->height;
2784
2785
  /* Are we exceeding the MAXSIZE limit on result size? */
2786
0
  if (map->width > map->maxsize || map->height > map->maxsize) {
2787
0
    msWCSFreeCoverageMetadata(&cm);
2788
0
    msSetError(MS_WCSERR,
2789
0
               "Raster size out of range, width and height of resulting "
2790
0
               "coverage must be no more than MAXSIZE=%d.",
2791
0
               "msWCSGetCoverage()", map->maxsize);
2792
2793
0
    return msWCSException(map, "InvalidParameterValue", "width/height",
2794
0
                          params->version);
2795
0
  }
2796
2797
  /* adjust OWS BBOX to MapServer's pixel model */
2798
0
  if (strncasecmp(params->version, "1.0", 3) == 0) {
2799
0
    params->bbox.minx += params->resx * 0.5;
2800
0
    params->bbox.miny += params->resy * 0.5;
2801
0
    params->bbox.maxx -= params->resx * 0.5;
2802
0
    params->bbox.maxy -= params->resy * 0.5;
2803
0
  }
2804
2805
0
  map->extent = params->bbox;
2806
2807
0
  map->cellsize = params->resx; /* pick one, MapServer only supports square
2808
                                   cells (what about msAdjustExtent here!) */
2809
2810
0
  if (params->width == 1 || params->height == 1)
2811
0
    msMapComputeGeotransformEx(map, params->resx, params->resy);
2812
0
  else
2813
0
    msMapComputeGeotransform(map);
2814
2815
  /* Do we need to fake out stuff for rotated support? */
2816
0
  if (map->gt.need_geotransform)
2817
0
    msMapSetFakedExtent(map);
2818
2819
0
  map->projection.gt = map->gt;
2820
2821
  /* check for overlap */
2822
2823
  /* get extent of bbox passed, and reproject */
2824
0
  reqextent.minx = map->extent.minx;
2825
0
  reqextent.miny = map->extent.miny;
2826
0
  reqextent.maxx = map->extent.maxx;
2827
0
  reqextent.maxy = map->extent.maxy;
2828
2829
  /* reproject incoming bbox */
2830
0
  msProjectRect(&map->projection, &lp->projection, &(reqextent));
2831
2832
  /* get extent of layer */
2833
0
  covextent.minx = cm.extent.minx;
2834
0
  covextent.miny = cm.extent.miny;
2835
0
  covextent.maxx = cm.extent.maxx;
2836
0
  covextent.maxy = cm.extent.maxy;
2837
2838
0
  if (msRectOverlap(&reqextent, &covextent) == MS_FALSE) {
2839
0
    msWCSFreeCoverageMetadata(&cm);
2840
0
    msSetError(MS_WCSERR,
2841
0
               "Requested BBOX (%.15g,%.15g,%.15g,%.15g) is outside requested "
2842
0
               "coverage BBOX (%.15g,%.15g,%.15g,%.15g)",
2843
0
               "msWCSGetCoverage()", reqextent.minx, reqextent.miny,
2844
0
               reqextent.maxx, reqextent.maxy, covextent.minx, covextent.miny,
2845
0
               covextent.maxx, covextent.maxy);
2846
0
    return msWCSException(map, "NoApplicableCode", "bbox", params->version);
2847
0
  }
2848
2849
  /* check and make sure there is a format, and that it's valid (TODO: make sure
2850
   * in the layer metadata) */
2851
0
  if (!params->format) {
2852
0
    msWCSFreeCoverageMetadata(&cm);
2853
0
    msSetError(MS_WCSERR, "Missing required FORMAT parameter.",
2854
0
               "msWCSGetCoverage()");
2855
0
    return msWCSException(map, "MissingParameterValue", "format",
2856
0
                          params->version);
2857
0
  }
2858
0
  msApplyDefaultOutputFormats(map);
2859
0
  if (msGetOutputFormatIndex(map, params->format) == -1) {
2860
0
    msWCSFreeCoverageMetadata(&cm);
2861
0
    msSetError(MS_WCSERR, "Unrecognized value for the FORMAT parameter.",
2862
0
               "msWCSGetCoverage()");
2863
0
    return msWCSException(map, "InvalidParameterValue", "format",
2864
0
                          params->version);
2865
0
  }
2866
2867
  /* create a temporary outputformat (we likely will need to tweak parts) */
2868
0
  format = msCloneOutputFormat(msSelectOutputFormat(map, params->format));
2869
0
  msApplyOutputFormat(&(map->outputformat), format, MS_NOOVERRIDE);
2870
2871
0
  if (!bandlist) { /* build a bandlist (default is ALL bands) */
2872
0
    bufferSize = cm.bandcount * 30 + 30;
2873
0
    bandlist = (char *)msSmallMalloc(bufferSize);
2874
0
    strcpy(bandlist, "1");
2875
0
    for (i = 1; i < cm.bandcount; i++)
2876
0
      snprintf(bandlist + strlen(bandlist), bufferSize - strlen(bandlist),
2877
0
               ",%d", i + 1);
2878
0
  }
2879
2880
  /* apply nullvalue to the output format object if we have it */
2881
0
  if ((value = msOWSLookupMetadata(&(lp->metadata), "CO",
2882
0
                                   "rangeset_nullvalue")) != NULL) {
2883
0
    msSetOutputFormatOption(map->outputformat, "NULLVALUE", value);
2884
0
  }
2885
2886
0
  msLayerSetProcessingKey(lp, "BANDS", bandlist);
2887
0
  snprintf(numbands, sizeof(numbands), "%d", msCountChars(bandlist, ',') + 1);
2888
0
  msSetOutputFormatOption(map->outputformat, "BAND_COUNT", numbands);
2889
2890
0
  msWCSApplyLayerCreationOptions(lp, map->outputformat, bandlist);
2891
0
  msWCSApplyLayerMetadataItemOptions(lp, map->outputformat, bandlist);
2892
2893
0
  if (lp->tileindex == NULL && lp->data != NULL && strlen(lp->data) > 0 &&
2894
0
      lp->connectiontype != MS_KERNELDENSITY) {
2895
0
    if (msDrawRasterLayerLowCheckIfMustDraw(map, lp)) {
2896
0
      char *decrypted_path = NULL;
2897
0
      char szPath[MS_MAXPATHLEN];
2898
0
      hDS = (GDALDatasetH)msDrawRasterLayerLowOpenDataset(
2899
0
          map, lp, lp->data, szPath, &decrypted_path);
2900
0
      msFree(decrypted_path);
2901
0
      if (hDS) {
2902
0
        msWCSApplyDatasetMetadataAsCreationOptions(lp, map->outputformat,
2903
0
                                                   bandlist, hDS);
2904
0
        msWCSApplySourceDatasetMetadata(lp, map->outputformat, bandlist, hDS);
2905
0
      }
2906
0
    } else {
2907
0
      doDrawRasterLayerDraw = MS_FALSE;
2908
0
    }
2909
0
  }
2910
2911
0
  free(bandlist);
2912
2913
0
  if (lp->mask) {
2914
0
    int maskLayerIdx = msGetLayerIndex(map, lp->mask);
2915
0
    layerObj *maskLayer;
2916
0
    outputFormatObj *altFormat;
2917
0
    if (maskLayerIdx == -1) {
2918
0
      msWCSFreeCoverageMetadata(&cm);
2919
0
      msSetError(MS_MISCERR, "Layer (%s) references unknown mask layer (%s)",
2920
0
                 "msDrawLayer()", lp->name, lp->mask);
2921
0
      msDrawRasterLayerLowCloseDataset(lp, hDS);
2922
0
      return msWCSException(map, NULL, NULL, params->version);
2923
0
    }
2924
0
    maskLayer = GET_LAYER(map, maskLayerIdx);
2925
0
    if (!maskLayer->maskimage) {
2926
0
      int i, retcode;
2927
0
      int origstatus, origlabelcache;
2928
0
      char *origImageType = msStrdup(map->imagetype);
2929
0
      altFormat = msSelectOutputFormat(map, "png24");
2930
0
      msInitializeRendererVTable(altFormat);
2931
      /* TODO: check the png24 format hasn't been tampered with, i.e. it's agg
2932
       */
2933
0
      maskLayer->maskimage = msImageCreate(
2934
0
          map->width, map->height, altFormat, map->web.imagepath,
2935
0
          map->web.imageurl, map->resolution, map->defresolution, NULL);
2936
0
      if (!maskLayer->maskimage) {
2937
0
        msWCSFreeCoverageMetadata(&cm);
2938
0
        msSetError(MS_MISCERR, "Unable to initialize mask image.",
2939
0
                   "msDrawLayer()");
2940
0
        msFree(origImageType);
2941
0
        msDrawRasterLayerLowCloseDataset(lp, hDS);
2942
0
        return msWCSException(map, NULL, NULL, params->version);
2943
0
      }
2944
2945
      /*
2946
       * force the masked layer to status on, and turn off the labelcache so
2947
       * that eventual labels are added to the temporary image instead of being
2948
       * added to the labelcache
2949
       */
2950
0
      origstatus = maskLayer->status;
2951
0
      origlabelcache = maskLayer->labelcache;
2952
0
      maskLayer->status = MS_ON;
2953
0
      maskLayer->labelcache = MS_OFF;
2954
2955
      /* draw the mask layer in the temporary image */
2956
0
      retcode = msDrawLayer(map, maskLayer, maskLayer->maskimage);
2957
0
      maskLayer->status = origstatus;
2958
0
      maskLayer->labelcache = origlabelcache;
2959
0
      if (retcode != MS_SUCCESS) {
2960
0
        msWCSFreeCoverageMetadata(&cm);
2961
        /* set the imagetype from the original outputformat back (it was removed
2962
         * by msSelectOutputFormat() */
2963
0
        msFree(map->imagetype);
2964
0
        map->imagetype = origImageType;
2965
0
        msDrawRasterLayerLowCloseDataset(lp, hDS);
2966
0
        return msWCSException(map, NULL, NULL, params->version);
2967
0
      }
2968
      /*
2969
       * hack to work around bug #3834: if we have use an alternate renderer,
2970
       * the symbolset may contain symbols that reference it. We want to remove
2971
       * those references before the altFormat is destroyed to avoid a segfault
2972
       * and/or a leak, and so the the main renderer doesn't pick the cache up
2973
       * thinking it's for him.
2974
       */
2975
0
      for (i = 0; i < map->symbolset.numsymbols; i++) {
2976
0
        if (map->symbolset.symbol[i] != NULL) {
2977
0
          symbolObj *s = map->symbolset.symbol[i];
2978
0
          if (s->renderer == MS_IMAGE_RENDERER(maskLayer->maskimage)) {
2979
0
            MS_IMAGE_RENDERER(maskLayer->maskimage)->freeSymbol(s);
2980
0
            s->renderer = NULL;
2981
0
          }
2982
0
        }
2983
0
      }
2984
      /* set the imagetype from the original outputformat back (it was removed
2985
       * by msSelectOutputFormat() */
2986
0
      msFree(map->imagetype);
2987
0
      map->imagetype = origImageType;
2988
0
    }
2989
0
  }
2990
2991
  /* create the image object  */
2992
0
  if (!map->outputformat) {
2993
0
    msWCSFreeCoverageMetadata(&cm);
2994
0
    msSetError(MS_WCSERR, "The map outputformat is missing!",
2995
0
               "msWCSGetCoverage()");
2996
0
    msDrawRasterLayerLowCloseDataset(lp, hDS);
2997
0
    return msWCSException(map, NULL, NULL, params->version);
2998
0
  } else if (MS_RENDERER_RAWDATA(map->outputformat) ||
2999
0
             MS_RENDERER_PLUGIN(map->outputformat)) {
3000
0
    image = msImageCreate(map->width, map->height, map->outputformat,
3001
0
                          map->web.imagepath, map->web.imageurl,
3002
0
                          map->resolution, map->defresolution, NULL);
3003
0
  } else {
3004
0
    msWCSFreeCoverageMetadata(&cm);
3005
0
    msSetError(MS_WCSERR, "Map outputformat not supported for WCS!",
3006
0
               "msWCSGetCoverage()");
3007
0
    msDrawRasterLayerLowCloseDataset(lp, hDS);
3008
0
    return msWCSException(map, NULL, NULL, params->version);
3009
0
  }
3010
3011
0
  if (image == NULL) {
3012
0
    msWCSFreeCoverageMetadata(&cm);
3013
0
    msDrawRasterLayerLowCloseDataset(lp, hDS);
3014
0
    return msWCSException(map, NULL, NULL, params->version);
3015
0
  }
3016
0
  if (MS_RENDERER_RAWDATA(map->outputformat)) {
3017
0
    if (doDrawRasterLayerDraw) {
3018
0
      status = msDrawRasterLayerLowWithDataset(map, lp, image, NULL, hDS);
3019
0
    } else {
3020
0
      status = MS_SUCCESS;
3021
0
    }
3022
0
  } else {
3023
0
    status = MS_IMAGE_RENDERER(image)->getRasterBufferHandle(image, &rb);
3024
0
    if (MS_UNLIKELY(status == MS_FAILURE)) {
3025
0
      msWCSFreeCoverageMetadata(&cm);
3026
0
      msDrawRasterLayerLowCloseDataset(lp, hDS);
3027
0
      return MS_FAILURE;
3028
0
    }
3029
3030
    /* Actually produce the "grid". */
3031
0
    if (doDrawRasterLayerDraw) {
3032
0
      status = msDrawRasterLayerLowWithDataset(map, lp, image, &rb, hDS);
3033
0
    } else {
3034
0
      status = MS_SUCCESS;
3035
0
    }
3036
0
  }
3037
0
  msDrawRasterLayerLowCloseDataset(lp, hDS);
3038
3039
0
  if (status != MS_SUCCESS) {
3040
0
    msWCSFreeCoverageMetadata(&cm);
3041
0
    msFreeImage(image);
3042
0
    return msWCSException(map, NULL, NULL, params->version);
3043
0
  }
3044
3045
0
  if (strncmp(params->version, "1.1", 3) == 0) {
3046
0
    msWCSReturnCoverage11(params, map, image);
3047
0
  } else { /* WCS 1.0.0 - just return the binary data with a content type */
3048
0
    const char *fo_filename;
3049
3050
    /* Do we have a predefined filename? */
3051
0
    fo_filename = msGetOutputFormatOption(format, "FILENAME", NULL);
3052
0
    if (fo_filename)
3053
0
      msIO_setHeader("Content-Disposition", "attachment; filename=%s",
3054
0
                     fo_filename);
3055
3056
    /* Emit back to client. */
3057
0
    msOutputFormatResolveFromImage(map, image);
3058
0
    msIO_setHeader("Content-Type", "%s", MS_IMAGE_MIME_TYPE(map->outputformat));
3059
0
    msIO_sendHeaders();
3060
0
    status = msSaveImage(map, image, NULL);
3061
3062
0
    if (status != MS_SUCCESS) {
3063
      /* unfortunately, the image content type will have already been sent
3064
         but that is hard for us to avoid.  The main error that could happen
3065
         here is a misconfigured tmp directory or running out of space. */
3066
0
      msWCSFreeCoverageMetadata(&cm);
3067
0
      return msWCSException(map, NULL, NULL, params->version);
3068
0
    }
3069
0
  }
3070
3071
  /* Cleanup */
3072
0
  msFreeImage(image);
3073
0
  msApplyOutputFormat(&(map->outputformat), NULL, MS_NOOVERRIDE);
3074
  /* msFreeOutputFormat(format); */
3075
3076
0
  msWCSFreeCoverageMetadata(&cm);
3077
0
  return status;
3078
0
}
3079
#endif /* def USE_WCS_SVR */
3080
3081
/************************************************************************/
3082
/*                           msWCSDispatch()                            */
3083
/*                                                                      */
3084
/*      Entry point for WCS requests                                    */
3085
/************************************************************************/
3086
3087
int msWCSDispatch(mapObj *map, cgiRequestObj *request,
3088
0
                  owsRequestObj *ows_request) {
3089
0
#if defined(USE_WCS_SVR)
3090
0
  wcs20ParamsObj *params20 = NULL;
3091
0
  int status, retVal, operation;
3092
3093
  /* If SERVICE is not set or not WCS exit gracefully. */
3094
0
  if (ows_request->service == NULL || !EQUAL(ows_request->service, "WCS")) {
3095
0
    return MS_DONE;
3096
0
  }
3097
3098
  /* If no REQUEST is set, exit with an error */
3099
0
  if (ows_request->request == NULL) {
3100
    /* The request has to be set. */
3101
0
    msSetError(MS_WCSERR, "Missing REQUEST parameter", "msWCSDispatch()");
3102
0
    return msWCSException(map, "MissingParameterValue", "request",
3103
0
                          ows_request->version);
3104
0
  }
3105
3106
0
  if (EQUAL(ows_request->request, "GetCapabilities")) {
3107
0
    operation = MS_WCS_GET_CAPABILITIES;
3108
0
  } else if (EQUAL(ows_request->request, "DescribeCoverage")) {
3109
0
    operation = MS_WCS_DESCRIBE_COVERAGE;
3110
0
  } else if (EQUAL(ows_request->request, "GetCoverage")) {
3111
0
    operation = MS_WCS_GET_COVERAGE;
3112
0
  } else {
3113
0
    msSetError(MS_WCSERR, "Invalid REQUEST parameter \"%s\"", "msWCSDispatch()",
3114
0
               ows_request->request);
3115
0
    return msWCSException(map, "InvalidParameterValue", "request",
3116
0
                          ows_request->version);
3117
0
  }
3118
3119
  /* Check the number of enabled layers for the REQUEST */
3120
0
  msOWSRequestLayersEnabled(map, "C", ows_request->request, ows_request);
3121
0
  if (ows_request->numlayers == 0) {
3122
0
    int caps_globally_enabled = MS_FALSE, disabled = MS_FALSE;
3123
0
    const char *enable_request;
3124
0
    if (operation == MS_WCS_GET_CAPABILITIES) {
3125
0
      enable_request =
3126
0
          msOWSLookupMetadata(&map->web.metadata, "OC", "enable_request");
3127
0
      caps_globally_enabled = msOWSParseRequestMetadata(
3128
0
          enable_request, "GetCapabilities", &disabled);
3129
0
    }
3130
3131
0
    if (caps_globally_enabled == MS_FALSE) {
3132
0
      msSetError(MS_WCSERR,
3133
0
                 "WCS request not enabled. Check "
3134
0
                 "wcs/ows_enable_request settings.",
3135
0
                 "msWCSDispatch()");
3136
0
      return msWCSException(map, "InvalidParameterValue", "request",
3137
0
                            ows_request->version);
3138
0
    }
3139
0
  }
3140
3141
  /* Check the VERSION parameter */
3142
0
  if (ows_request->version == NULL) {
3143
    /* If the VERSION parameter is not set, it is either */
3144
    /* an error (Describe and GetCoverage), or it has to */
3145
    /* be determined (GetCapabilities). To determine the */
3146
    /* version, the request has to be fully parsed to    */
3147
    /* obtain the ACCEPTVERSIONS parameter. If this is   */
3148
    /* present also, set version to "2.0.1".             */
3149
3150
0
    if (operation == MS_WCS_GET_CAPABILITIES) {
3151
      /* Parse it as if it was a WCS 2.0 request */
3152
0
      wcs20ParamsObjPtr params_tmp = msWCSCreateParamsObj20();
3153
0
      status = msWCSParseRequest20(map, request, ows_request, params_tmp);
3154
0
      if (status == MS_FAILURE) {
3155
0
        msWCSFreeParamsObj20(params_tmp);
3156
0
        return msWCSException(map, "InvalidParameterValue", "request", "2.0.1");
3157
0
      }
3158
3159
      /* VERSION negotiation */
3160
0
      if (params_tmp->accept_versions != NULL) {
3161
        /* choose highest acceptable */
3162
0
        int i, highest_version = 0;
3163
0
        char version_string[OWS_VERSION_MAXLEN];
3164
0
        for (i = 0; params_tmp->accept_versions[i] != NULL; ++i) {
3165
0
          int version = msOWSParseVersionString(params_tmp->accept_versions[i]);
3166
0
          if (version == OWS_VERSION_BADFORMAT) {
3167
0
            msWCSFreeParamsObj20(params_tmp);
3168
0
            return msWCSException(map, "InvalidParameterValue", "version",
3169
0
                                  NULL);
3170
0
          }
3171
0
          if (version > highest_version) {
3172
0
            highest_version = version;
3173
0
          }
3174
0
        }
3175
0
        msOWSGetVersionString(highest_version, version_string);
3176
0
        params_tmp->version = msStrdup(version_string);
3177
0
        ows_request->version = msStrdup(version_string);
3178
0
      } else {
3179
        /* set to highest acceptable */
3180
0
        params_tmp->version = msStrdup("2.0.1");
3181
0
        ows_request->version = msStrdup("2.0.1");
3182
0
      }
3183
3184
      /* check if we can keep the params object */
3185
0
      if (EQUAL(params_tmp->version, "2.0.1")) {
3186
0
        params20 = params_tmp;
3187
0
      } else {
3188
0
        msWCSFreeParamsObj20(params_tmp);
3189
0
      }
3190
0
    } else { /* operation != GetCapabilities */
3191
      /* VERSION is mandatory in other requests */
3192
0
      msSetError(MS_WCSERR, "VERSION parameter not set.", "msWCSDispatch()");
3193
0
      return msWCSException(map, "InvalidParameterValue", "version", NULL);
3194
0
    }
3195
0
  } else {
3196
    /* Parse the VERSION parameter */
3197
0
    int requested_version = msOWSParseVersionString(ows_request->version);
3198
0
    if (requested_version == OWS_VERSION_BADFORMAT) {
3199
      /* Return an error if the VERSION is */
3200
      /* in an unsupported format.         */
3201
0
      return msWCSException(map, "InvalidParameterValue", "version", NULL);
3202
0
    }
3203
3204
0
    if (operation == MS_WCS_GET_CAPABILITIES) {
3205
      /* In case of GetCapabilities, make  */
3206
0
      char version_string[OWS_VERSION_MAXLEN];
3207
0
      int version, supported_versions[] = {OWS_2_0_1, OWS_2_0_0, OWS_1_1_2,
3208
0
                                           OWS_1_1_1, OWS_1_1_0, OWS_1_0_0};
3209
0
      version = msOWSNegotiateVersion(requested_version, supported_versions,
3210
0
                                      sizeof(supported_versions) / sizeof(int));
3211
0
      msOWSGetVersionString(version, version_string);
3212
0
      msFree(ows_request->version);
3213
0
      ows_request->version = msStrdup(version_string);
3214
0
    }
3215
0
  }
3216
3217
  /* VERSION specific request handler */
3218
0
  if (strcmp(ows_request->version, "1.0.0") == 0 ||
3219
0
      strcmp(ows_request->version, "1.1.0") == 0 ||
3220
0
      strcmp(ows_request->version, "1.1.1") == 0 ||
3221
0
      strcmp(ows_request->version, "1.1.2") == 0) {
3222
0
    auto paramsTmp = msWCSCreateParams();
3223
0
    status = msWCSParseRequest(request, paramsTmp, map);
3224
0
    if (status == MS_DONE) {
3225
0
      msWCSFreeParams(paramsTmp);
3226
0
      free(paramsTmp);
3227
0
      return MS_FAILURE;
3228
0
    }
3229
0
    if (status == MS_FAILURE) {
3230
0
      msWCSFreeParams(paramsTmp);
3231
0
      free(paramsTmp);
3232
0
      return msWCSException(map, "InvalidParameterValue", "request", "2.0");
3233
0
    }
3234
3235
0
    retVal = MS_FAILURE;
3236
0
    if (operation == MS_WCS_GET_CAPABILITIES) {
3237
0
      retVal = msWCSGetCapabilities(map, paramsTmp, request, ows_request);
3238
0
    } else if (operation == MS_WCS_DESCRIBE_COVERAGE) {
3239
0
      retVal = msWCSDescribeCoverage(map, paramsTmp, ows_request, request);
3240
0
    } else if (operation == MS_WCS_GET_COVERAGE) {
3241
0
      retVal = msWCSGetCoverage(map, request, paramsTmp, ows_request);
3242
0
    }
3243
0
    msWCSFreeParams(paramsTmp);
3244
0
    free(paramsTmp);
3245
0
    return retVal;
3246
0
  } else if (strcmp(ows_request->version, "2.0.0") == 0 ||
3247
0
             strcmp(ows_request->version, "2.0.1") == 0) {
3248
0
#if defined(USE_LIBXML2)
3249
0
    int i;
3250
3251
0
    if (params20 == NULL) {
3252
0
      params20 = msWCSCreateParamsObj20();
3253
0
      status = msWCSParseRequest20(map, request, ows_request, params20);
3254
0
      if (status == MS_FAILURE) {
3255
0
        msWCSFreeParamsObj20(params20);
3256
0
        return msWCSException(map, "InvalidParameterValue", "request", "2.0.1");
3257
0
      } else if (status == MS_DONE) {
3258
        /* MS_DONE means, that the exception has already been written to the IO
3259
          buffer.
3260
        */
3261
0
        msWCSFreeParamsObj20(params20);
3262
0
        return MS_FAILURE;
3263
0
      }
3264
0
    }
3265
3266
    /* check if all layer names are valid NCNames */
3267
0
    for (i = 0; i < map->numlayers; ++i) {
3268
0
      if (!msWCSIsLayerSupported(map->layers[i]))
3269
0
        continue;
3270
3271
      /* Check if each layers name is a valid NCName. */
3272
0
      if (msEvalRegex("^[a-zA-z_][a-zA-Z0-9_.-]*$", map->layers[i]->name) ==
3273
0
          MS_FALSE) {
3274
0
        msSetError(MS_WCSERR, "Layer name '%s' is not a valid NCName.",
3275
0
                   "msWCSDispatch()", map->layers[i]->name);
3276
0
        msWCSFreeParamsObj20(params20);
3277
0
        return msWCSException(map, "mapserv", "Internal", "2.0.1");
3278
0
      }
3279
0
    }
3280
3281
    /* Call operation specific functions */
3282
0
    if (operation == MS_WCS_GET_CAPABILITIES) {
3283
0
      retVal = msWCSGetCapabilities20(map, request, params20, ows_request);
3284
0
    } else if (operation == MS_WCS_DESCRIBE_COVERAGE) {
3285
0
      retVal = msWCSDescribeCoverage20(map, params20, ows_request);
3286
0
    } else if (operation == MS_WCS_GET_COVERAGE) {
3287
0
      retVal = msWCSGetCoverage20(map, request, params20, ows_request);
3288
0
    } else {
3289
0
      msSetError(MS_WCSERR, "Invalid request '%s'.", "msWCSDispatch20()",
3290
0
                 ows_request->request);
3291
0
      retVal =
3292
0
          msWCSException20(map, "InvalidParameterValue", "request", "2.0.1");
3293
0
    }
3294
    /* clean up */
3295
0
    msWCSFreeParamsObj20(params20);
3296
0
    return retVal;
3297
#else      /* def USE_LIBXML2 */
3298
    msSetError(MS_WCSERR,
3299
               "WCS 2.0 needs mapserver to be compiled with libxml2.",
3300
               "msWCSDispatch()");
3301
    return msWCSException(map, "mapserv", "NoApplicableCode", "2.0.1");
3302
#endif     /* def USE_LIBXML2 */
3303
0
  } else { /* unsupported version */
3304
0
    msSetError(MS_WCSERR, "WCS Server does not support VERSION %s.",
3305
0
               "msWCSDispatch()", ows_request->version);
3306
0
    return msWCSException(map, "InvalidParameterValue", "version",
3307
0
                          ows_request->version);
3308
0
  }
3309
3310
#else
3311
  msSetError(MS_WCSERR, "WCS server support is not available.",
3312
             "msWCSDispatch()");
3313
  return MS_FAILURE;
3314
#endif
3315
0
}
3316
3317
/************************************************************************/
3318
/*                      msWCSGetCoverageMetadata()                      */
3319
/************************************************************************/
3320
3321
#ifdef USE_WCS_SVR
3322
3323
0
void msWCSFreeCoverageMetadata(coverageMetadataObj *cm) {
3324
0
  msFree(cm->srs_epsg);
3325
0
}
3326
3327
0
int msWCSGetCoverageMetadata(layerObj *layer, coverageMetadataObj *cm) {
3328
0
  char *srs_urn = NULL;
3329
0
  int i = 0;
3330
0
  if (msCheckParentPointer(layer->map, "map") == MS_FAILURE)
3331
0
    return MS_FAILURE;
3332
3333
  /* -------------------------------------------------------------------- */
3334
  /*      Get the SRS in WCS 1.0 format (eg. EPSG:n)                      */
3335
  /* -------------------------------------------------------------------- */
3336
0
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "CO", MS_TRUE,
3337
0
                   &(cm->srs_epsg));
3338
0
  if (!cm->srs_epsg) {
3339
0
    msOWSGetEPSGProj(&(layer->map->projection), &(layer->map->web.metadata),
3340
0
                     "CO", MS_TRUE, &(cm->srs_epsg));
3341
0
    if (!cm->srs_epsg) {
3342
0
      msSetError(MS_WCSERR,
3343
0
                 "Unable to determine the SRS for this layer, no projection "
3344
0
                 "defined and no metadata available.",
3345
0
                 "msWCSGetCoverageMetadata()");
3346
0
      return MS_FAILURE;
3347
0
    }
3348
0
  }
3349
3350
  /* -------------------------------------------------------------------- */
3351
  /*      Get the SRS in urn format.                                      */
3352
  /* -------------------------------------------------------------------- */
3353
0
  if ((srs_urn = msOWSGetProjURN(&(layer->projection), &(layer->metadata), "CO",
3354
0
                                 MS_TRUE)) == NULL) {
3355
0
    srs_urn = msOWSGetProjURN(&(layer->map->projection),
3356
0
                              &(layer->map->web.metadata), "CO", MS_TRUE);
3357
0
  }
3358
3359
0
  if (srs_urn != NULL) {
3360
0
    if (strlen(srs_urn) > sizeof(cm->srs_urn) - 1) {
3361
0
      msSetError(MS_WCSERR, "SRS URN too long!", "msWCSGetCoverageMetadata()");
3362
0
      return MS_FAILURE;
3363
0
    }
3364
3365
0
    strcpy(cm->srs_urn, srs_urn);
3366
0
    msFree(srs_urn);
3367
0
  } else
3368
0
    cm->srs_urn[0] = '\0';
3369
3370
  /* -------------------------------------------------------------------- */
3371
  /*      If we have "virtual dataset" metadata on the layer, then use    */
3372
  /*      that in preference to inspecting the file(s).                   */
3373
  /*      We require extent and either size or resolution.                */
3374
  /* -------------------------------------------------------------------- */
3375
0
  if (msOWSLookupMetadata(&(layer->metadata), "CO", "extent") != NULL &&
3376
0
      (msOWSLookupMetadata(&(layer->metadata), "CO", "resolution") != NULL ||
3377
0
       msOWSLookupMetadata(&(layer->metadata), "CO", "size") != NULL)) {
3378
0
    const char *value;
3379
3380
    /* get extent */
3381
0
    cm->extent.minx = 0.0;
3382
0
    cm->extent.maxx = 0.0;
3383
0
    cm->extent.miny = 0.0;
3384
0
    cm->extent.maxy = 0.0;
3385
0
    if (msOWSGetLayerExtent(layer->map, layer, "CO", &cm->extent) == MS_FAILURE)
3386
0
      return MS_FAILURE;
3387
3388
    /* get resolution */
3389
0
    cm->xresolution = 0.0;
3390
0
    cm->yresolution = 0.0;
3391
0
    if ((value = msOWSLookupMetadata(&(layer->metadata), "CO", "resolution")) !=
3392
0
        NULL) {
3393
0
      char **tokens;
3394
0
      int n;
3395
3396
0
      tokens = msStringSplit(value, ' ', &n);
3397
0
      if (tokens == NULL || n != 2) {
3398
0
        msSetError(MS_WCSERR,
3399
0
                   "Wrong number of arguments for wcs|ows_resolution metadata.",
3400
0
                   "msWCSGetCoverageMetadata()");
3401
0
        msFreeCharArray(tokens, n);
3402
0
        return MS_FAILURE;
3403
0
      }
3404
0
      cm->xresolution = atof(tokens[0]);
3405
0
      cm->yresolution = atof(tokens[1]);
3406
0
      msFreeCharArray(tokens, n);
3407
0
    }
3408
3409
    /* get Size (in pixels and lines) */
3410
0
    cm->xsize = 0;
3411
0
    cm->ysize = 0;
3412
0
    if ((value = msOWSLookupMetadata(&(layer->metadata), "CO", "size")) !=
3413
0
        NULL) {
3414
0
      char **tokens;
3415
0
      int n;
3416
3417
0
      tokens = msStringSplit(value, ' ', &n);
3418
0
      if (tokens == NULL || n != 2) {
3419
0
        msSetError(MS_WCSERR,
3420
0
                   "Wrong number of arguments for wcs|ows_size metadata.",
3421
0
                   "msWCSGetCoverageDomain()");
3422
0
        msFreeCharArray(tokens, n);
3423
0
        return MS_FAILURE;
3424
0
      }
3425
0
      cm->xsize = atoi(tokens[0]);
3426
0
      cm->ysize = atoi(tokens[1]);
3427
0
      msFreeCharArray(tokens, n);
3428
0
    }
3429
3430
    /* try to compute raster size */
3431
0
    if (cm->xsize == 0 && cm->ysize == 0 && cm->xresolution != 0.0 &&
3432
0
        cm->yresolution != 0.0 && cm->extent.minx != cm->extent.maxx &&
3433
0
        cm->extent.miny != cm->extent.maxy) {
3434
0
      cm->xsize =
3435
0
          (int)((cm->extent.maxx - cm->extent.minx) / cm->xresolution + 0.5);
3436
0
      cm->ysize = (int)fabs(
3437
0
          (cm->extent.maxy - cm->extent.miny) / cm->yresolution + 0.5);
3438
0
    }
3439
3440
    /* try to compute raster resolution */
3441
0
    if ((cm->xresolution == 0.0 || cm->yresolution == 0.0) && cm->xsize != 0 &&
3442
0
        cm->ysize != 0) {
3443
0
      cm->xresolution = (cm->extent.maxx - cm->extent.minx) / cm->xsize;
3444
0
      cm->yresolution = (cm->extent.maxy - cm->extent.miny) / cm->ysize;
3445
0
    }
3446
3447
    /* do we have information to do anything */
3448
0
    if (cm->xresolution == 0.0 || cm->yresolution == 0.0 || cm->xsize == 0 ||
3449
0
        cm->ysize == 0) {
3450
0
      msSetError(MS_WCSERR,
3451
0
                 "Failed to collect extent and resolution for WCS coverage "
3452
0
                 "from metadata for layer '%s'.  Need value wcs|ows_resolution "
3453
0
                 "or wcs|ows_size values.",
3454
0
                 "msWCSGetCoverageMetadata()", layer->name);
3455
0
      return MS_FAILURE;
3456
0
    }
3457
3458
    /* compute geotransform */
3459
0
    cm->geotransform[0] = cm->extent.minx;
3460
0
    cm->geotransform[1] = cm->xresolution;
3461
0
    cm->geotransform[2] = 0.0;
3462
0
    cm->geotransform[3] = cm->extent.maxy;
3463
0
    cm->geotransform[4] = 0.0;
3464
0
    cm->geotransform[5] = -fabs(cm->yresolution);
3465
3466
    /* get bands count, or assume 1 if not found */
3467
0
    cm->bandcount = 1;
3468
0
    if ((value = msOWSLookupMetadata(&(layer->metadata), "CO", "bandcount")) !=
3469
0
        NULL) {
3470
0
      cm->bandcount = atoi(value);
3471
0
    }
3472
3473
    /* get bands type, or assume float if not found */
3474
0
    cm->imagemode = MS_IMAGEMODE_FLOAT32;
3475
0
    if ((value = msOWSLookupMetadata(&(layer->metadata), "CO", "imagemode")) !=
3476
0
        NULL) {
3477
0
      if (EQUAL(value, "INT16"))
3478
0
        cm->imagemode = MS_IMAGEMODE_INT16;
3479
0
      else if (EQUAL(value, "FLOAT32"))
3480
0
        cm->imagemode = MS_IMAGEMODE_FLOAT32;
3481
0
      else if (EQUAL(value, "BYTE"))
3482
0
        cm->imagemode = MS_IMAGEMODE_BYTE;
3483
0
      else {
3484
0
        msSetError(MS_WCSERR,
3485
0
                   "Content of wcs|ows_imagemode (%s) not recognised.  Should "
3486
0
                   "be one of BYTE, INT16 or FLOAT32.",
3487
0
                   "msWCSGetCoverageMetadata()", value);
3488
0
        return MS_FAILURE;
3489
0
      }
3490
0
    }
3491
    /* set color interpretation to undefined */
3492
    /* TODO: find better solution */
3493
0
    for (i = 0; i < 10; ++i) {
3494
0
      cm->bandinterpretation[i] = GDALGetColorInterpretationName(GCI_Undefined);
3495
0
    }
3496
0
  } else if (layer->data ==
3497
0
             NULL) { /* no virtual metadata, not ok unless we're talking 1
3498
                        image, hopefully we can fix that */
3499
0
    msSetError(
3500
0
        MS_WCSERR,
3501
0
        "RASTER Layer with no DATA statement and no WCS virtual dataset "
3502
0
        "metadata.  Tileindexed raster layers not supported for WCS without "
3503
0
        "virtual dataset metadata (cm->extent, wcs_res, wcs_size).",
3504
0
        "msWCSGetCoverageDomain()");
3505
0
    return MS_FAILURE;
3506
0
  } else { /* work from the file (e.g. DATA) */
3507
0
    GDALDatasetH hDS;
3508
0
    GDALRasterBandH hBand;
3509
0
    char szPath[MS_MAXPATHLEN];
3510
0
    char *decrypted_path;
3511
3512
0
    msGDALInitialize();
3513
3514
0
    msTryBuildPath3(szPath, layer->map->mappath, layer->map->shapepath,
3515
0
                    layer->data);
3516
0
    decrypted_path = msDecryptStringTokens(layer->map, szPath);
3517
0
    if (!decrypted_path)
3518
0
      return MS_FAILURE;
3519
3520
0
    msAcquireLock(TLOCK_GDAL);
3521
0
    {
3522
0
      char **connectionoptions =
3523
0
          msGetStringListFromHashTable(&(layer->connectionoptions));
3524
0
      hDS = GDALOpenEx(decrypted_path, GDAL_OF_RASTER, NULL,
3525
0
                       (const char *const *)connectionoptions, NULL);
3526
0
      CSLDestroy(connectionoptions);
3527
0
    }
3528
0
    if (hDS == NULL) {
3529
0
      const char *cpl_error_msg = CPLGetLastErrorMsg();
3530
3531
      /* we wish to avoid reporting decrypted paths */
3532
0
      if (cpl_error_msg != NULL &&
3533
0
          strstr(cpl_error_msg, decrypted_path) != NULL &&
3534
0
          strcmp(decrypted_path, szPath) != 0)
3535
0
        cpl_error_msg = NULL;
3536
3537
0
      if (cpl_error_msg == NULL)
3538
0
        cpl_error_msg = "";
3539
3540
0
      msReleaseLock(TLOCK_GDAL);
3541
3542
0
      msSetError(MS_IOERR, "%s", "msWCSGetCoverageMetadata()", cpl_error_msg);
3543
3544
0
      msFree(decrypted_path);
3545
0
      return MS_FAILURE;
3546
0
    }
3547
0
    msFree(decrypted_path);
3548
3549
0
    msGetGDALGeoTransform(hDS, layer->map, layer, cm->geotransform);
3550
3551
0
    cm->xsize = GDALGetRasterXSize(hDS);
3552
0
    cm->ysize = GDALGetRasterYSize(hDS);
3553
3554
0
    cm->extent.minx = cm->geotransform[0];
3555
0
    cm->extent.maxx = cm->geotransform[0] + cm->geotransform[1] * cm->xsize +
3556
0
                      cm->geotransform[2] * cm->ysize;
3557
0
    cm->extent.miny = cm->geotransform[3] + cm->geotransform[4] * cm->xsize +
3558
0
                      cm->geotransform[5] * cm->ysize;
3559
0
    cm->extent.maxy = cm->geotransform[3];
3560
3561
0
    cm->xresolution = cm->geotransform[1];
3562
0
    cm->yresolution = cm->geotransform[5];
3563
3564
    /* TODO: need to set resolution */
3565
3566
0
    cm->bandcount = GDALGetRasterCount(hDS);
3567
3568
0
    if (cm->bandcount == 0) {
3569
0
      msReleaseLock(TLOCK_GDAL);
3570
0
      msSetError(MS_WCSERR,
3571
0
                 "Raster file %s has no raster bands.  This cannot be used in "
3572
0
                 "a layer.",
3573
0
                 "msWCSGetCoverageMetadata()", layer->data);
3574
0
      return MS_FAILURE;
3575
0
    }
3576
3577
0
    hBand = GDALGetRasterBand(hDS, 1);
3578
0
    switch (GDALGetRasterDataType(hBand)) {
3579
0
    case GDT_Byte:
3580
0
      cm->imagemode = MS_IMAGEMODE_BYTE;
3581
0
      break;
3582
0
    case GDT_Int16:
3583
0
      cm->imagemode = MS_IMAGEMODE_INT16;
3584
0
      break;
3585
0
    default:
3586
0
      cm->imagemode = MS_IMAGEMODE_FLOAT32;
3587
0
      break;
3588
0
    }
3589
3590
    /* color interpretation */
3591
0
    for (i = 1; i <= 10 && i <= cm->bandcount; ++i) {
3592
0
      GDALColorInterp colorInterp;
3593
0
      hBand = GDALGetRasterBand(hDS, i);
3594
0
      colorInterp = GDALGetRasterColorInterpretation(hBand);
3595
0
      cm->bandinterpretation[i - 1] =
3596
0
          GDALGetColorInterpretationName(colorInterp);
3597
0
    }
3598
3599
0
    GDALClose(hDS);
3600
0
    msReleaseLock(TLOCK_GDAL);
3601
0
  }
3602
3603
  /* we must have the bounding box in lat/lon [WGS84(DD)/EPSG:4326] */
3604
0
  cm->llextent = cm->extent;
3605
3606
  /* Already in latlong .. use directly. */
3607
0
  if (layer->projection.proj != NULL &&
3608
0
      msProjIsGeographicCRS(&(layer->projection))) {
3609
    /* no change */
3610
0
  }
3611
3612
0
  else if (layer->projection.numargs > 0 &&
3613
0
           !msProjIsGeographicCRS(
3614
0
               &(layer->projection))) /* check the layer projection */
3615
0
    msProjectRect(&(layer->projection), NULL, &(cm->llextent));
3616
3617
0
  else if (layer->map->projection.numargs > 0 &&
3618
0
           !msProjIsGeographicCRS(
3619
0
               &(layer->map->projection))) /* check the map projection */
3620
0
    msProjectRect(&(layer->map->projection), NULL, &(cm->llextent));
3621
3622
0
  else { /* projection was specified in the metadata only (EPSG:... only at the
3623
            moment)  */
3624
0
    projectionObj proj;
3625
0
    char projstring[32];
3626
3627
0
    msInitProjection(&proj); /* or bad things happen */
3628
0
    msProjectionInheritContextFrom(&proj, &(layer->map->projection));
3629
3630
0
    snprintf(projstring, sizeof(projstring), "init=epsg:%.20s",
3631
0
             cm->srs_epsg + 5);
3632
0
    if (msLoadProjectionString(&proj, projstring) != 0) {
3633
0
      msFreeProjection(&proj);
3634
0
      return MS_FAILURE;
3635
0
    }
3636
0
    msProjectRect(&proj, NULL, &(cm->llextent));
3637
0
  }
3638
3639
0
  return MS_SUCCESS;
3640
0
}
3641
#endif /* def USE_WCS_SVR */