• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

geographika / mapserver / 17823520225

18 Sep 2025 08:57AM UTC coverage: 41.442% (-0.02%) from 41.466%
17823520225

push

github

geographika
Use full path for CONFIG test

62112 of 149877 relevant lines covered (41.44%)

25354.57 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

77.39
/src/mapogcapi.cpp
1
/**********************************************************************
2
 * $id$
3
 *
4
 * Project:  MapServer
5
 * Purpose:  OGCAPI 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 OR
22
 * 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
 ****************************************************************************/
28
#include "mapserver.h"
29
#include "mapogcapi.h"
30
#include "mapows.h"
31
#include "mapgml.h"
32
#include "maptime.h"
33
#include "mapogcfilter.h"
34

35
#include "cpl_conv.h"
36

37
#include "third-party/include_nlohmann_json.hpp"
38
#include "third-party/include_pantor_inja.hpp"
39

40
#include <algorithm>
41
#include <map>
42
#include <string>
43
#include <iostream>
44
#include <utility>
45

46
using namespace inja;
47
using json = nlohmann::json;
48

49
#define OGCAPI_DEFAULT_TITLE "MapServer OGC API"
50

51
/*
52
** HTML Templates
53
*/
54
#define OGCAPI_TEMPLATE_HTML_LANDING "landing.html"
55
#define OGCAPI_TEMPLATE_HTML_CONFORMANCE "conformance.html"
56
#define OGCAPI_TEMPLATE_HTML_COLLECTION "collection.html"
57
#define OGCAPI_TEMPLATE_HTML_COLLECTIONS "collections.html"
58
#define OGCAPI_TEMPLATE_HTML_COLLECTION_ITEMS "collection-items.html"
59
#define OGCAPI_TEMPLATE_HTML_COLLECTION_ITEM "collection-item.html"
60
#define OGCAPI_TEMPLATE_HTML_OPENAPI "openapi.html"
61

62
#define OGCAPI_DEFAULT_LIMIT 10 // by specification
63
#define OGCAPI_MAX_LIMIT 10000
64

65
#define OGCAPI_DEFAULT_GEOMETRY_PRECISION 6
66

67
constexpr const char *EPSG_PREFIX_URL =
68
    "http://www.opengis.net/def/crs/EPSG/0/";
69
constexpr const char *CRS84_URL =
70
    "http://www.opengis.net/def/crs/OGC/1.3/CRS84";
71

72
#ifdef USE_OGCAPI_SVR
73

74
/*
75
** Returns a JSON object using and a description.
76
*/
77
void outputError(OGCAPIErrorType errorType, const std::string &description) {
9✔
78
  const char *code = "";
9✔
79
  const char *status = "";
80
  switch (errorType) {
9✔
81
  case OGCAPI_SERVER_ERROR: {
×
82
    code = "ServerError";
×
83
    status = "500";
84
    break;
×
85
  }
86
  case OGCAPI_CONFIG_ERROR: {
2✔
87
    code = "ConfigError";
2✔
88
    status = "500";
89
    break;
2✔
90
  }
91
  case OGCAPI_PARAM_ERROR: {
6✔
92
    code = "InvalidParameterValue";
6✔
93
    status = "400";
94
    break;
6✔
95
  }
96
  case OGCAPI_NOT_FOUND_ERROR: {
1✔
97
    code = "NotFound";
1✔
98
    status = "404";
99
    break;
1✔
100
  }
101
  }
102

103
  json j = {{"code", code}, {"description", description}};
63✔
104

105
  msIO_setHeader("Content-Type", "%s", OGCAPI_MIMETYPE_JSON);
9✔
106
  msIO_setHeader("Status", "%s", status);
9✔
107
  msIO_sendHeaders();
9✔
108
  msIO_printf("%s\n", j.dump().c_str());
18✔
109
}
72✔
110

111
static int includeLayer(mapObj *map, layerObj *layer) {
30✔
112
  if (!msOWSRequestIsEnabled(map, layer, "AO", "OGCAPI", MS_FALSE) ||
60✔
113
      !msIsLayerSupportedForWFSOrOAPIF(layer) || !msIsLayerQueryable(layer)) {
60✔
114
    return MS_FALSE;
×
115
  } else {
116
    return MS_TRUE;
117
  }
118
}
119

120
/*
121
** Get stuff...
122
*/
123

124
/*
125
** Returns the value associated with an item from the request's query string and
126
*NULL if the item was not found.
127
*/
128
static const char *getRequestParameter(cgiRequestObj *request,
141✔
129
                                       const char *item) {
130
  int i;
131

132
  for (i = 0; i < request->NumParams; i++) {
324✔
133
    if (strcmp(item, request->ParamNames[i]) == 0)
241✔
134
      return request->ParamValues[i];
58✔
135
  }
136

137
  return NULL;
138
}
139

140
static int getMaxLimit(mapObj *map, layerObj *layer) {
22✔
141
  int max_limit = OGCAPI_MAX_LIMIT;
22✔
142
  const char *value;
143

144
  // check metadata, layer then map
145
  value = msOWSLookupMetadata(&(layer->metadata), "A", "max_limit");
22✔
146
  if (value == NULL)
22✔
147
    value = msOWSLookupMetadata(&(map->web.metadata), "A", "max_limit");
22✔
148

149
  if (value != NULL) {
22✔
150
    int status = msStringToInt(value, &max_limit, 10);
16✔
151
    if (status != MS_SUCCESS)
16✔
152
      max_limit = OGCAPI_MAX_LIMIT; // conversion failed
×
153
  }
154

155
  return max_limit;
22✔
156
}
157

158
static int getDefaultLimit(mapObj *map, layerObj *layer) {
27✔
159
  int default_limit = OGCAPI_DEFAULT_LIMIT;
27✔
160

161
  // check metadata, layer then map
162
  const char *value =
163
      msOWSLookupMetadata(&(layer->metadata), "A", "default_limit");
27✔
164
  if (value == NULL)
27✔
165
    value = msOWSLookupMetadata(&(map->web.metadata), "A", "default_limit");
27✔
166

167
  if (value != NULL) {
27✔
168
    int status = msStringToInt(value, &default_limit, 10);
15✔
169
    if (status != MS_SUCCESS)
15✔
170
      default_limit = OGCAPI_DEFAULT_LIMIT; // conversion failed
×
171
  }
172

173
  return default_limit;
27✔
174
}
175

176
/*
177
** Returns the limit as an int - between 1 and getMaxLimit(). We always return a
178
*valid value...
179
*/
180
static int getLimit(mapObj *map, cgiRequestObj *request, layerObj *layer,
22✔
181
                    int *limit) {
182
  int status;
183
  const char *p;
184

185
  int max_limit;
186
  max_limit = getMaxLimit(map, layer);
22✔
187

188
  p = getRequestParameter(request, "limit");
22✔
189
  if (!p || (p && strlen(p) == 0)) { // missing or empty
22✔
190
    *limit = MS_MIN(getDefaultLimit(map, layer),
12✔
191
                    max_limit); // max could be smaller than the default
192
  } else {
193
    status = msStringToInt(p, limit, 10);
10✔
194
    if (status != MS_SUCCESS)
10✔
195
      return MS_FAILURE;
196

197
    if (*limit <= 0) {
10✔
198
      *limit = MS_MIN(getDefaultLimit(map, layer),
×
199
                      max_limit); // max could be smaller than the default
200
    } else {
201
      *limit = MS_MIN(*limit, max_limit);
10✔
202
    }
203
  }
204

205
  return MS_SUCCESS;
206
}
207

208
// Return the content of the "crs" member of the /collections/{name} response
209
static json getCrsList(mapObj *map, layerObj *layer) {
13✔
210
  char *pszSRSList = NULL;
13✔
211
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "AOF", MS_FALSE,
13✔
212
                   &pszSRSList);
213
  if (!pszSRSList)
13✔
214
    msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "AOF", MS_FALSE,
×
215
                     &pszSRSList);
216
  json jCrsList;
217
  if (pszSRSList) {
13✔
218
    const auto tokens = msStringSplit(pszSRSList, ' ');
13✔
219
    for (const auto &crs : tokens) {
37✔
220
      if (crs.find("EPSG:") == 0) {
24✔
221
        if (jCrsList.empty()) {
11✔
222
          jCrsList.push_back(CRS84_URL);
26✔
223
        }
224
        const std::string url =
225
            std::string(EPSG_PREFIX_URL) + crs.substr(strlen("EPSG:"));
48✔
226
        jCrsList.push_back(url);
48✔
227
      }
228
    }
229
    msFree(pszSRSList);
13✔
230
  }
231
  return jCrsList;
13✔
232
}
233

234
// Return the content of the "storageCrs" member of the /collections/{name}
235
// response
236
static std::string getStorageCrs(layerObj *layer) {
5✔
237
  std::string storageCrs;
238
  char *pszFirstSRS = nullptr;
5✔
239
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "AOF", MS_TRUE,
5✔
240
                   &pszFirstSRS);
241
  if (pszFirstSRS) {
5✔
242
    if (std::string(pszFirstSRS).find("EPSG:") == 0) {
10✔
243
      storageCrs =
244
          std::string(EPSG_PREFIX_URL) + (pszFirstSRS + strlen("EPSG:"));
15✔
245
    }
246
    msFree(pszFirstSRS);
5✔
247
  }
248
  return storageCrs;
5✔
249
}
250

251
/*
252
** Returns the bbox in output CRS (CRS84 by default, or "crs" request parameter
253
*when specified)
254
*/
255
static bool getBbox(mapObj *map, layerObj *layer, cgiRequestObj *request,
20✔
256
                    rectObj *bbox, projectionObj *outputProj) {
257
  int status;
258

259
  const char *bboxParam = getRequestParameter(request, "bbox");
20✔
260
  if (!bboxParam || strlen(bboxParam) == 0) { // missing or empty extent
20✔
261
    rectObj rect;
262
    if (FLTLayerSetInvalidRectIfSupported(layer, &rect, "AO")) {
15✔
263
      bbox->minx = rect.minx;
×
264
      bbox->miny = rect.miny;
×
265
      bbox->maxx = rect.maxx;
×
266
      bbox->maxy = rect.maxy;
×
267
    } else {
268
      // assign map->extent (no projection necessary)
269
      bbox->minx = map->extent.minx;
15✔
270
      bbox->miny = map->extent.miny;
15✔
271
      bbox->maxx = map->extent.maxx;
15✔
272
      bbox->maxy = map->extent.maxy;
15✔
273
    }
274
  } else {
15✔
275
    const auto tokens = msStringSplit(bboxParam, ',');
5✔
276
    if (tokens.size() != 4) {
5✔
277
      outputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
278
      return false;
×
279
    }
280

281
    double values[4];
282
    for (int i = 0; i < 4; i++) {
25✔
283
      status = msStringToDouble(tokens[i].c_str(), &values[i]);
20✔
284
      if (status != MS_SUCCESS) {
20✔
285
        outputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
286
        return false;
×
287
      }
288
    }
289

290
    bbox->minx = values[0]; // assign
5✔
291
    bbox->miny = values[1];
5✔
292
    bbox->maxx = values[2];
5✔
293
    bbox->maxy = values[3];
5✔
294

295
    // validate bbox is well-formed (degenerate is ok)
296
    if (MS_VALID_SEARCH_EXTENT(*bbox) != MS_TRUE) {
5✔
297
      outputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
298
      return false;
×
299
    }
300

301
    std::string bboxCrs = "EPSG:4326";
5✔
302
    bool axisInverted =
303
        false; // because above EPSG:4326 is meant to be OGC:CRS84 actually
304
    const char *bboxCrsParam = getRequestParameter(request, "bbox-crs");
5✔
305
    if (bboxCrsParam) {
5✔
306
      bool isExpectedCrs = false;
307
      for (const auto &crsItem : getCrsList(map, layer)) {
26✔
308
        if (bboxCrsParam == crsItem.get<std::string>()) {
22✔
309
          isExpectedCrs = true;
310
          break;
311
        }
312
      }
313
      if (!isExpectedCrs) {
4✔
314
        outputError(OGCAPI_PARAM_ERROR, "Bad value for bbox-crs.");
2✔
315
        return false;
2✔
316
      }
317
      if (std::string(bboxCrsParam) != CRS84_URL) {
4✔
318
        if (std::string(bboxCrsParam).find(EPSG_PREFIX_URL) == 0) {
4✔
319
          const char *code = bboxCrsParam + strlen(EPSG_PREFIX_URL);
2✔
320
          bboxCrs = std::string("EPSG:") + code;
6✔
321
          axisInverted = msIsAxisInverted(atoi(code));
2✔
322
        }
323
      }
324
    }
325
    if (axisInverted) {
2✔
326
      std::swap(bbox->minx, bbox->miny);
327
      std::swap(bbox->maxx, bbox->maxy);
328
    }
329

330
    projectionObj bboxProj;
331
    msInitProjection(&bboxProj);
3✔
332
    msProjectionInheritContextFrom(&bboxProj, &(map->projection));
3✔
333
    if (msLoadProjectionString(&bboxProj, bboxCrs.c_str()) != 0) {
3✔
334
      msFreeProjection(&bboxProj);
×
335
      outputError(OGCAPI_SERVER_ERROR, "Cannot process bbox-crs.");
×
336
      return false;
×
337
    }
338

339
    status = msProjectRect(&bboxProj, outputProj, bbox);
3✔
340
    msFreeProjection(&bboxProj);
3✔
341
    if (status != MS_SUCCESS) {
3✔
342
      outputError(OGCAPI_SERVER_ERROR,
×
343
                  "Cannot reproject bbox from bbox-crs to output CRS.");
344
      return false;
×
345
    }
346
  }
347

348
  return true;
349
}
350

351
/*
352
** Returns the template directory location or NULL if it isn't set.
353
*/
354
std::string getTemplateDirectory(mapObj *map, const char *key,
5✔
355
                                 const char *envvar) {
356
  const char *directory = NULL;
357

358
  if (map != NULL) {
5✔
359
    directory = msOWSLookupMetadata(&(map->web.metadata), "A", key);
5✔
360
  }
361

362
  if (directory == NULL) {
5✔
363
    directory = CPLGetConfigOption(envvar, NULL);
×
364
  }
365

366
  std::string s;
367
  if (directory != NULL) {
5✔
368
    s = directory;
369
    if (!s.empty() && (s.back() != '/' && s.back() != '\\')) {
5✔
370
      // add a trailing slash if missing
371
      std::string slash = "/";
3✔
372
#ifdef _WIN32
373
      slash = "\\";
374
#endif
375
      s += slash;
376
    }
377
  }
378

379
  return s;
5✔
380
}
381

382
/*
383
** Returns the service title from oga_{key} and/or ows_{key} or a default value
384
*if not set.
385
*/
386
static const char *getWebMetadata(mapObj *map, const char *domain,
387
                                  const char *key, const char *defaultVal) {
388
  const char *value;
389

390
  if ((value = msOWSLookupMetadata(&(map->web.metadata), domain, key)) != NULL)
11✔
391
    return value;
392
  else
393
    return defaultVal;
1✔
394
}
395

396
/*
397
** Returns the service title from oga|ows_title or a default value if not set.
398
*/
399
static const char *getTitle(mapObj *map) {
400
  return getWebMetadata(map, "OA", "title", OGCAPI_DEFAULT_TITLE);
401
}
402

403
/*
404
** Returns the API root URL from oga_onlineresource or builds a value if not
405
*set.
406
*/
407
std::string getApiRootUrl(mapObj *map, cgiRequestObj *request,
34✔
408
                          const char *namespaces = "A") {
409
  const char *root;
410
  if ((root = msOWSLookupMetadata(&(map->web.metadata), namespaces,
34✔
411
                                  "onlineresource")) != NULL) {
412
    return std::string(root);
34✔
413
  }
414

415
  std::string api_root;
416
  if (char *res = msBuildOnlineResource(NULL, request)) {
×
417
    api_root = res;
418
    free(res);
×
419

420
    // find last ogcapi in the string and strip the rest to get the root API
421
    std::size_t pos = api_root.rfind("ogcapi");
422
    if (pos != std::string::npos) {
×
423
      api_root = api_root.substr(0, pos + std::string("ogcapi").size());
×
424
    }
425
  }
426

427
  return api_root;
×
428
}
429

430
static json getFeatureConstant(const gmlConstantObj *constant) {
×
431
  json j; // empty (null)
432

433
  if (!constant)
×
434
    throw std::runtime_error("Null constant metadata.");
×
435
  if (!constant->value)
×
436
    return j;
437

438
  // initialize
439
  j = {{constant->name, constant->value}};
×
440

441
  return j;
×
442
}
×
443

444
static json getFeatureItem(const gmlItemObj *item, const char *value) {
170✔
445
  json j; // empty (null)
446
  const char *key;
447

448
  if (!item)
170✔
449
    throw std::runtime_error("Null item metadata.");
×
450
  if (!item->visible)
170✔
451
    return j;
452

453
  if (item->alias)
108✔
454
    key = item->alias;
68✔
455
  else
456
    key = item->name;
40✔
457

458
  // initialize
459
  j = {{key, value}};
432✔
460

461
  if (item->type &&
172✔
462
      (EQUAL(item->type, "Date") || EQUAL(item->type, "DateTime") ||
64✔
463
       EQUAL(item->type, "Time"))) {
48✔
464
    struct tm tm;
465
    if (msParseTime(value, &tm) == MS_TRUE) {
16✔
466
      char tmpValue[64];
467
      if (EQUAL(item->type, "Date"))
16✔
468
        snprintf(tmpValue, sizeof(tmpValue), "%04d-%02d-%02d",
×
469
                 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
×
470
      else if (EQUAL(item->type, "Time"))
16✔
471
        snprintf(tmpValue, sizeof(tmpValue), "%02d:%02d:%02dZ", tm.tm_hour,
×
472
                 tm.tm_min, tm.tm_sec);
473
      else
474
        snprintf(tmpValue, sizeof(tmpValue), "%04d-%02d-%02dT%02d:%02d:%02dZ",
16✔
475
                 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
16✔
476
                 tm.tm_min, tm.tm_sec);
477

478
      j = {{key, tmpValue}};
64✔
479
    }
480
  } else if (item->type &&
108✔
481
             (EQUAL(item->type, "Integer") || EQUAL(item->type, "Long"))) {
48✔
482
    try {
483
      j = {{key, std::stoll(value)}};
80✔
484
    } catch (const std::exception &) {
×
485
    }
×
486
  } else if (item->type && EQUAL(item->type, "Real")) {
76✔
487
    try {
488
      j = {{key, std::stod(value)}};
160✔
489
    } catch (const std::exception &) {
×
490
    }
×
491
  } else if (item->type && EQUAL(item->type, "Boolean")) {
44✔
492
    if (EQUAL(value, "0") || EQUAL(value, "false")) {
×
493
      j = {{key, false}};
×
494
    } else {
495
      j = {{key, true}};
×
496
    }
497
  }
498

499
  return j;
500
}
736✔
501

502
static double round_down(double value, int decimal_places) {
10✔
503
  const double multiplier = std::pow(10.0, decimal_places);
504
  return std::floor(value * multiplier) / multiplier;
10✔
505
}
506
// https://stackoverflow.com/questions/25925290/c-round-a-double-up-to-2-decimal-places
507
static double round_up(double value, int decimal_places) {
30,614✔
508
  const double multiplier = std::pow(10.0, decimal_places);
509
  return std::ceil(value * multiplier) / multiplier;
30,614✔
510
}
511

512
static json getFeatureGeometry(shapeObj *shape, int precision,
23✔
513
                               bool outputCrsAxisInverted) {
514
  json geometry; // empty (null)
515
  int *outerList = NULL, numOuterRings = 0;
516

517
  if (!shape)
23✔
518
    throw std::runtime_error("Null shape.");
×
519

520
  switch (shape->type) {
23✔
521
  case (MS_SHAPE_POINT):
1✔
522
    if (shape->numlines == 0 ||
1✔
523
        shape->line[0].numpoints == 0) // not enough info for a point
1✔
524
      return geometry;
525

526
    if (shape->line[0].numpoints == 1) {
1✔
527
      geometry["type"] = "Point";
1✔
528
      double x = shape->line[0].point[0].x;
1✔
529
      double y = shape->line[0].point[0].y;
1✔
530
      if (outputCrsAxisInverted)
1✔
531
        std::swap(x, y);
532
      geometry["coordinates"] = {round_up(x, precision),
2✔
533
                                 round_up(y, precision)};
5✔
534
    } else {
535
      geometry["type"] = "MultiPoint";
×
536
      geometry["coordinates"] = json::array();
×
537
      for (int j = 0; j < shape->line[0].numpoints; j++) {
×
538
        double x = shape->line[0].point[j].x;
×
539
        double y = shape->line[0].point[j].y;
×
540
        if (outputCrsAxisInverted)
×
541
          std::swap(x, y);
542
        geometry["coordinates"].push_back(
×
543
            {round_up(x, precision), round_up(y, precision)});
×
544
      }
545
    }
546
    break;
547
  case (MS_SHAPE_LINE):
×
548
    if (shape->numlines == 0 ||
×
549
        shape->line[0].numpoints < 2) // not enough info for a line
×
550
      return geometry;
551

552
    if (shape->numlines == 1) {
×
553
      geometry["type"] = "LineString";
×
554
      geometry["coordinates"] = json::array();
×
555
      for (int j = 0; j < shape->line[0].numpoints; j++) {
×
556
        double x = shape->line[0].point[j].x;
×
557
        double y = shape->line[0].point[j].y;
×
558
        if (outputCrsAxisInverted)
×
559
          std::swap(x, y);
560
        geometry["coordinates"].push_back(
×
561
            {round_up(x, precision), round_up(y, precision)});
×
562
      }
563
    } else {
564
      geometry["type"] = "MultiLineString";
×
565
      geometry["coordinates"] = json::array();
×
566
      for (int i = 0; i < shape->numlines; i++) {
×
567
        json part = json::array();
×
568
        for (int j = 0; j < shape->line[i].numpoints; j++) {
×
569
          double x = shape->line[i].point[j].x;
×
570
          double y = shape->line[i].point[j].y;
×
571
          if (outputCrsAxisInverted)
×
572
            std::swap(x, y);
573
          part.push_back({round_up(x, precision), round_up(y, precision)});
×
574
        }
575
        geometry["coordinates"].push_back(part);
×
576
      }
577
    }
578
    break;
579
  case (MS_SHAPE_POLYGON):
22✔
580
    if (shape->numlines == 0 ||
22✔
581
        shape->line[0].numpoints <
22✔
582
            4) // not enough info for a polygon (first=last)
583
      return geometry;
584

585
    outerList = msGetOuterList(shape);
22✔
586
    if (outerList == NULL)
22✔
587
      throw std::runtime_error("Unable to allocate list of outer rings.");
×
588
    for (int k = 0; k < shape->numlines; k++) {
50✔
589
      if (outerList[k] == MS_TRUE)
28✔
590
        numOuterRings++;
24✔
591
    }
592

593
    if (numOuterRings == 1) {
22✔
594
      geometry["type"] = "Polygon";
40✔
595
      geometry["coordinates"] = json::array();
20✔
596
      for (int i = 0; i < shape->numlines; i++) {
40✔
597
        json part = json::array();
20✔
598
        for (int j = 0; j < shape->line[i].numpoints; j++) {
15,275✔
599
          double x = shape->line[i].point[j].x;
15,255✔
600
          double y = shape->line[i].point[j].y;
15,255✔
601
          if (outputCrsAxisInverted)
15,255✔
602
            std::swap(x, y);
603
          part.push_back({round_up(x, precision), round_up(y, precision)});
91,530✔
604
        }
605
        geometry["coordinates"].push_back(part);
20✔
606
      }
607
    } else {
608
      geometry["type"] = "MultiPolygon";
4✔
609
      geometry["coordinates"] = json::array();
2✔
610

611
      for (int k = 0; k < shape->numlines; k++) {
10✔
612
        if (outerList[k] ==
8✔
613
            MS_TRUE) { // outer ring: generate polygon and add to coordinates
614
          int *innerList = msGetInnerList(shape, k, outerList);
4✔
615
          if (innerList == NULL) {
4✔
616
            msFree(outerList);
×
617
            throw std::runtime_error("Unable to allocate list of inner rings.");
×
618
          }
619

620
          json polygon = json::array();
4✔
621
          for (int i = 0; i < shape->numlines; i++) {
20✔
622
            if (i == k ||
16✔
623
                innerList[i] ==
12✔
624
                    MS_TRUE) { // add outer ring (k) and any inner rings
625
              json part = json::array();
8✔
626
              for (int j = 0; j < shape->line[i].numpoints; j++) {
54✔
627
                double x = shape->line[i].point[j].x;
46✔
628
                double y = shape->line[i].point[j].y;
46✔
629
                if (outputCrsAxisInverted)
46✔
630
                  std::swap(x, y);
631
                part.push_back(
184✔
632
                    {round_up(x, precision), round_up(y, precision)});
92✔
633
              }
634
              polygon.push_back(part);
8✔
635
            }
636
          }
637

638
          msFree(innerList);
4✔
639
          geometry["coordinates"].push_back(polygon);
4✔
640
        }
641
      }
642
    }
643
    msFree(outerList);
22✔
644
    break;
22✔
645
  default:
×
646
    throw std::runtime_error("Invalid shape type.");
×
647
    break;
648
  }
649

650
  return geometry;
651
}
652

653
/*
654
** Return a GeoJSON representation of a shape.
655
*/
656
static json getFeature(layerObj *layer, shapeObj *shape, gmlItemListObj *items,
23✔
657
                       gmlConstantListObj *constants, int geometry_precision,
658
                       bool outputCrsAxisInverted) {
659
  int i;
660
  json feature; // empty (null)
661

662
  if (!layer || !shape)
23✔
663
    throw std::runtime_error("Null arguments.");
×
664

665
  // initialize
666
  feature = {{"type", "Feature"}, {"properties", json::object()}};
184✔
667

668
  // id
669
  const char *featureIdItem =
670
      msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
23✔
671
  if (featureIdItem == NULL)
23✔
672
    throw std::runtime_error(
673
        "Missing required featureid metadata."); // should have been trapped
×
674
                                                 // earlier
675
  for (i = 0; i < items->numitems; i++) {
95✔
676
    if (strcasecmp(featureIdItem, items->items[i].name) == 0) {
95✔
677
      feature["id"] = shape->values[i];
46✔
678
      break;
23✔
679
    }
680
  }
681

682
  if (i == items->numitems)
23✔
683
    throw std::runtime_error("Feature id not found.");
×
684

685
  // properties - build from items and constants, no group support for now
686

687
  for (int i = 0; i < items->numitems; i++) {
193✔
688
    try {
689
      json item = getFeatureItem(&(items->items[i]), shape->values[i]);
170✔
690
      if (!item.is_null())
170✔
691
        feature["properties"].insert(item.begin(), item.end());
108✔
692
    } catch (const std::runtime_error &) {
×
693
      throw std::runtime_error("Error fetching item.");
×
694
    }
×
695
  }
696

697
  for (int i = 0; i < constants->numconstants; i++) {
23✔
698
    try {
699
      json constant = getFeatureConstant(&(constants->constants[i]));
×
700
      if (!constant.is_null())
×
701
        feature["properties"].insert(constant.begin(), constant.end());
×
702
    } catch (const std::runtime_error &) {
×
703
      throw std::runtime_error("Error fetching constant.");
×
704
    }
×
705
  }
706

707
  // geometry
708
  try {
709
    json geometry =
710
        getFeatureGeometry(shape, geometry_precision, outputCrsAxisInverted);
23✔
711
    if (!geometry.is_null())
23✔
712
      feature["geometry"] = std::move(geometry);
46✔
713
  } catch (const std::runtime_error &) {
×
714
    throw std::runtime_error("Error fetching geometry.");
×
715
  }
×
716

717
  return feature;
23✔
718
}
184✔
719

720
static json getLink(hashTableObj *metadata, const std::string &name) {
11✔
721
  json link;
722

723
  const char *href =
724
      msOWSLookupMetadata(metadata, "A", (name + "_href").c_str());
11✔
725
  if (!href)
11✔
726
    throw std::runtime_error("Missing required link href property.");
×
727

728
  const char *title =
729
      msOWSLookupMetadata(metadata, "A", (name + "_title").c_str());
11✔
730
  const char *type =
731
      msOWSLookupMetadata(metadata, "A", (name + "_type").c_str());
22✔
732

733
  link = {{"href", href},
734
          {"title", title ? title : href},
735
          {"type", type ? type : "text/html"}};
132✔
736

737
  return link;
11✔
738
}
110✔
739

740
static const char *getCollectionDescription(layerObj *layer) {
14✔
741
  const char *description =
742
      msOWSLookupMetadata(&(layer->metadata), "A", "description");
14✔
743
  if (!description)
14✔
744
    description = msOWSLookupMetadata(&(layer->metadata), "OF",
×
745
                                      "abstract"); // fallback on abstract
746
  if (!description)
×
747
    description =
748
        "<!-- Warning: unable to set the collection description. -->"; // finally
749
                                                                       // a
750
                                                                       // warning...
751
  return description;
14✔
752
}
753

754
static const char *getCollectionTitle(layerObj *layer) {
755
  const char *title = msOWSLookupMetadata(&(layer->metadata), "AOF", "title");
12✔
756
  if (!title)
17✔
757
    title = layer->name; // revert to layer name if no title found
×
758
  return title;
759
}
760

761
static int getGeometryPrecision(mapObj *map, layerObj *layer) {
21✔
762
  int geometry_precision = OGCAPI_DEFAULT_GEOMETRY_PRECISION;
763
  if (msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision")) {
21✔
764
    geometry_precision = atoi(
×
765
        msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision"));
766
  } else if (msOWSLookupMetadata(&map->web.metadata, "AF",
21✔
767
                                 "geometry_precision")) {
768
    geometry_precision = atoi(
21✔
769
        msOWSLookupMetadata(&map->web.metadata, "AF", "geometry_precision"));
770
  }
771
  return geometry_precision;
21✔
772
}
773

774
static json getCollection(mapObj *map, layerObj *layer, OGCAPIFormat format,
5✔
775
                          const std::string api_root) {
776
  json collection; // empty (null)
777
  rectObj bbox;
778

779
  if (!map || !layer)
5✔
780
    return collection;
781

782
  if (!includeLayer(map, layer))
5✔
783
    return collection;
784

785
  // initialize some things
786
  if (msOWSGetLayerExtent(map, layer, "AOF", &bbox) == MS_SUCCESS) {
5✔
787
    if (layer->projection.numargs > 0)
5✔
788
      msOWSProjectToWGS84(&layer->projection, &bbox);
5✔
789
    else if (map->projection.numargs > 0)
×
790
      msOWSProjectToWGS84(&map->projection, &bbox);
×
791
    else
792
      throw std::runtime_error(
793
          "Unable to transform bounding box, no projection defined.");
×
794
  } else {
795
    throw std::runtime_error(
796
        "Unable to get collection bounding box."); // might be too harsh since
×
797
                                                   // extent is optional
798
  }
799

800
  const char *description = getCollectionDescription(layer);
5✔
801
  const char *title = getCollectionTitle(layer);
5✔
802

803
  const char *id = layer->name;
5✔
804
  char *id_encoded = msEncodeUrl(id); // free after use
5✔
805

806
  const int geometry_precision = getGeometryPrecision(map, layer);
5✔
807

808
  // build collection object
809
  collection = {{"id", id},
810
                {"description", description},
811
                {"title", title},
812
                {"extent",
813
                 {{"spatial",
814
                   {{"bbox",
815
                     {{round_down(bbox.minx, geometry_precision),
5✔
816
                       round_down(bbox.miny, geometry_precision),
5✔
817
                       round_up(bbox.maxx, geometry_precision),
5✔
818
                       round_up(bbox.maxy, geometry_precision)}}},
5✔
819
                    {"crs", CRS84_URL}}}}},
820
                {"links",
821
                 {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
6✔
822
                   {"type", OGCAPI_MIMETYPE_JSON},
823
                   {"title", "This collection as JSON"},
824
                   {"href", api_root + "/collections/" +
10✔
825
                                std::string(id_encoded) + "?f=json"}},
5✔
826
                  {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
9✔
827
                   {"type", OGCAPI_MIMETYPE_HTML},
828
                   {"title", "This collection as HTML"},
829
                   {"href", api_root + "/collections/" +
10✔
830
                                std::string(id_encoded) + "?f=html"}},
5✔
831
                  {{"rel", "items"},
832
                   {"type", OGCAPI_MIMETYPE_GEOJSON},
833
                   {"title", "Items for this collection as GeoJSON"},
834
                   {"href", api_root + "/collections/" +
10✔
835
                                std::string(id_encoded) + "/items?f=json"}},
5✔
836
                  {{"rel", "items"},
837
                   {"type", OGCAPI_MIMETYPE_HTML},
838
                   {"title", "Items for this collection as HTML"},
839
                   {"href", api_root + "/collections/" +
10✔
840
                                std::string(id_encoded) + "/items?f=html"}}
5✔
841

842
                 }},
843
                {"itemType", "feature"}};
425✔
844

845
  msFree(id_encoded); // done
5✔
846

847
  // handle optional configuration (keywords and links)
848
  const char *value = msOWSLookupMetadata(&(layer->metadata), "A", "keywords");
5✔
849
  if (!value)
5✔
850
    value = msOWSLookupMetadata(&(layer->metadata), "OF",
×
851
                                "keywordlist"); // fallback on keywordlist
852
  if (value) {
×
853
    std::vector<std::string> keywords = msStringSplit(value, ',');
5✔
854
    for (const std::string &keyword : keywords) {
24✔
855
      collection["keywords"].push_back(keyword);
57✔
856
    }
857
  }
858

859
  value = msOWSLookupMetadata(&(layer->metadata), "A", "links");
5✔
860
  if (value) {
5✔
861
    std::vector<std::string> names = msStringSplit(value, ',');
5✔
862
    for (const std::string &name : names) {
10✔
863
      try {
864
        json link = getLink(&(layer->metadata), name);
5✔
865
        collection["links"].push_back(link);
5✔
866
      } catch (const std::runtime_error &e) {
×
867
        throw e;
×
868
      }
×
869
    }
870
  }
871

872
  // Part 2 - CRS support
873
  // Inspect metadata to set the "crs": [] member and "storageCrs" member
874

875
  json jCrsList = getCrsList(map, layer);
5✔
876
  if (!jCrsList.empty()) {
5✔
877
    collection["crs"] = std::move(jCrsList);
5✔
878

879
    std::string storageCrs = getStorageCrs(layer);
5✔
880
    if (!storageCrs.empty()) {
5✔
881
      collection["storageCrs"] = std::move(storageCrs);
10✔
882
    }
883
  }
884

885
  return collection;
886
}
525✔
887

888
/*
889
** Output stuff...
890
*/
891

892
void outputJson(const json &j, const char *mimetype,
20✔
893
                const std::map<std::string, std::string> &extraHeaders) {
894
  std::string js;
895

896
  try {
897
    js = j.dump();
20✔
898
  } catch (...) {
1✔
899
    outputError(OGCAPI_CONFIG_ERROR, "Invalid UTF-8 data, check encoding.");
1✔
900
    return;
901
  }
1✔
902

903
  msIO_setHeader("Content-Type", "%s", mimetype);
19✔
904
  for (const auto &kvp : extraHeaders) {
31✔
905
    msIO_setHeader(kvp.first.c_str(), "%s", kvp.second.c_str());
12✔
906
  }
907
  msIO_sendHeaders();
19✔
908
  msIO_printf("%s\n", js.c_str());
19✔
909
}
910

911
void outputTemplate(const char *directory, const char *filename, const json &j,
5✔
912
                    const char *mimetype) {
913
  std::string _directory(directory);
5✔
914
  std::string _filename(filename);
5✔
915
  Environment env{_directory}; // catch
5✔
916

917
  // ERB-style instead of Mustache (we'll see)
918
  // env.set_expression("<%=", "%>");
919
  // env.set_statement("<%", "%>");
920

921
  // callbacks, need:
922
  //   - match (regex)
923
  //   - contains (substring)
924
  //   - URL encode
925

926
  try {
927
    std::string js = j.dump();
5✔
928
  } catch (...) {
1✔
929
    outputError(OGCAPI_CONFIG_ERROR, "Invalid UTF-8 data, check encoding.");
1✔
930
    return;
931
  }
1✔
932

933
  try {
934
    Template t = env.parse_template(_filename); // catch
4✔
935
    std::string result = env.render(t, j);
4✔
936

937
    msIO_setHeader("Content-Type", "%s", mimetype);
4✔
938
    msIO_sendHeaders();
4✔
939
    msIO_printf("%s\n", result.c_str());
4✔
940
  } catch (const inja::RenderError &e) {
4✔
941
    outputError(OGCAPI_CONFIG_ERROR, "Template rendering error. " +
×
942
                                         std::string(e.what()) + " (" +
×
943
                                         std::string(filename) + ").");
×
944
    return;
945
  } catch (const inja::InjaError &e) {
×
946
    outputError(OGCAPI_CONFIG_ERROR, "InjaError error. " +
×
947
                                         std::string(e.what()) + " (" +
×
948
                                         std::string(filename) + ")." + " (" +
×
949
                                         std::string(directory) + ").");
×
950
    return;
951
  } catch (...) {
×
952
    outputError(OGCAPI_SERVER_ERROR, "General template handling error.");
×
953
    return;
954
  }
×
955
}
5✔
956

957
/*
958
** Generic response output.
959
*/
960
static void
961
outputResponse(mapObj *map, cgiRequestObj *request, OGCAPIFormat format,
24✔
962
               const char *filename, const json &response,
963
               const std::map<std::string, std::string> &extraHeaders =
964
                   std::map<std::string, std::string>()) {
965
  std::string path;
966
  char fullpath[MS_MAXPATHLEN];
967

968
  if (format == OGCAPIFormat::JSON) {
24✔
969
    outputJson(response, OGCAPI_MIMETYPE_JSON, extraHeaders);
5✔
970
  } else if (format == OGCAPIFormat::GeoJSON) {
19✔
971
    outputJson(response, OGCAPI_MIMETYPE_GEOJSON, extraHeaders);
13✔
972
  } else if (format == OGCAPIFormat::OpenAPI_V3) {
6✔
973
    outputJson(response, OGCAPI_MIMETYPE_OPENAPI_V3, extraHeaders);
1✔
974
  } else if (format == OGCAPIFormat::HTML) {
5✔
975
    path = getTemplateDirectory(map, "html_template_directory",
10✔
976
                                "OGCAPI_HTML_TEMPLATE_DIRECTORY");
5✔
977
    if (path.empty()) {
5✔
978
      outputError(OGCAPI_CONFIG_ERROR, "Template directory not set.");
×
979
      return; // bail
×
980
    }
981
    msBuildPath(fullpath, map->mappath, path.c_str());
5✔
982

983
    json j;
984

985
    j["response"] = response; // nest the response so we could write the whole
10✔
986
                              // object in the template
987

988
    // extend the JSON with a few things that we need for templating
989
    j["template"] = {{"path", json::array()},
10✔
990
                     {"params", json::object()},
5✔
991
                     {"api_root", getApiRootUrl(map, request)},
5✔
992
                     {"title", getTitle(map)},
5✔
993
                     {"tags", json::object()}};
85✔
994

995
    // api path
996
    for (int i = 0; i < request->api_path_length; i++)
26✔
997
      j["template"]["path"].push_back(request->api_path[i]);
63✔
998

999
    // parameters (optional)
1000
    for (int i = 0; i < request->NumParams; i++) {
9✔
1001
      if (request->ParamValues[i] &&
4✔
1002
          strlen(request->ParamValues[i]) > 0) { // skip empty params
4✔
1003
        j["template"]["params"].update(
24✔
1004
            {{request->ParamNames[i], request->ParamValues[i]}});
4✔
1005
      }
1006
    }
1007

1008
    // add custom tags (optional)
1009
    const char *tags =
1010
        msOWSLookupMetadata(&(map->web.metadata), "A", "html_tags");
5✔
1011
    if (tags) {
5✔
1012
      std::vector<std::string> names = msStringSplit(tags, ',');
2✔
1013
      for (std::string name : names) {
6✔
1014
        const char *value = msOWSLookupMetadata(&(map->web.metadata), "A",
4✔
1015
                                                ("tag_" + name).c_str());
8✔
1016
        if (value) {
4✔
1017
          j["template"]["tags"].update({{name, value}}); // add object
24✔
1018
        }
1019
      }
1020
    }
1021

1022
    outputTemplate(fullpath, filename, j, OGCAPI_MIMETYPE_HTML);
5✔
1023
  } else {
1024
    outputError(OGCAPI_PARAM_ERROR, "Unsupported format requested.");
×
1025
  }
1026
}
132✔
1027

1028
/*
1029
** Process stuff...
1030
*/
1031
static int processLandingRequest(mapObj *map, cgiRequestObj *request,
3✔
1032
                                 OGCAPIFormat format) {
1033
  json response;
1034

1035
  // define ambiguous elements
1036
  const char *description =
1037
      msOWSLookupMetadata(&(map->web.metadata), "A", "description");
3✔
1038
  if (!description)
3✔
1039
    description =
1040
        msOWSLookupMetadata(&(map->web.metadata), "OF",
×
1041
                            "abstract"); // fallback on abstract if necessary
1042

1043
  // define api root url
1044
  std::string api_root = getApiRootUrl(map, request);
3✔
1045

1046
  // build response object
1047
  //   - consider conditionally excluding links for HTML format
1048
  response = {
1049
      {"title", getTitle(map)},
3✔
1050
      {"description", description ? description : ""},
3✔
1051
      {"links",
1052
       {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
4✔
1053
         {"type", OGCAPI_MIMETYPE_JSON},
1054
         {"title", "This document as JSON"},
1055
         {"href", api_root + "?f=json"}},
3✔
1056
        {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
5✔
1057
         {"type", OGCAPI_MIMETYPE_HTML},
1058
         {"title", "This document as HTML"},
1059
         {"href", api_root + "?f=html"}},
3✔
1060
        {{"rel", "conformance"},
1061
         {"type", OGCAPI_MIMETYPE_JSON},
1062
         {"title",
1063
          "OCG API conformance classes implemented by this server (JSON)"},
1064
         {"href", api_root + "/conformance?f=json"}},
3✔
1065
        {{"rel", "conformance"},
1066
         {"type", OGCAPI_MIMETYPE_HTML},
1067
         {"title", "OCG API conformance classes implemented by this server"},
1068
         {"href", api_root + "/conformance?f=html"}},
3✔
1069
        {{"rel", "data"},
1070
         {"type", OGCAPI_MIMETYPE_JSON},
1071
         {"title", "Information about feature collections available from this "
1072
                   "server (JSON)"},
1073
         {"href", api_root + "/collections?f=json"}},
3✔
1074
        {{"rel", "data"},
1075
         {"type", OGCAPI_MIMETYPE_HTML},
1076
         {"title",
1077
          "Information about feature collections available from this server"},
1078
         {"href", api_root + "/collections?f=html"}},
3✔
1079
        {{"rel", "service-desc"},
1080
         {"type", OGCAPI_MIMETYPE_OPENAPI_V3},
1081
         {"title", "OpenAPI document"},
1082
         {"href", api_root + "/api?f=json"}},
3✔
1083
        {{"rel", "service-doc"},
1084
         {"type", OGCAPI_MIMETYPE_HTML},
1085
         {"title", "API documentation"},
1086
         {"href", api_root + "/api?f=html"}}}}};
345✔
1087

1088
  // handle custom links (optional)
1089
  const char *links = msOWSLookupMetadata(&(map->web.metadata), "A", "links");
3✔
1090
  if (links) {
3✔
1091
    std::vector<std::string> names = msStringSplit(links, ',');
3✔
1092
    for (std::string name : names) {
9✔
1093
      try {
1094
        json link = getLink(&(map->web.metadata), name);
6✔
1095
        response["links"].push_back(link);
6✔
1096
      } catch (const std::runtime_error &e) {
×
1097
        outputError(OGCAPI_CONFIG_ERROR, std::string(e.what()));
×
1098
        return MS_SUCCESS;
1099
      }
×
1100
    }
1101
  }
1102

1103
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_LANDING, response);
3✔
1104
  return MS_SUCCESS;
3✔
1105
}
459✔
1106

1107
static int processConformanceRequest(mapObj *map, cgiRequestObj *request,
1✔
1108
                                     OGCAPIFormat format) {
1109
  json response;
1110

1111
  // build response object
1112
  response = {
1113
      {"conformsTo",
1114
       {
1115
           "http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core",
1116
           "http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections",
1117
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core",
1118
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/oas30",
1119
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/html",
1120
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/geojson",
1121
           "http://www.opengis.net/spec/ogcapi-features-2/1.0/conf/crs",
1122
       }}};
11✔
1123

1124
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_CONFORMANCE,
2✔
1125
                 response);
1126
  return MS_SUCCESS;
1✔
1127
}
12✔
1128

1129
static int processCollectionItemsRequest(mapObj *map, cgiRequestObj *request,
22✔
1130
                                         const char *collectionId,
1131
                                         const char *featureId,
1132
                                         OGCAPIFormat format) {
1133
  json response;
1134
  int i;
1135
  layerObj *layer;
1136

1137
  int limit;
1138
  rectObj bbox;
1139

1140
  int numberMatched = 0;
1141

1142
  // find the right layer
1143
  for (i = 0; i < map->numlayers; i++) {
26✔
1144
    if (strcmp(map->layers[i]->name, collectionId) == 0)
26✔
1145
      break; // match
1146
  }
1147

1148
  if (i == map->numlayers) { // invalid collectionId
22✔
1149
    outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1150
    return MS_SUCCESS;
×
1151
  }
1152

1153
  layer = map->layers[i]; // for convenience
22✔
1154
  layer->status = MS_ON;  // force on (do we need to save and reset?)
22✔
1155

1156
  if (!includeLayer(map, layer)) {
22✔
1157
    outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1158
    return MS_SUCCESS;
×
1159
  }
1160

1161
  //
1162
  // handle parameters specific to this endpoint
1163
  //
1164
  if (getLimit(map, request, layer, &limit) != MS_SUCCESS) {
22✔
1165
    outputError(OGCAPI_PARAM_ERROR, "Bad value for limit.");
×
1166
    return MS_SUCCESS;
×
1167
  }
1168

1169
  std::string api_root = getApiRootUrl(map, request);
22✔
1170
  const char *crs = getRequestParameter(request, "crs");
22✔
1171

1172
  std::string outputCrs = "EPSG:4326";
22✔
1173
  bool outputCrsAxisInverted =
1174
      false; // because above EPSG:4326 is meant to be OGC:CRS84 actually
1175
  std::map<std::string, std::string> extraHeaders;
1176
  if (crs) {
22✔
1177
    bool isExpectedCrs = false;
1178
    for (const auto &crsItem : getCrsList(map, layer)) {
26✔
1179
      if (crs == crsItem.get<std::string>()) {
22✔
1180
        isExpectedCrs = true;
1181
        break;
1182
      }
1183
    }
1184
    if (!isExpectedCrs) {
4✔
1185
      outputError(OGCAPI_PARAM_ERROR, "Bad value for crs.");
2✔
1186
      return MS_SUCCESS;
2✔
1187
    }
1188
    extraHeaders["Content-Crs"] = '<' + std::string(crs) + '>';
6✔
1189
    if (std::string(crs) != CRS84_URL) {
4✔
1190
      if (std::string(crs).find(EPSG_PREFIX_URL) == 0) {
4✔
1191
        const char *code = crs + strlen(EPSG_PREFIX_URL);
2✔
1192
        outputCrs = std::string("EPSG:") + code;
6✔
1193
        outputCrsAxisInverted = msIsAxisInverted(atoi(code));
2✔
1194
      }
1195
    }
1196
  } else {
1197
    extraHeaders["Content-Crs"] = '<' + std::string(CRS84_URL) + '>';
72✔
1198
  }
1199

1200
  struct ReprojectionObjects {
1201
    reprojectionObj *reprojector = NULL;
1202
    projectionObj proj;
1203

1204
    ReprojectionObjects() { msInitProjection(&proj); }
20✔
1205

1206
    ~ReprojectionObjects() {
1207
      msProjectDestroyReprojector(reprojector);
20✔
1208
      msFreeProjection(&proj);
20✔
1209
    }
20✔
1210

1211
    int executeQuery(mapObj *map) {
29✔
1212
      projectionObj backupMapProjection = map->projection;
29✔
1213
      map->projection = proj;
29✔
1214
      int ret = msExecuteQuery(map);
29✔
1215
      map->projection = backupMapProjection;
29✔
1216
      return ret;
29✔
1217
    }
1218
  };
1219
  ReprojectionObjects reprObjs;
1220

1221
  msProjectionInheritContextFrom(&reprObjs.proj, &(map->projection));
20✔
1222
  if (msLoadProjectionString(&reprObjs.proj, outputCrs.c_str()) != 0) {
20✔
1223
    outputError(OGCAPI_SERVER_ERROR, "Cannot instantiate output CRS.");
×
1224
    return MS_SUCCESS;
×
1225
  }
1226

1227
  if (layer->projection.numargs > 0) {
20✔
1228
    if (msProjectionsDiffer(&(layer->projection), &reprObjs.proj)) {
20✔
1229
      reprObjs.reprojector =
13✔
1230
          msProjectCreateReprojector(&(layer->projection), &reprObjs.proj);
13✔
1231
      if (reprObjs.reprojector == NULL) {
13✔
1232
        outputError(OGCAPI_SERVER_ERROR, "Error creating re-projector.");
×
1233
        return MS_SUCCESS;
×
1234
      }
1235
    }
1236
  } else if (map->projection.numargs > 0) {
×
1237
    if (msProjectionsDiffer(&(map->projection), &reprObjs.proj)) {
×
1238
      reprObjs.reprojector =
×
1239
          msProjectCreateReprojector(&(map->projection), &reprObjs.proj);
×
1240
      if (reprObjs.reprojector == NULL) {
×
1241
        outputError(OGCAPI_SERVER_ERROR, "Error creating re-projector.");
×
1242
        return MS_SUCCESS;
×
1243
      }
1244
    }
1245
  } else {
1246
    outputError(OGCAPI_CONFIG_ERROR,
×
1247
                "Unable to transform geometries, no projection defined.");
1248
    return MS_SUCCESS;
×
1249
  }
1250

1251
  if (map->projection.numargs > 0) {
20✔
1252
    msProjectRect(&(map->projection), &reprObjs.proj, &map->extent);
20✔
1253
  }
1254

1255
  if (!getBbox(map, layer, request, &bbox, &reprObjs.proj)) {
20✔
1256
    return MS_SUCCESS;
1257
  }
1258

1259
  int offset = 0;
18✔
1260
  if (featureId) {
18✔
1261
    const char *featureIdItem =
1262
        msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
3✔
1263
    if (featureIdItem == NULL) {
3✔
1264
      outputError(OGCAPI_CONFIG_ERROR, "Missing required featureid metadata.");
×
1265
      return MS_SUCCESS;
×
1266
    }
1267

1268
    // TODO: does featureIdItem exist in the data?
1269

1270
    // optional validation
1271
    const char *featureIdValidation =
1272
        msLookupHashTable(&(layer->validation), featureIdItem);
3✔
1273
    if (featureIdValidation &&
6✔
1274
        msValidateParameter(featureId, featureIdValidation, NULL, NULL, NULL) !=
3✔
1275
            MS_SUCCESS) {
1276
      outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid feature id.");
1✔
1277
      return MS_SUCCESS;
1✔
1278
    }
1279

1280
    map->query.type = MS_QUERY_BY_FILTER;
2✔
1281
    map->query.mode = MS_QUERY_SINGLE;
2✔
1282
    map->query.layer = i;
2✔
1283
    map->query.rect = bbox;
2✔
1284
    map->query.filteritem = strdup(featureIdItem);
2✔
1285

1286
    msInitExpression(&map->query.filter);
2✔
1287
    map->query.filter.type = MS_STRING;
2✔
1288
    map->query.filter.string = strdup(featureId);
2✔
1289

1290
    if (reprObjs.executeQuery(map) != MS_SUCCESS) {
2✔
1291
      outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items id query failed.");
×
1292
      return MS_SUCCESS;
×
1293
    }
1294

1295
    if (!layer->resultcache || layer->resultcache->numresults != 1) {
2✔
1296
      outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items id query failed.");
×
1297
      return MS_SUCCESS;
×
1298
    }
1299
  } else { // bbox query
1300

1301
    const char *compliance_mode =
1302
        msOWSLookupMetadata(&(map->web.metadata), "A", "compliance_mode");
15✔
1303
    if (compliance_mode != NULL && strcasecmp(compliance_mode, "true") == 0) {
15✔
1304
      for (int j = 0; j < request->NumParams; j++) {
44✔
1305
        const char *paramName = request->ParamNames[j];
30✔
1306
        if (strcmp(paramName, "f") == 0 || strcmp(paramName, "bbox") == 0 ||
30✔
1307
            strcmp(paramName, "bbox-crs") == 0 ||
12✔
1308
            strcmp(paramName, "datetime") == 0 ||
10✔
1309
            strcmp(paramName, "limit") == 0 ||
10✔
1310
            strcmp(paramName, "offset") == 0 || strcmp(paramName, "crs") == 0) {
4✔
1311
          // ok
1312
        } else {
1313
          outputError(
1✔
1314
              OGCAPI_PARAM_ERROR,
1315
              (std::string("Unknown query parameter: ") + paramName).c_str());
1✔
1316
          return MS_SUCCESS;
1✔
1317
        }
1318
      }
1319
    }
1320

1321
    map->query.type = MS_QUERY_BY_RECT;
14✔
1322
    map->query.mode = MS_QUERY_MULTIPLE;
14✔
1323
    map->query.layer = i;
14✔
1324
    map->query.rect = bbox;
14✔
1325
    map->query.only_cache_result_count = MS_TRUE;
14✔
1326

1327
    // get number matched
1328
    if (reprObjs.executeQuery(map) != MS_SUCCESS) {
14✔
1329
      outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items query failed.");
×
1330
      return MS_SUCCESS;
×
1331
    }
1332

1333
    if (!layer->resultcache) {
14✔
1334
      outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items query failed.");
×
1335
      return MS_SUCCESS;
×
1336
    }
1337

1338
    numberMatched = layer->resultcache->numresults;
14✔
1339

1340
    if (numberMatched > 0) {
14✔
1341
      map->query.only_cache_result_count = MS_FALSE;
13✔
1342
      map->query.maxfeatures = limit;
13✔
1343

1344
      const char *offsetStr = getRequestParameter(request, "offset");
13✔
1345
      if (offsetStr) {
13✔
1346
        if (msStringToInt(offsetStr, &offset, 10) != MS_SUCCESS) {
1✔
1347
          outputError(OGCAPI_PARAM_ERROR, "Bad value for offset.");
×
1348
          return MS_SUCCESS;
×
1349
        }
1350

1351
        if (offset < 0 || offset >= numberMatched) {
1✔
1352
          outputError(OGCAPI_PARAM_ERROR, "Offset out of range.");
×
1353
          return MS_SUCCESS;
×
1354
        }
1355

1356
        // msExecuteQuery() use a 1-based offset convention, whereas the API
1357
        // uses a 0-based offset convention.
1358
        map->query.startindex = 1 + offset;
1✔
1359
        layer->startindex = 1 + offset;
1✔
1360
      }
1361

1362
      if (reprObjs.executeQuery(map) != MS_SUCCESS || !layer->resultcache) {
13✔
1363
        outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items query failed.");
×
1364
        return MS_SUCCESS;
×
1365
      }
1366
    }
1367
  }
1368

1369
  // build response object
1370
  if (!featureId) {
16✔
1371
    const char *id = layer->name;
14✔
1372
    char *id_encoded = msEncodeUrl(id); // free after use
14✔
1373

1374
    std::string extra_kvp = "&limit=" + std::to_string(limit);
14✔
1375
    extra_kvp += "&offset=" + std::to_string(offset);
28✔
1376

1377
    std::string other_extra_kvp;
1378
    if (crs)
14✔
1379
      other_extra_kvp += "&crs=" + std::string(crs);
4✔
1380
    const char *bbox = getRequestParameter(request, "bbox");
14✔
1381
    if (bbox)
14✔
1382
      other_extra_kvp += "&bbox=" + std::string(bbox);
6✔
1383
    const char *bboxCrs = getRequestParameter(request, "bbox-crs");
14✔
1384
    if (bboxCrs)
14✔
1385
      other_extra_kvp += "&bbox-crs=" + std::string(bboxCrs);
4✔
1386

1387
    response = {
1388
        {"type", "FeatureCollection"},
1389
        {"numberMatched", numberMatched},
1390
        {"numberReturned", layer->resultcache->numresults},
14✔
1391
        {"features", json::array()},
14✔
1392
        {"links",
1393
         {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
17✔
1394
           {"type", OGCAPI_MIMETYPE_GEOJSON},
1395
           {"title", "Items for this collection as GeoJSON"},
1396
           {"href", api_root + "/collections/" + std::string(id_encoded) +
28✔
1397
                        "/items?f=json" + extra_kvp + other_extra_kvp}},
14✔
1398
          {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
25✔
1399
           {"type", OGCAPI_MIMETYPE_HTML},
1400
           {"title", "Items for this collection as HTML"},
1401
           {"href", api_root + "/collections/" + std::string(id_encoded) +
28✔
1402
                        "/items?f=html" + extra_kvp + other_extra_kvp}}}}};
588✔
1403

1404
    if (offset + layer->resultcache->numresults < numberMatched) {
14✔
1405
      response["links"].push_back(
98✔
1406
          {{"rel", "next"},
1407
           {"type", format == OGCAPIFormat::JSON ? OGCAPI_MIMETYPE_GEOJSON
7✔
1408
                                                 : OGCAPI_MIMETYPE_HTML},
1409
           {"title", "next page"},
1410
           {"href",
1411
            api_root + "/collections/" + std::string(id_encoded) +
14✔
1412
                "/items?f=" + (format == OGCAPIFormat::JSON ? "json" : "html") +
14✔
1413
                "&limit=" + std::to_string(limit) + "&offset=" +
28✔
1414
                std::to_string(offset + limit) + other_extra_kvp}});
7✔
1415
    }
1416

1417
    if (offset > 0) {
14✔
1418
      response["links"].push_back(
14✔
1419
          {{"rel", "prev"},
1420
           {"type", format == OGCAPIFormat::JSON ? OGCAPI_MIMETYPE_GEOJSON
1✔
1421
                                                 : OGCAPI_MIMETYPE_HTML},
1422
           {"title", "previous page"},
1423
           {"href",
1424
            api_root + "/collections/" + std::string(id_encoded) +
2✔
1425
                "/items?f=" + (format == OGCAPIFormat::JSON ? "json" : "html") +
2✔
1426
                "&limit=" + std::to_string(limit) +
3✔
1427
                "&offset=" + std::to_string(MS_MAX(0, (offset - limit))) +
2✔
1428
                other_extra_kvp}});
1429
    }
1430

1431
    msFree(id_encoded); // done
14✔
1432
  }
1433

1434
  // features (items)
1435
  {
1436
    shapeObj shape;
1437
    msInitShape(&shape);
16✔
1438

1439
    // we piggyback on GML configuration
1440
    gmlItemListObj *items = msGMLGetItems(layer, "AG");
16✔
1441
    gmlConstantListObj *constants = msGMLGetConstants(layer, "AG");
16✔
1442

1443
    if (!items || !constants) {
16✔
1444
      msGMLFreeItems(items);
×
1445
      msGMLFreeConstants(constants);
×
1446
      outputError(OGCAPI_SERVER_ERROR,
×
1447
                  "Error fetching layer attribute metadata.");
1448
      return MS_SUCCESS;
×
1449
    }
1450

1451
    const int geometry_precision = getGeometryPrecision(map, layer);
16✔
1452

1453
    for (i = 0; i < layer->resultcache->numresults; i++) {
39✔
1454
      int status =
1455
          msLayerGetShape(layer, &shape, &(layer->resultcache->results[i]));
23✔
1456
      if (status != MS_SUCCESS) {
23✔
1457
        msGMLFreeItems(items);
×
1458
        msGMLFreeConstants(constants);
×
1459
        outputError(OGCAPI_SERVER_ERROR, "Error fetching feature.");
×
1460
        return MS_SUCCESS;
×
1461
      }
1462

1463
      if (reprObjs.reprojector) {
23✔
1464
        status = msProjectShapeEx(reprObjs.reprojector, &shape);
16✔
1465
        if (status != MS_SUCCESS) {
16✔
1466
          msGMLFreeItems(items);
×
1467
          msGMLFreeConstants(constants);
×
1468
          msFreeShape(&shape);
×
1469
          outputError(OGCAPI_SERVER_ERROR, "Error reprojecting feature.");
×
1470
          return MS_SUCCESS;
×
1471
        }
1472
      }
1473

1474
      try {
1475
        json feature = getFeature(layer, &shape, items, constants,
1476
                                  geometry_precision, outputCrsAxisInverted);
23✔
1477
        if (featureId) {
23✔
1478
          response = std::move(feature);
2✔
1479
        } else {
1480
          response["features"].emplace_back(std::move(feature));
21✔
1481
        }
1482
      } catch (const std::runtime_error &e) {
×
1483
        msGMLFreeItems(items);
×
1484
        msGMLFreeConstants(constants);
×
1485
        msFreeShape(&shape);
×
1486
        outputError(OGCAPI_SERVER_ERROR,
×
1487
                    "Error getting feature. " + std::string(e.what()));
×
1488
        return MS_SUCCESS;
1489
      }
×
1490

1491
      msFreeShape(&shape); // next
23✔
1492
    }
1493

1494
    msGMLFreeItems(items); // clean up
16✔
1495
    msGMLFreeConstants(constants);
16✔
1496
  }
1497

1498
  // extend the response a bit for templating (HERE)
1499
  if (format == OGCAPIFormat::HTML) {
16✔
1500
    const char *title = getCollectionTitle(layer);
1501
    const char *id = layer->name;
3✔
1502
    response["collection"] = {{"id", id}, {"title", title ? title : ""}};
27✔
1503
  }
1504

1505
  if (featureId) {
16✔
1506
    const char *id = layer->name;
2✔
1507
    char *id_encoded = msEncodeUrl(id); // free after use
2✔
1508

1509
    response["links"] = {
2✔
1510
        {{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
2✔
1511
         {"type", OGCAPI_MIMETYPE_GEOJSON},
1512
         {"title", "This document as GeoJSON"},
1513
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1514
                      "/items/" + featureId + "?f=json"}},
2✔
1515
        {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
4✔
1516
         {"type", OGCAPI_MIMETYPE_HTML},
1517
         {"title", "This document as HTML"},
1518
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1519
                      "/items/" + featureId + "?f=html"}},
2✔
1520
        {{"rel", "collection"},
1521
         {"type", OGCAPI_MIMETYPE_JSON},
1522
         {"title", "This collection as JSON"},
1523
         {"href",
1524
          api_root + "/collections/" + std::string(id_encoded) + "?f=json"}},
4✔
1525
        {{"rel", "collection"},
1526
         {"type", OGCAPI_MIMETYPE_HTML},
1527
         {"title", "This collection as HTML"},
1528
         {"href",
1529
          api_root + "/collections/" + std::string(id_encoded) + "?f=html"}}};
110✔
1530

1531
    msFree(id_encoded);
2✔
1532

1533
    outputResponse(
2✔
1534
        map, request,
1535
        format == OGCAPIFormat::JSON ? OGCAPIFormat::GeoJSON : format,
1536
        OGCAPI_TEMPLATE_HTML_COLLECTION_ITEM, response, extraHeaders);
1537
  } else {
1538
    outputResponse(
25✔
1539
        map, request,
1540
        format == OGCAPIFormat::JSON ? OGCAPIFormat::GeoJSON : format,
1541
        OGCAPI_TEMPLATE_HTML_COLLECTION_ITEMS, response, extraHeaders);
1542
  }
1543
  return MS_SUCCESS;
1544
}
999✔
1545

1546
static int processCollectionRequest(mapObj *map, cgiRequestObj *request,
2✔
1547
                                    const char *collectionId,
1548
                                    OGCAPIFormat format) {
1549
  json response;
1550
  int l;
1551

1552
  for (l = 0; l < map->numlayers; l++) {
2✔
1553
    if (strcmp(map->layers[l]->name, collectionId) == 0)
2✔
1554
      break; // match
1555
  }
1556

1557
  if (l == map->numlayers) { // invalid collectionId
2✔
1558
    outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1559
    return MS_SUCCESS;
×
1560
  }
1561

1562
  try {
1563
    response =
1564
        getCollection(map, map->layers[l], format, getApiRootUrl(map, request));
4✔
1565
    if (response.is_null()) { // same as not found
2✔
1566
      outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1567
      return MS_SUCCESS;
×
1568
    }
1569
  } catch (const std::runtime_error &e) {
×
1570
    outputError(OGCAPI_CONFIG_ERROR,
×
1571
                "Error getting collection. " + std::string(e.what()));
×
1572
    return MS_SUCCESS;
1573
  }
×
1574

1575
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_COLLECTION,
2✔
1576
                 response);
1577
  return MS_SUCCESS;
2✔
1578
}
1579

1580
static int processCollectionsRequest(mapObj *map, cgiRequestObj *request,
1✔
1581
                                     OGCAPIFormat format) {
1582
  json response;
1583
  int i;
1584

1585
  // define api root url
1586
  std::string api_root = getApiRootUrl(map, request);
1✔
1587

1588
  // build response object
1589
  response = {{"links",
1590
               {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
1✔
1591
                 {"type", OGCAPI_MIMETYPE_JSON},
1592
                 {"title", "This document as JSON"},
1593
                 {"href", api_root + "/collections?f=json"}},
1✔
1594
                {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
2✔
1595
                 {"type", OGCAPI_MIMETYPE_HTML},
1596
                 {"title", "This document as HTML"},
1597
                 {"href", api_root + "/collections?f=html"}}}},
1✔
1598
              {"collections", json::array()}};
34✔
1599

1600
  for (i = 0; i < map->numlayers; i++) {
4✔
1601
    try {
1602
      json collection = getCollection(map, map->layers[i], format, api_root);
6✔
1603
      if (!collection.is_null())
3✔
1604
        response["collections"].push_back(collection);
3✔
1605
    } catch (const std::runtime_error &e) {
×
1606
      outputError(OGCAPI_CONFIG_ERROR,
×
1607
                  "Error getting collection." + std::string(e.what()));
×
1608
      return MS_SUCCESS;
1609
    }
×
1610
  }
1611

1612
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_COLLECTIONS,
1✔
1613
                 response);
1614
  return MS_SUCCESS;
1✔
1615
}
43✔
1616

1617
static int processApiRequest(mapObj *map, cgiRequestObj *request,
1✔
1618
                             OGCAPIFormat format) {
1619
  // Strongly inspired from
1620
  // https://github.com/geopython/pygeoapi/blob/master/pygeoapi/openapi.py
1621

1622
  json response;
1623

1624
  response = {
1625
      {"openapi", "3.0.2"},
1626
      {"tags", json::array()},
1✔
1627
  };
7✔
1628

1629
  response["info"] = {
1✔
1630
      {"title", getTitle(map)},
1✔
1631
      {"version", getWebMetadata(map, "A", "version", "1.0.0")},
1✔
1632
  };
7✔
1633

1634
  for (const char *item : {"description", "termsOfService"}) {
3✔
1635
    const char *value = getWebMetadata(map, "AO", item, nullptr);
2✔
1636
    if (value) {
2✔
1637
      response["info"][item] = value;
4✔
1638
    }
1639
  }
1640

1641
  for (const auto &pair : {
3✔
1642
           std::make_pair("name", "contactperson"),
1643
           std::make_pair("url", "contacturl"),
1644
           std::make_pair("email", "contactelectronicmailaddress"),
1645
       }) {
4✔
1646
    const char *value = getWebMetadata(map, "AO", pair.second, nullptr);
3✔
1647
    if (value) {
3✔
1648
      response["info"]["contact"][pair.first] = value;
6✔
1649
    }
1650
  }
1651

1652
  for (const auto &pair : {
2✔
1653
           std::make_pair("name", "licensename"),
1654
           std::make_pair("url", "licenseurl"),
1655
       }) {
3✔
1656
    const char *value = getWebMetadata(map, "AO", pair.second, nullptr);
2✔
1657
    if (value) {
2✔
1658
      response["info"]["license"][pair.first] = value;
×
1659
    }
1660
  }
1661

1662
  {
1663
    const char *value = getWebMetadata(map, "AO", "keywords", nullptr);
1✔
1664
    if (value) {
1✔
1665
      response["info"]["x-keywords"] = value;
2✔
1666
    }
1667
  }
1668

1669
  json server;
1670
  server["url"] = getApiRootUrl(map, request);
3✔
1671

1672
  {
1673
    const char *value =
1674
        getWebMetadata(map, "AO", "server_description", nullptr);
1✔
1675
    if (value) {
1✔
1676
      server["description"] = value;
2✔
1677
    }
1678
  }
1679
  response["servers"].push_back(server);
1✔
1680

1681
  const std::string oapif_schema_base_url = msOWSGetSchemasLocation(map);
1✔
1682
  const std::string oapif_yaml_url = oapif_schema_base_url +
1683
                                     "/ogcapi/features/part1/1.0/openapi/"
1684
                                     "ogcapi-features-1.yaml";
1✔
1685
  const std::string oapif_part2_yaml_url = oapif_schema_base_url +
1686
                                           "/ogcapi/features/part2/1.0/openapi/"
1687
                                           "ogcapi-features-2.yaml";
1✔
1688

1689
  json paths;
1690

1691
  paths["/"]["get"] = {
1✔
1692
      {"summary", "Landing page"},
1693
      {"description", "Landing page"},
1694
      {"tags", {"server"}},
1695
      {"operationId", "getLandingPage"},
1696
      {"parameters",
1697
       {
1698
           {{"$ref", "#/components/parameters/f"}},
1699
       }},
1700
      {"responses",
1701
       {{"200",
1702
         {{"$ref", oapif_yaml_url + "#/components/responses/LandingPage"}}},
1✔
1703
        {"400",
1704
         {{"$ref",
1705
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1706
        {"500",
1707
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1708

1709
  paths["/api"]["get"] = {
1✔
1710
      {"summary", "API documentation"},
1711
      {"description", "API documentation"},
1712
      {"tags", {"server"}},
1713
      {"operationId", "getOpenapi"},
1714
      {"parameters",
1715
       {
1716
           {{"$ref", "#/components/parameters/f"}},
1717
       }},
1718
      {"responses",
1719
       {{"200", {{"$ref", "#/components/responses/200"}}},
1720
        {"400",
1721
         {{"$ref",
1722
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1723
        {"default", {{"$ref", "#/components/responses/default"}}}}}};
42✔
1724

1725
  paths["/conformance"]["get"] = {
1✔
1726
      {"summary", "API conformance definition"},
1727
      {"description", "API conformance definition"},
1728
      {"tags", {"server"}},
1729
      {"operationId", "getConformanceDeclaration"},
1730
      {"parameters",
1731
       {
1732
           {{"$ref", "#/components/parameters/f"}},
1733
       }},
1734
      {"responses",
1735
       {{"200",
1736
         {{"$ref",
1737
           oapif_yaml_url + "#/components/responses/ConformanceDeclaration"}}},
1✔
1738
        {"400",
1739
         {{"$ref",
1740
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1741
        {"500",
1742
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1743

1744
  paths["/collections"]["get"] = {
1✔
1745
      {"summary", "Collections"},
1746
      {"description", "Collections"},
1747
      {"tags", {"server"}},
1748
      {"operationId", "getCollections"},
1749
      {"parameters",
1750
       {
1751
           {{"$ref", "#/components/parameters/f"}},
1752
       }},
1753
      {"responses",
1754
       {{"200",
1755
         {{"$ref", oapif_yaml_url + "#/components/responses/Collections"}}},
1✔
1756
        {"400",
1757
         {{"$ref",
1758
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1759
        {"500",
1760
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1761

1762
  for (int i = 0; i < map->numlayers; i++) {
4✔
1763
    layerObj *layer = map->layers[i];
3✔
1764
    if (!includeLayer(map, layer)) {
3✔
1765
      continue;
×
1766
    }
1767

1768
    json collection_get = {
1769
        {"summary",
1770
         std::string("Get ") + getCollectionTitle(layer) + " metadata"},
3✔
1771
        {"description", getCollectionDescription(layer)},
3✔
1772
        {"tags", {layer->name}},
3✔
1773
        {"operationId", "describe" + std::string(layer->name) + "Collection"},
3✔
1774
        {"parameters",
1775
         {
1776
             {{"$ref", "#/components/parameters/f"}},
1777
         }},
1778
        {"responses",
1779
         {{"200",
1780
           {{"$ref", oapif_yaml_url + "#/components/responses/Collection"}}},
3✔
1781
          {"400",
1782
           {{"$ref",
1783
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1784
          {"500",
1785
           {{"$ref",
1786
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
129✔
1787

1788
    std::string collectionNamePath("/collections/");
×
1789
    collectionNamePath += layer->name;
3✔
1790
    paths[collectionNamePath]["get"] = std::move(collection_get);
3✔
1791

1792
    // check metadata, layer then map
1793
    const char *max_limit_str =
1794
        msOWSLookupMetadata(&(layer->metadata), "A", "max_limit");
3✔
1795
    if (max_limit_str == nullptr)
3✔
1796
      max_limit_str =
1797
          msOWSLookupMetadata(&(map->web.metadata), "A", "max_limit");
3✔
1798
    const int max_limit =
1799
        max_limit_str ? atoi(max_limit_str) : OGCAPI_MAX_LIMIT;
3✔
1800
    const int default_limit = getDefaultLimit(map, layer);
3✔
1801

1802
    json items_get = {
1803
        {"summary", std::string("Get ") + getCollectionTitle(layer) + " items"},
3✔
1804
        {"description", getCollectionDescription(layer)},
3✔
1805
        {"tags", {layer->name}},
1806
        {"operationId", "get" + std::string(layer->name) + "Features"},
3✔
1807
        {"parameters",
1808
         {
1809
             {{"$ref", "#/components/parameters/f"}},
1810
             {{"$ref", oapif_yaml_url + "#/components/parameters/bbox"}},
3✔
1811
             {{"$ref", oapif_yaml_url + "#/components/parameters/datetime"}},
3✔
1812
             {{"$ref",
1813
               oapif_part2_yaml_url + "#/components/parameters/bbox-crs"}},
3✔
1814
             {{"$ref", oapif_part2_yaml_url + "#/components/parameters/crs"}},
3✔
1815
             {{"$ref", "#/components/parameters/offset"}},
1816
         }},
1817
        {"responses",
1818
         {{"200",
1819
           {{"$ref", oapif_yaml_url + "#/components/responses/Features"}}},
3✔
1820
          {"400",
1821
           {{"$ref",
1822
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1823
          {"500",
1824
           {{"$ref",
1825
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
189✔
1826

1827
    json param_limit = {
1828
        {"name", "limit"},
1829
        {"in", "query"},
1830
        {"description", "The optional limit parameter limits the number of "
1831
                        "items that are presented in the response document."},
1832
        {"required", false},
1833
        {"schema",
1834
         {
1835
             {"type", "integer"},
1836
             {"minimum", 1},
1837
             {"maximum", max_limit},
1838
             {"default", default_limit},
1839
         }},
1840
        {"style", "form"},
1841
        {"explode", false},
1842
    };
102✔
1843
    items_get["parameters"].emplace_back(param_limit);
3✔
1844

1845
    std::string itemsPath(collectionNamePath + "/items");
3✔
1846
    paths[itemsPath]["get"] = std::move(items_get);
6✔
1847

1848
    json feature_id_get = {
1849
        {"summary",
1850
         std::string("Get ") + getCollectionTitle(layer) + " item by id"},
3✔
1851
        {"description", getCollectionDescription(layer)},
3✔
1852
        {"tags", {layer->name}},
1853
        {"operationId", "get" + std::string(layer->name) + "Feature"},
3✔
1854
        {"parameters",
1855
         {
1856
             {{"$ref", "#/components/parameters/f"}},
1857
             {{"$ref", oapif_yaml_url + "#/components/parameters/featureId"}},
3✔
1858
         }},
1859
        {"responses",
1860
         {{"200",
1861
           {{"$ref", oapif_yaml_url + "#/components/responses/Feature"}}},
3✔
1862
          {"400",
1863
           {{"$ref",
1864
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1865
          {"404",
1866
           {{"$ref", oapif_yaml_url + "#/components/responses/NotFound"}}},
3✔
1867
          {"500",
1868
           {{"$ref",
1869
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
159✔
1870
    std::string itemsFeatureIdPath(collectionNamePath + "/items/{featureId}");
3✔
1871
    paths[itemsFeatureIdPath]["get"] = std::move(feature_id_get);
6✔
1872
  }
1873

1874
  response["paths"] = std::move(paths);
2✔
1875

1876
  json components;
1877
  components["responses"]["200"] = {{"description", "successful operation"}};
5✔
1878
  components["responses"]["default"] = {
1✔
1879
      {"description", "unexpected error"},
1880
      {"content",
1881
       {{"application/json",
1882
         {{"schema",
1883
           {{"$ref", "https://schemas.opengis.net/ogcapi/common/part1/1.0/"
1884
                     "openapi/schemas/exception.yaml"}}}}}}}};
16✔
1885

1886
  json parameters;
1887
  parameters["f"] = {
1✔
1888
      {"name", "f"},
1889
      {"in", "query"},
1890
      {"description", "The optional f parameter indicates the output format "
1891
                      "which the server shall provide as part of the response "
1892
                      "document.  The default format is GeoJSON."},
1893
      {"required", false},
1894
      {"schema",
1895
       {{"type", "string"}, {"enum", {"json", "html"}}, {"default", "json"}}},
1896
      {"style", "form"},
1897
      {"explode", false},
1898
  };
33✔
1899

1900
  parameters["offset"] = {
1✔
1901
      {"name", "offset"},
1902
      {"in", "query"},
1903
      {"description",
1904
       "The optional offset parameter indicates the index within the result "
1905
       "set from which the server shall begin presenting results in the "
1906
       "response document.  The first element has an index of 0 (default)."},
1907
      {"required", false},
1908
      {"schema",
1909
       {
1910
           {"type", "integer"},
1911
           {"minimum", 0},
1912
           {"default", 0},
1913
       }},
1914
      {"style", "form"},
1915
      {"explode", false},
1916
  };
31✔
1917

1918
  components["parameters"] = std::move(parameters);
2✔
1919

1920
  response["components"] = std::move(components);
2✔
1921

1922
  // TODO: "tags" array ?
1923

1924
  outputResponse(map, request,
3✔
1925
                 format == OGCAPIFormat::JSON ? OGCAPIFormat::OpenAPI_V3
1926
                                              : format,
1927
                 OGCAPI_TEMPLATE_HTML_OPENAPI, response);
1928
  return MS_SUCCESS;
1✔
1929
}
1,167✔
1930

1931
#endif
1932

1933
OGCAPIFormat msGetOutputFormat(cgiRequestObj *request) {
31✔
1934
  OGCAPIFormat format; // all endpoints need a format
1935
  const char *p = getRequestParameter(request, "f");
31✔
1936

1937
  // if f= query parameter is not specified, use HTTP Accept header if available
1938
  if (p == nullptr) {
31✔
1939
    const char *accept = getenv("HTTP_ACCEPT");
2✔
1940
    if (accept) {
2✔
1941
      if (strcmp(accept, "*/*") == 0)
1✔
1942
        p = OGCAPI_MIMETYPE_JSON;
1943
      else
1944
        p = accept;
1945
    }
1946
  }
1947

1948
  if (p &&
30✔
1949
      (strcmp(p, "json") == 0 || strstr(p, OGCAPI_MIMETYPE_JSON) != nullptr ||
30✔
1950
       strstr(p, OGCAPI_MIMETYPE_GEOJSON) != nullptr ||
4✔
1951
       strstr(p, OGCAPI_MIMETYPE_OPENAPI_V3) != nullptr)) {
1952
    format = OGCAPIFormat::JSON;
1953
  } else if (p && (strcmp(p, "html") == 0 ||
4✔
1954
                   strstr(p, OGCAPI_MIMETYPE_HTML) != nullptr)) {
1955
    format = OGCAPIFormat::HTML;
1956
  } else if (p) {
1957
    std::string errorMsg("Unsupported format requested: ");
×
1958
    errorMsg += p;
1959
    outputError(OGCAPI_PARAM_ERROR, errorMsg.c_str());
×
1960
    format = OGCAPIFormat::Invalid;
1961
  } else {
1962
    format = OGCAPIFormat::HTML; // default for now
1963
  }
1964

1965
  return format;
31✔
1966
}
1967

1968
int msOGCAPIDispatchRequest(mapObj *map, cgiRequestObj *request) {
31✔
1969
#ifdef USE_OGCAPI_SVR
1970

1971
  // make sure ogcapi requests are enabled for this map
1972
  int status = msOWSRequestIsEnabled(map, NULL, "AO", "OGCAPI", MS_FALSE);
31✔
1973
  if (status != MS_TRUE) {
31✔
1974
    msSetError(MS_OGCAPIERR, "OGC API requests are not enabled.",
×
1975
               "msCGIDispatchAPIRequest()");
1976
    return MS_FAILURE; // let normal error handling take over
×
1977
  }
1978

1979
  for (int i = 0; i < request->NumParams; i++) {
84✔
1980
    for (int j = i + 1; j < request->NumParams; j++) {
96✔
1981
      if (strcmp(request->ParamNames[i], request->ParamNames[j]) == 0) {
43✔
1982
        std::string errorMsg("Query parameter ");
1✔
1983
        errorMsg += request->ParamNames[i];
1✔
1984
        errorMsg += " is repeated";
1985
        outputError(OGCAPI_PARAM_ERROR, errorMsg.c_str());
2✔
1986
        return MS_SUCCESS;
1987
      }
1988
    }
1989
  }
1990

1991
  OGCAPIFormat format;
1992
  format = msGetOutputFormat(request);
30✔
1993

1994
  if (format == OGCAPIFormat::Invalid) {
30✔
1995
    return MS_SUCCESS; // avoid any downstream MapServer processing
1996
  }
1997

1998
  if (request->api_path_length == 2) {
30✔
1999

2000
    return processLandingRequest(map, request, format);
3✔
2001

2002
  } else if (request->api_path_length == 3) {
2003

2004
    if (strcmp(request->api_path[2], "conformance") == 0) {
3✔
2005
      return processConformanceRequest(map, request, format);
1✔
2006
    } else if (strcmp(request->api_path[2], "conformance.html") == 0) {
2✔
2007
      return processConformanceRequest(map, request, OGCAPIFormat::HTML);
×
2008
    } else if (strcmp(request->api_path[2], "collections") == 0) {
2✔
2009
      return processCollectionsRequest(map, request, format);
1✔
2010
    } else if (strcmp(request->api_path[2], "collections.html") == 0) {
1✔
2011
      return processCollectionsRequest(map, request, OGCAPIFormat::HTML);
×
2012
    } else if (strcmp(request->api_path[2], "api") == 0) {
1✔
2013
      return processApiRequest(map, request, format);
1✔
2014
    }
2015

2016
  } else if (request->api_path_length == 4) {
2017

2018
    if (strcmp(request->api_path[2], "collections") ==
2✔
2019
        0) { // next argument (3) is collectionId
2020
      return processCollectionRequest(map, request, request->api_path[3],
2✔
2021
                                      format);
2✔
2022
    }
2023

2024
  } else if (request->api_path_length == 5) {
2025

2026
    if (strcmp(request->api_path[2], "collections") == 0 &&
19✔
2027
        strcmp(request->api_path[4], "items") ==
19✔
2028
            0) { // middle argument (3) is the collectionId
2029
      return processCollectionItemsRequest(map, request, request->api_path[3],
19✔
2030
                                           NULL, format);
19✔
2031
    }
2032

2033
  } else if (request->api_path_length == 6) {
2034

2035
    if (strcmp(request->api_path[2], "collections") == 0 &&
3✔
2036
        strcmp(request->api_path[4], "items") ==
3✔
2037
            0) { // middle argument (3) is the collectionId, last argument (5)
2038
                 // is featureId
2039
      return processCollectionItemsRequest(map, request, request->api_path[3],
3✔
2040
                                           request->api_path[5], format);
3✔
2041
    }
2042
  }
2043

2044
  outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid API path.");
×
2045
  return MS_SUCCESS; // avoid any downstream MapServer processing
×
2046
#else
2047
  msSetError(MS_OGCAPIERR, "OGC API server support is not enabled.",
2048
             "msOGCAPIDispatchRequest()");
2049
  return MS_FAILURE;
2050
#endif
2051
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc