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

geographika / mapserver / 19276394673

11 Nov 2025 07:28PM UTC coverage: 41.713% (+0.03%) from 41.681%
19276394673

push

github

geographika
Add null guard and missing map tests

2 of 4 new or added lines in 1 file covered. (50.0%)

10 existing lines in 2 files now uncovered.

62784 of 150515 relevant lines covered (41.71%)

25209.01 hits per line

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

78.21
/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 msOGCAPIOutputError(OGCAPIErrorType errorType,
8✔
78
                         const std::string &description) {
79
  const char *code = "";
8✔
80
  const char *status = "";
81
  switch (errorType) {
8✔
82
  case OGCAPI_SERVER_ERROR: {
×
83
    code = "ServerError";
×
84
    status = "500";
85
    break;
×
86
  }
87
  case OGCAPI_CONFIG_ERROR: {
2✔
88
    code = "ConfigError";
2✔
89
    status = "500";
90
    break;
2✔
91
  }
92
  case OGCAPI_PARAM_ERROR: {
5✔
93
    code = "InvalidParameterValue";
5✔
94
    status = "400";
95
    break;
5✔
96
  }
97
  case OGCAPI_NOT_FOUND_ERROR: {
1✔
98
    code = "NotFound";
1✔
99
    status = "404";
100
    break;
1✔
101
  }
102
  }
103

104
  json j = {{"code", code}, {"description", description}};
56✔
105

106
  msIO_setHeader("Content-Type", "%s", OGCAPI_MIMETYPE_JSON);
8✔
107
  msIO_setHeader("Status", "%s", status);
8✔
108
  msIO_sendHeaders();
8✔
109
  msIO_printf("%s\n", j.dump().c_str());
16✔
110
}
64✔
111

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

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

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

133
  for (i = 0; i < request->NumParams; i++) {
400✔
134
    if (strcmp(item, request->ParamNames[i]) == 0)
303✔
135
      return request->ParamValues[i];
79✔
136
  }
137

138
  return NULL;
139
}
140

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

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

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

156
  return max_limit;
24✔
157
}
158

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

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

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

174
  return default_limit;
29✔
175
}
176

177
static std::string getExtraParameters(mapObj *map, layerObj *layer) {
49✔
178

179
  std::string extra_params;
180

181
  // first check layer metadata if layer is not null
182
  if (layer) {
49✔
183
    const char *layerVal =
184
        msOWSLookupMetadata(&(layer->metadata), "AO", "extra_params");
32✔
185
    if (layerVal) // only check for null
32✔
186
      extra_params = std::string("&") + layerVal;
12✔
187
  }
188

189
  if (extra_params.empty() && map) {
49✔
190
    const char *mapVal =
191
        msOWSLookupMetadata(&(map->web.metadata), "AO", "extra_params");
45✔
192
    if (mapVal)
45✔
193
      extra_params = std::string("&") + mapVal;
45✔
194
  }
195

196
  return extra_params;
49✔
197
}
198

199
/*
200
** Returns the limit as an int - between 1 and getMaxLimit(). We always return a
201
*valid value...
202
*/
203
static int getLimit(mapObj *map, cgiRequestObj *request, layerObj *layer,
24✔
204
                    int *limit) {
205
  int status;
206
  const char *p;
207

208
  int max_limit;
209
  max_limit = getMaxLimit(map, layer);
24✔
210

211
  p = getRequestParameter(request, "limit");
24✔
212
  if (!p || (p && strlen(p) == 0)) { // missing or empty
24✔
213
    *limit = MS_MIN(getDefaultLimit(map, layer),
13✔
214
                    max_limit); // max could be smaller than the default
215
  } else {
216
    status = msStringToInt(p, limit, 10);
11✔
217
    if (status != MS_SUCCESS)
11✔
218
      return MS_FAILURE;
219

220
    if (*limit <= 0) {
11✔
221
      *limit = MS_MIN(getDefaultLimit(map, layer),
×
222
                      max_limit); // max could be smaller than the default
223
    } else {
224
      *limit = MS_MIN(*limit, max_limit);
11✔
225
    }
226
  }
227

228
  return MS_SUCCESS;
229
}
230

231
// Return the content of the "crs" member of the /collections/{name} response
232
static json getCrsList(mapObj *map, layerObj *layer) {
21✔
233
  char *pszSRSList = NULL;
21✔
234
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "AOF", MS_FALSE,
21✔
235
                   &pszSRSList);
236
  if (!pszSRSList)
21✔
237
    msOWSGetEPSGProj(&(map->projection), &(map->web.metadata), "AOF", MS_FALSE,
×
238
                     &pszSRSList);
239
  json jCrsList;
240
  if (pszSRSList) {
21✔
241
    const auto tokens = msStringSplit(pszSRSList, ' ');
21✔
242
    for (const auto &crs : tokens) {
53✔
243
      if (crs.find("EPSG:") == 0) {
32✔
244
        if (jCrsList.empty()) {
11✔
245
          jCrsList.push_back(CRS84_URL);
42✔
246
        }
247
        const std::string url =
248
            std::string(EPSG_PREFIX_URL) + crs.substr(strlen("EPSG:"));
64✔
249
        jCrsList.push_back(url);
64✔
250
      }
251
    }
252
    msFree(pszSRSList);
21✔
253
  }
254
  return jCrsList;
21✔
255
}
256

257
// Return the content of the "storageCrs" member of the /collections/{name}
258
// response
259
static std::string getStorageCrs(layerObj *layer) {
13✔
260
  std::string storageCrs;
261
  char *pszFirstSRS = nullptr;
13✔
262
  msOWSGetEPSGProj(&(layer->projection), &(layer->metadata), "AOF", MS_TRUE,
13✔
263
                   &pszFirstSRS);
264
  if (pszFirstSRS) {
13✔
265
    if (std::string(pszFirstSRS).find("EPSG:") == 0) {
26✔
266
      storageCrs =
267
          std::string(EPSG_PREFIX_URL) + (pszFirstSRS + strlen("EPSG:"));
39✔
268
    }
269
    msFree(pszFirstSRS);
13✔
270
  }
271
  return storageCrs;
13✔
272
}
273

274
/*
275
** Returns the bbox in output CRS (CRS84 by default, or "crs" request parameter
276
*when specified)
277
*/
278
static bool getBbox(mapObj *map, layerObj *layer, cgiRequestObj *request,
22✔
279
                    rectObj *bbox, projectionObj *outputProj) {
280
  int status;
281

282
  const char *bboxParam = getRequestParameter(request, "bbox");
22✔
283
  if (!bboxParam || strlen(bboxParam) == 0) { // missing or empty extent
22✔
284
    rectObj rect;
285
    if (FLTLayerSetInvalidRectIfSupported(layer, &rect, "AO")) {
17✔
286
      bbox->minx = rect.minx;
×
287
      bbox->miny = rect.miny;
×
288
      bbox->maxx = rect.maxx;
×
289
      bbox->maxy = rect.maxy;
×
290
    } else {
291
      // assign map->extent (no projection necessary)
292
      bbox->minx = map->extent.minx;
17✔
293
      bbox->miny = map->extent.miny;
17✔
294
      bbox->maxx = map->extent.maxx;
17✔
295
      bbox->maxy = map->extent.maxy;
17✔
296
    }
297
  } else {
17✔
298
    const auto tokens = msStringSplit(bboxParam, ',');
5✔
299
    if (tokens.size() != 4) {
5✔
300
      msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
301
      return false;
×
302
    }
303

304
    double values[4];
305
    for (int i = 0; i < 4; i++) {
25✔
306
      status = msStringToDouble(tokens[i].c_str(), &values[i]);
20✔
307
      if (status != MS_SUCCESS) {
20✔
308
        msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
309
        return false;
×
310
      }
311
    }
312

313
    bbox->minx = values[0]; // assign
5✔
314
    bbox->miny = values[1];
5✔
315
    bbox->maxx = values[2];
5✔
316
    bbox->maxy = values[3];
5✔
317

318
    // validate bbox is well-formed (degenerate is ok)
319
    if (MS_VALID_SEARCH_EXTENT(*bbox) != MS_TRUE) {
5✔
320
      msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
×
321
      return false;
×
322
    }
323

324
    std::string bboxCrs = "EPSG:4326";
5✔
325
    bool axisInverted =
326
        false; // because above EPSG:4326 is meant to be OGC:CRS84 actually
327
    const char *bboxCrsParam = getRequestParameter(request, "bbox-crs");
5✔
328
    if (bboxCrsParam) {
5✔
329
      bool isExpectedCrs = false;
330
      for (const auto &crsItem : getCrsList(map, layer)) {
26✔
331
        if (bboxCrsParam == crsItem.get<std::string>()) {
22✔
332
          isExpectedCrs = true;
333
          break;
334
        }
335
      }
336
      if (!isExpectedCrs) {
4✔
337
        msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for bbox-crs.");
2✔
338
        return false;
2✔
339
      }
340
      if (std::string(bboxCrsParam) != CRS84_URL) {
4✔
341
        if (std::string(bboxCrsParam).find(EPSG_PREFIX_URL) == 0) {
4✔
342
          const char *code = bboxCrsParam + strlen(EPSG_PREFIX_URL);
2✔
343
          bboxCrs = std::string("EPSG:") + code;
6✔
344
          axisInverted = msIsAxisInverted(atoi(code));
2✔
345
        }
346
      }
347
    }
348
    if (axisInverted) {
2✔
349
      std::swap(bbox->minx, bbox->miny);
350
      std::swap(bbox->maxx, bbox->maxy);
351
    }
352

353
    projectionObj bboxProj;
354
    msInitProjection(&bboxProj);
3✔
355
    msProjectionInheritContextFrom(&bboxProj, &(map->projection));
3✔
356
    if (msLoadProjectionString(&bboxProj, bboxCrs.c_str()) != 0) {
3✔
357
      msFreeProjection(&bboxProj);
×
358
      msOGCAPIOutputError(OGCAPI_SERVER_ERROR, "Cannot process bbox-crs.");
×
359
      return false;
×
360
    }
361

362
    status = msProjectRect(&bboxProj, outputProj, bbox);
3✔
363
    msFreeProjection(&bboxProj);
3✔
364
    if (status != MS_SUCCESS) {
3✔
365
      msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
366
                          "Cannot reproject bbox from bbox-crs to output CRS.");
367
      return false;
×
368
    }
369
  }
370

371
  return true;
372
}
373

374
/*
375
** Returns the template directory location or NULL if it isn't set.
376
*/
377
std::string msOGCAPIGetTemplateDirectory(mapObj *map, const char *key,
11✔
378
                                         const char *envvar) {
379
  const char *directory = NULL;
380

381
  if (map != NULL) {
11✔
382
    directory = msOWSLookupMetadata(&(map->web.metadata), "A", key);
9✔
383
  }
384

385
  if (directory == NULL) {
9✔
386
    directory = CPLGetConfigOption(envvar, NULL);
2✔
387
  }
388

389
  std::string s;
390
  if (directory != NULL) {
11✔
391
    s = directory;
392
    if (!s.empty() && (s.back() != '/' && s.back() != '\\')) {
11✔
393
      // add a trailing slash if missing
394
      std::string slash = "/";
3✔
395
#ifdef _WIN32
396
      slash = "\\";
397
#endif
398
      s += slash;
399
    }
400
  }
401

402
  return s;
11✔
403
}
404

405
/*
406
** Returns the service title from oga_{key} and/or ows_{key} or a default value
407
*if not set.
408
*/
409
static const char *getWebMetadata(mapObj *map, const char *domain,
410
                                  const char *key, const char *defaultVal) {
411
  const char *value;
412

413
  if ((value = msOWSLookupMetadata(&(map->web.metadata), domain, key)) != NULL)
17✔
414
    return value;
415
  else
416
    return defaultVal;
1✔
417
}
418

419
/*
420
** Returns the service title from oga|ows_title or a default value if not set.
421
*/
422
static const char *getTitle(mapObj *map) {
423
  return getWebMetadata(map, "OA", "title", OGCAPI_DEFAULT_TITLE);
424
}
425

426
/*
427
** Returns the API root URL from oga_onlineresource or builds a value if not
428
*set.
429
*/
430
std::string msOGCAPIGetApiRootUrl(mapObj *map, cgiRequestObj *request,
50✔
431
                                  const char *namespaces) {
432
  const char *root;
433
  if ((root = msOWSLookupMetadata(&(map->web.metadata), namespaces,
50✔
434
                                  "onlineresource")) != NULL) {
435
    return std::string(root);
48✔
436
  }
437

438
  std::string api_root;
439
  if (char *res = msBuildOnlineResource(NULL, request)) {
2✔
440
    api_root = res;
441
    free(res);
×
442

443
    // find last ogcapi in the string and strip the rest to get the root API
444
    std::size_t pos = api_root.rfind("ogcapi");
445
    if (pos != std::string::npos) {
×
446
      api_root = api_root.substr(0, pos + std::string("ogcapi").size());
×
447
    } else {
448
      // strip trailing '?' or '/' and append "/ogcapi"
449
      while (!api_root.empty() &&
×
450
             (api_root.back() == '?' || api_root.back() == '/')) {
×
451
        api_root.pop_back();
452
      }
453
      api_root += "/ogcapi";
454
    }
455
  }
456

457
  if (api_root.empty()) {
2✔
458
    api_root = "/ogcapi";
459
  }
460

461
  return api_root;
2✔
462
}
463

464
static json getFeatureConstant(const gmlConstantObj *constant) {
×
465
  json j; // empty (null)
466

467
  if (!constant)
×
468
    throw std::runtime_error("Null constant metadata.");
×
469
  if (!constant->value)
×
470
    return j;
471

472
  // initialize
473
  j = {{constant->name, constant->value}};
×
474

475
  return j;
×
476
}
×
477

478
static json getFeatureItem(const gmlItemObj *item, const char *value) {
346✔
479
  json j; // empty (null)
480
  const char *key;
481

482
  if (!item)
346✔
483
    throw std::runtime_error("Null item metadata.");
×
484
  if (!item->visible)
346✔
485
    return j;
486

487
  if (item->alias)
196✔
488
    key = item->alias;
68✔
489
  else
490
    key = item->name;
128✔
491

492
  // initialize
493
  j = {{key, value}};
784✔
494

495
  if (item->type &&
260✔
496
      (EQUAL(item->type, "Date") || EQUAL(item->type, "DateTime") ||
64✔
497
       EQUAL(item->type, "Time"))) {
48✔
498
    struct tm tm;
499
    if (msParseTime(value, &tm) == MS_TRUE) {
16✔
500
      char tmpValue[64];
501
      if (EQUAL(item->type, "Date"))
16✔
502
        snprintf(tmpValue, sizeof(tmpValue), "%04d-%02d-%02d",
×
503
                 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
×
504
      else if (EQUAL(item->type, "Time"))
16✔
505
        snprintf(tmpValue, sizeof(tmpValue), "%02d:%02d:%02dZ", tm.tm_hour,
×
506
                 tm.tm_min, tm.tm_sec);
507
      else
508
        snprintf(tmpValue, sizeof(tmpValue), "%04d-%02d-%02dT%02d:%02d:%02dZ",
16✔
509
                 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
16✔
510
                 tm.tm_min, tm.tm_sec);
511

512
      j = {{key, tmpValue}};
64✔
513
    }
514
  } else if (item->type &&
196✔
515
             (EQUAL(item->type, "Integer") || EQUAL(item->type, "Long"))) {
48✔
516
    try {
517
      j = {{key, std::stoll(value)}};
80✔
518
    } catch (const std::exception &) {
×
519
    }
×
520
  } else if (item->type && EQUAL(item->type, "Real")) {
164✔
521
    try {
522
      j = {{key, std::stod(value)}};
160✔
523
    } catch (const std::exception &) {
×
524
    }
×
525
  } else if (item->type && EQUAL(item->type, "Boolean")) {
132✔
526
    if (EQUAL(value, "0") || EQUAL(value, "false")) {
×
527
      j = {{key, false}};
×
528
    } else {
529
      j = {{key, true}};
×
530
    }
531
  }
532

533
  return j;
534
}
1,088✔
535

536
static double round_down(double value, int decimal_places) {
26✔
537
  const double multiplier = std::pow(10.0, decimal_places);
538
  return std::floor(value * multiplier) / multiplier;
26✔
539
}
540
// https://stackoverflow.com/questions/25925290/c-round-a-double-up-to-2-decimal-places
541
static double round_up(double value, int decimal_places) {
30,674✔
542
  const double multiplier = std::pow(10.0, decimal_places);
543
  return std::ceil(value * multiplier) / multiplier;
30,674✔
544
}
545

546
static json getFeatureGeometry(shapeObj *shape, int precision,
45✔
547
                               bool outputCrsAxisInverted) {
548
  json geometry; // empty (null)
549
  int *outerList = NULL, numOuterRings = 0;
550

551
  if (!shape)
45✔
552
    throw std::runtime_error("Null shape.");
×
553

554
  switch (shape->type) {
45✔
555
  case (MS_SHAPE_POINT):
23✔
556
    if (shape->numlines == 0 ||
23✔
557
        shape->line[0].numpoints == 0) // not enough info for a point
23✔
558
      return geometry;
559

560
    if (shape->line[0].numpoints == 1) {
23✔
561
      geometry["type"] = "Point";
23✔
562
      double x = shape->line[0].point[0].x;
23✔
563
      double y = shape->line[0].point[0].y;
23✔
564
      if (outputCrsAxisInverted)
23✔
565
        std::swap(x, y);
566
      geometry["coordinates"] = {round_up(x, precision),
46✔
567
                                 round_up(y, precision)};
115✔
568
    } else {
569
      geometry["type"] = "MultiPoint";
×
570
      geometry["coordinates"] = json::array();
×
571
      for (int j = 0; j < shape->line[0].numpoints; j++) {
×
572
        double x = shape->line[0].point[j].x;
×
573
        double y = shape->line[0].point[j].y;
×
574
        if (outputCrsAxisInverted)
×
575
          std::swap(x, y);
576
        geometry["coordinates"].push_back(
×
577
            {round_up(x, precision), round_up(y, precision)});
×
578
      }
579
    }
580
    break;
581
  case (MS_SHAPE_LINE):
×
582
    if (shape->numlines == 0 ||
×
583
        shape->line[0].numpoints < 2) // not enough info for a line
×
584
      return geometry;
585

586
    if (shape->numlines == 1) {
×
587
      geometry["type"] = "LineString";
×
588
      geometry["coordinates"] = json::array();
×
589
      for (int j = 0; j < shape->line[0].numpoints; j++) {
×
590
        double x = shape->line[0].point[j].x;
×
591
        double y = shape->line[0].point[j].y;
×
592
        if (outputCrsAxisInverted)
×
593
          std::swap(x, y);
594
        geometry["coordinates"].push_back(
×
595
            {round_up(x, precision), round_up(y, precision)});
×
596
      }
597
    } else {
598
      geometry["type"] = "MultiLineString";
×
599
      geometry["coordinates"] = json::array();
×
600
      for (int i = 0; i < shape->numlines; i++) {
×
601
        json part = json::array();
×
602
        for (int j = 0; j < shape->line[i].numpoints; j++) {
×
603
          double x = shape->line[i].point[j].x;
×
604
          double y = shape->line[i].point[j].y;
×
605
          if (outputCrsAxisInverted)
×
606
            std::swap(x, y);
607
          part.push_back({round_up(x, precision), round_up(y, precision)});
×
608
        }
609
        geometry["coordinates"].push_back(part);
×
610
      }
611
    }
612
    break;
613
  case (MS_SHAPE_POLYGON):
22✔
614
    if (shape->numlines == 0 ||
22✔
615
        shape->line[0].numpoints <
22✔
616
            4) // not enough info for a polygon (first=last)
617
      return geometry;
618

619
    outerList = msGetOuterList(shape);
22✔
620
    if (outerList == NULL)
22✔
621
      throw std::runtime_error("Unable to allocate list of outer rings.");
×
622
    for (int k = 0; k < shape->numlines; k++) {
50✔
623
      if (outerList[k] == MS_TRUE)
28✔
624
        numOuterRings++;
24✔
625
    }
626

627
    if (numOuterRings == 1) {
22✔
628
      geometry["type"] = "Polygon";
40✔
629
      geometry["coordinates"] = json::array();
20✔
630
      for (int i = 0; i < shape->numlines; i++) {
40✔
631
        json part = json::array();
20✔
632
        for (int j = 0; j < shape->line[i].numpoints; j++) {
15,275✔
633
          double x = shape->line[i].point[j].x;
15,255✔
634
          double y = shape->line[i].point[j].y;
15,255✔
635
          if (outputCrsAxisInverted)
15,255✔
636
            std::swap(x, y);
637
          part.push_back({round_up(x, precision), round_up(y, precision)});
91,530✔
638
        }
639
        geometry["coordinates"].push_back(part);
20✔
640
      }
641
    } else {
642
      geometry["type"] = "MultiPolygon";
4✔
643
      geometry["coordinates"] = json::array();
2✔
644

645
      for (int k = 0; k < shape->numlines; k++) {
10✔
646
        if (outerList[k] ==
8✔
647
            MS_TRUE) { // outer ring: generate polygon and add to coordinates
648
          int *innerList = msGetInnerList(shape, k, outerList);
4✔
649
          if (innerList == NULL) {
4✔
650
            msFree(outerList);
×
651
            throw std::runtime_error("Unable to allocate list of inner rings.");
×
652
          }
653

654
          json polygon = json::array();
4✔
655
          for (int i = 0; i < shape->numlines; i++) {
20✔
656
            if (i == k ||
16✔
657
                innerList[i] ==
12✔
658
                    MS_TRUE) { // add outer ring (k) and any inner rings
659
              json part = json::array();
8✔
660
              for (int j = 0; j < shape->line[i].numpoints; j++) {
54✔
661
                double x = shape->line[i].point[j].x;
46✔
662
                double y = shape->line[i].point[j].y;
46✔
663
                if (outputCrsAxisInverted)
46✔
664
                  std::swap(x, y);
665
                part.push_back(
184✔
666
                    {round_up(x, precision), round_up(y, precision)});
92✔
667
              }
668
              polygon.push_back(part);
8✔
669
            }
670
          }
671

672
          msFree(innerList);
4✔
673
          geometry["coordinates"].push_back(polygon);
4✔
674
        }
675
      }
676
    }
677
    msFree(outerList);
22✔
678
    break;
22✔
679
  default:
×
680
    throw std::runtime_error("Invalid shape type.");
×
681
    break;
682
  }
683

684
  return geometry;
685
}
686

687
/*
688
** Return a GeoJSON representation of a shape.
689
*/
690
static json getFeature(layerObj *layer, shapeObj *shape, gmlItemListObj *items,
45✔
691
                       gmlConstantListObj *constants, int geometry_precision,
692
                       bool outputCrsAxisInverted) {
693
  int i;
694
  json feature; // empty (null)
695

696
  if (!layer || !shape)
45✔
697
    throw std::runtime_error("Null arguments.");
×
698

699
  // initialize
700
  feature = {{"type", "Feature"}, {"properties", json::object()}};
360✔
701

702
  // id
703
  const char *featureIdItem =
704
      msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
45✔
705
  if (featureIdItem == NULL)
45✔
706
    throw std::runtime_error(
707
        "Missing required featureid metadata."); // should have been trapped
×
708
                                                 // earlier
709
  for (i = 0; i < items->numitems; i++) {
205✔
710
    if (strcasecmp(featureIdItem, items->items[i].name) == 0) {
205✔
711
      feature["id"] = shape->values[i];
90✔
712
      break;
45✔
713
    }
714
  }
715

716
  if (i == items->numitems)
45✔
717
    throw std::runtime_error("Feature id not found.");
×
718

719
  // properties - build from items and constants, no group support for now
720

721
  for (int i = 0; i < items->numitems; i++) {
391✔
722
    try {
723
      json item = getFeatureItem(&(items->items[i]), shape->values[i]);
346✔
724
      if (!item.is_null())
346✔
725
        feature["properties"].insert(item.begin(), item.end());
196✔
726
    } catch (const std::runtime_error &) {
×
727
      throw std::runtime_error("Error fetching item.");
×
728
    }
×
729
  }
730

731
  for (int i = 0; i < constants->numconstants; i++) {
45✔
732
    try {
733
      json constant = getFeatureConstant(&(constants->constants[i]));
×
734
      if (!constant.is_null())
×
735
        feature["properties"].insert(constant.begin(), constant.end());
×
736
    } catch (const std::runtime_error &) {
×
737
      throw std::runtime_error("Error fetching constant.");
×
738
    }
×
739
  }
740

741
  // geometry
742
  try {
743
    json geometry =
744
        getFeatureGeometry(shape, geometry_precision, outputCrsAxisInverted);
45✔
745
    if (!geometry.is_null())
45✔
746
      feature["geometry"] = std::move(geometry);
90✔
747
  } catch (const std::runtime_error &) {
×
748
    throw std::runtime_error("Error fetching geometry.");
×
749
  }
×
750

751
  return feature;
45✔
752
}
360✔
753

754
static json getLink(hashTableObj *metadata, const std::string &name) {
17✔
755
  json link;
756

757
  const char *href =
758
      msOWSLookupMetadata(metadata, "A", (name + "_href").c_str());
17✔
759
  if (!href)
17✔
760
    throw std::runtime_error("Missing required link href property.");
×
761

762
  const char *title =
763
      msOWSLookupMetadata(metadata, "A", (name + "_title").c_str());
17✔
764
  const char *type =
765
      msOWSLookupMetadata(metadata, "A", (name + "_type").c_str());
34✔
766

767
  link = {{"href", href},
768
          {"title", title ? title : href},
769
          {"type", type ? type : "text/html"}};
204✔
770

771
  return link;
17✔
772
}
170✔
773

774
static const char *getCollectionDescription(layerObj *layer) {
22✔
775
  const char *description =
776
      msOWSLookupMetadata(&(layer->metadata), "A", "description");
22✔
777
  if (!description)
22✔
778
    description = msOWSLookupMetadata(&(layer->metadata), "OF",
×
779
                                      "abstract"); // fallback on abstract
780
  if (!description)
×
781
    description =
782
        "<!-- Warning: unable to set the collection description. -->"; // finally
783
                                                                       // a
784
                                                                       // warning...
785
  return description;
22✔
786
}
787

788
static const char *getCollectionTitle(layerObj *layer) {
789
  const char *title = msOWSLookupMetadata(&(layer->metadata), "AOF", "title");
13✔
790
  if (!title)
26✔
791
    title = layer->name; // revert to layer name if no title found
×
792
  return title;
793
}
794

795
static int getGeometryPrecision(mapObj *map, layerObj *layer) {
32✔
796
  int geometry_precision = OGCAPI_DEFAULT_GEOMETRY_PRECISION;
797
  if (msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision")) {
32✔
798
    geometry_precision = atoi(
×
799
        msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision"));
800
  } else if (msOWSLookupMetadata(&map->web.metadata, "AF",
32✔
801
                                 "geometry_precision")) {
802
    geometry_precision = atoi(
21✔
803
        msOWSLookupMetadata(&map->web.metadata, "AF", "geometry_precision"));
804
  }
805
  return geometry_precision;
32✔
806
}
807

808
static json getCollection(mapObj *map, layerObj *layer, OGCAPIFormat format,
13✔
809
                          const std::string &api_root) {
810
  json collection; // empty (null)
811
  rectObj bbox;
812

813
  if (!map || !layer)
13✔
814
    return collection;
815

816
  if (!includeLayer(map, layer))
13✔
817
    return collection;
818

819
  // initialize some things
820
  if (msOWSGetLayerExtent(map, layer, "AOF", &bbox) == MS_SUCCESS) {
13✔
821
    if (layer->projection.numargs > 0)
13✔
822
      msOWSProjectToWGS84(&layer->projection, &bbox);
13✔
823
    else if (map->projection.numargs > 0)
×
824
      msOWSProjectToWGS84(&map->projection, &bbox);
×
825
    else
826
      throw std::runtime_error(
827
          "Unable to transform bounding box, no projection defined.");
×
828
  } else {
829
    throw std::runtime_error(
830
        "Unable to get collection bounding box."); // might be too harsh since
×
831
                                                   // extent is optional
832
  }
833

834
  const char *description = getCollectionDescription(layer);
13✔
835
  const char *title = getCollectionTitle(layer);
13✔
836

837
  const char *id = layer->name;
13✔
838
  char *id_encoded = msEncodeUrl(id); // free after use
13✔
839

840
  const int geometry_precision = getGeometryPrecision(map, layer);
13✔
841

842
  const std::string extra_params = getExtraParameters(map, layer);
13✔
843

844
  // build collection object
845
  collection = {
846
      {"id", id},
847
      {"description", description},
848
      {"title", title},
849
      {"extent",
850
       {{"spatial",
851
         {{"bbox",
852
           {{round_down(bbox.minx, geometry_precision),
13✔
853
             round_down(bbox.miny, geometry_precision),
13✔
854
             round_up(bbox.maxx, geometry_precision),
13✔
855
             round_up(bbox.maxy, geometry_precision)}}},
13✔
856
          {"crs", CRS84_URL}}}}},
857
      {"links",
858
       {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
18✔
859
         {"type", OGCAPI_MIMETYPE_JSON},
860
         {"title", "This collection as JSON"},
861
         {"href", api_root + "/collections/" + std::string(id_encoded) +
26✔
862
                      "?f=json" + extra_params}},
13✔
863
        {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
21✔
864
         {"type", OGCAPI_MIMETYPE_HTML},
865
         {"title", "This collection as HTML"},
866
         {"href", api_root + "/collections/" + std::string(id_encoded) +
26✔
867
                      "?f=html" + extra_params}},
13✔
868
        {{"rel", "items"},
869
         {"type", OGCAPI_MIMETYPE_GEOJSON},
870
         {"title", "Items for this collection as GeoJSON"},
871
         {"href", api_root + "/collections/" + std::string(id_encoded) +
26✔
872
                      "/items?f=json" + extra_params}},
13✔
873
        {{"rel", "items"},
874
         {"type", OGCAPI_MIMETYPE_HTML},
875
         {"title", "Items for this collection as HTML"},
876
         {"href", api_root + "/collections/" + std::string(id_encoded) +
26✔
877
                      "/items?f=html" + extra_params}}
13✔
878

879
       }},
880
      {"itemType", "feature"}};
1,105✔
881

882
  msFree(id_encoded); // done
13✔
883

884
  // handle optional configuration (keywords and links)
885
  const char *value = msOWSLookupMetadata(&(layer->metadata), "A", "keywords");
13✔
886
  if (!value)
13✔
887
    value = msOWSLookupMetadata(&(layer->metadata), "OF",
8✔
888
                                "keywordlist"); // fallback on keywordlist
889
  if (value) {
8✔
890
    std::vector<std::string> keywords = msStringSplit(value, ',');
5✔
891
    for (const std::string &keyword : keywords) {
24✔
892
      collection["keywords"].push_back(keyword);
57✔
893
    }
894
  }
895

896
  value = msOWSLookupMetadata(&(layer->metadata), "A", "links");
13✔
897
  if (value) {
13✔
898
    std::vector<std::string> names = msStringSplit(value, ',');
9✔
899
    for (const std::string &name : names) {
18✔
900
      try {
901
        json link = getLink(&(layer->metadata), name);
9✔
902
        collection["links"].push_back(link);
9✔
903
      } catch (const std::runtime_error &e) {
×
904
        throw e;
×
905
      }
×
906
    }
907
  }
908

909
  // Part 2 - CRS support
910
  // Inspect metadata to set the "crs": [] member and "storageCrs" member
911

912
  json jCrsList = getCrsList(map, layer);
13✔
913
  if (!jCrsList.empty()) {
13✔
914
    collection["crs"] = std::move(jCrsList);
13✔
915

916
    std::string storageCrs = getStorageCrs(layer);
13✔
917
    if (!storageCrs.empty()) {
13✔
918
      collection["storageCrs"] = std::move(storageCrs);
26✔
919
    }
920
  }
921

922
  return collection;
923
}
1,365✔
924

925
/*
926
** Output stuff...
927
*/
928

929
void msOGCAPIOutputJson(
35✔
930
    const json &j, const char *mimetype,
931
    const std::map<std::string, std::string> &extraHeaders) {
932
  std::string js;
933

934
  try {
935
    js = j.dump();
35✔
936
  } catch (...) {
1✔
937
    msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
1✔
938
                        "Invalid UTF-8 data, check encoding.");
939
    return;
940
  }
1✔
941

942
  msIO_setHeader("Content-Type", "%s", mimetype);
34✔
943
  for (const auto &kvp : extraHeaders) {
48✔
944
    msIO_setHeader(kvp.first.c_str(), "%s", kvp.second.c_str());
14✔
945
  }
946
  msIO_sendHeaders();
34✔
947
  msIO_printf("%s\n", js.c_str());
34✔
948
}
949

950
void msOGCAPIOutputTemplate(const char *directory, const char *filename,
11✔
951
                            const json &j, const char *mimetype) {
952
  std::string _directory(directory);
11✔
953
  std::string _filename(filename);
11✔
954
  Environment env{_directory}; // catch
11✔
955

956
  // ERB-style instead of Mustache (we'll see)
957
  // env.set_expression("<%=", "%>");
958
  // env.set_statement("<%", "%>");
959

960
  // callbacks, need:
961
  //   - match (regex)
962
  //   - contains (substring)
963
  //   - URL encode
964

965
  try {
966
    std::string js = j.dump();
11✔
967
  } catch (...) {
1✔
968
    msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
1✔
969
                        "Invalid UTF-8 data, check encoding.");
970
    return;
971
  }
1✔
972

973
  try {
974
    Template t = env.parse_template(_filename); // catch
10✔
975
    std::string result = env.render(t, j);
10✔
976

977
    msIO_setHeader("Content-Type", "%s", mimetype);
10✔
978
    msIO_sendHeaders();
10✔
979
    msIO_printf("%s\n", result.c_str());
10✔
980
  } catch (const inja::RenderError &e) {
10✔
981
    msOGCAPIOutputError(OGCAPI_CONFIG_ERROR, "Template rendering error. " +
×
982
                                                 std::string(e.what()) + " (" +
×
983
                                                 std::string(filename) + ").");
×
984
    return;
UNCOV
985
  } catch (const inja::InjaError &e) {
×
UNCOV
986
    msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
×
UNCOV
987
                        "InjaError error. " + std::string(e.what()) + " (" +
×
UNCOV
988
                            std::string(filename) + ")." + " (" +
×
UNCOV
989
                            std::string(directory) + ").");
×
990
    return;
UNCOV
991
  } catch (...) {
×
992
    msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
993
                        "General template handling error.");
994
    return;
995
  }
×
996
}
11✔
997

998
/*
999
** Generic response output.
1000
*/
1001
static void
1002
outputResponse(mapObj *map, cgiRequestObj *request, OGCAPIFormat format,
35✔
1003
               const char *filename, const json &response,
1004
               const std::map<std::string, std::string> &extraHeaders =
1005
                   std::map<std::string, std::string>()) {
1006
  std::string path;
1007
  char fullpath[MS_MAXPATHLEN];
1008

1009
  if (format == OGCAPIFormat::JSON) {
35✔
1010
    msOGCAPIOutputJson(response, OGCAPI_MIMETYPE_JSON, extraHeaders);
10✔
1011
  } else if (format == OGCAPIFormat::GeoJSON) {
25✔
1012
    msOGCAPIOutputJson(response, OGCAPI_MIMETYPE_GEOJSON, extraHeaders);
15✔
1013
  } else if (format == OGCAPIFormat::OpenAPI_V3) {
10✔
1014
    msOGCAPIOutputJson(response, OGCAPI_MIMETYPE_OPENAPI_V3, extraHeaders);
1✔
1015
  } else if (format == OGCAPIFormat::HTML) {
9✔
1016
    path = msOGCAPIGetTemplateDirectory(map, "html_template_directory",
18✔
1017
                                        "OGCAPI_HTML_TEMPLATE_DIRECTORY");
9✔
1018
    if (path.empty()) {
9✔
1019
      msOGCAPIOutputError(OGCAPI_CONFIG_ERROR, "Template directory not set.");
×
1020
      return; // bail
×
1021
    }
1022
    msBuildPath(fullpath, map->mappath, path.c_str());
9✔
1023

1024
    json j;
1025

1026
    j["response"] = response; // nest the response so we could write the whole
9✔
1027
                              // object in the template
1028

1029
    // extend the JSON with a few things that we need for templating
1030
    const std::string extra_params = getExtraParameters(map, nullptr);
9✔
1031

1032
    j["template"] = {{"path", json::array()},
18✔
1033
                     {"params", json::object()},
9✔
1034
                     {"api_root", msOGCAPIGetApiRootUrl(map, request)},
9✔
1035
                     {"extra_params", extra_params},
1036
                     {"title", getTitle(map)},
9✔
1037
                     {"tags", json::object()}};
180✔
1038

1039
    // api path
1040
    for (int i = 0; i < request->api_path_length; i++)
46✔
1041
      j["template"]["path"].push_back(request->api_path[i]);
111✔
1042

1043
    // parameters (optional)
1044
    for (int i = 0; i < request->NumParams; i++) {
25✔
1045
      if (request->ParamValues[i] &&
16✔
1046
          strlen(request->ParamValues[i]) > 0) { // skip empty params
16✔
1047
        j["template"]["params"].update(
84✔
1048
            {{request->ParamNames[i], request->ParamValues[i]}});
14✔
1049
      }
1050
    }
1051

1052
    // add custom tags (optional)
1053
    const char *tags =
1054
        msOWSLookupMetadata(&(map->web.metadata), "A", "html_tags");
9✔
1055
    if (tags) {
9✔
1056
      std::vector<std::string> names = msStringSplit(tags, ',');
2✔
1057
      for (std::string name : names) {
6✔
1058
        const char *value = msOWSLookupMetadata(&(map->web.metadata), "A",
4✔
1059
                                                ("tag_" + name).c_str());
8✔
1060
        if (value) {
4✔
1061
          j["template"]["tags"].update({{name, value}}); // add object
24✔
1062
        }
1063
      }
1064
    }
1065

1066
    msOGCAPIOutputTemplate(fullpath, filename, j, OGCAPI_MIMETYPE_HTML);
9✔
1067
  } else {
1068
    msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Unsupported format requested.");
×
1069
  }
1070
}
279✔
1071

1072
/*
1073
** Process stuff...
1074
*/
1075
static int processLandingRequest(mapObj *map, cgiRequestObj *request,
5✔
1076
                                 OGCAPIFormat format) {
1077
  json response;
1078

1079
  // define ambiguous elements
1080
  const char *description =
1081
      msOWSLookupMetadata(&(map->web.metadata), "A", "description");
5✔
1082
  if (!description)
5✔
1083
    description =
1084
        msOWSLookupMetadata(&(map->web.metadata), "OF",
2✔
1085
                            "abstract"); // fallback on abstract if necessary
1086

1087
  const std::string extra_params = getExtraParameters(map, nullptr);
5✔
1088

1089
  // define api root url
1090
  std::string api_root = msOGCAPIGetApiRootUrl(map, request);
5✔
1091

1092
  // build response object
1093
  //   - consider conditionally excluding links for HTML format
1094
  response = {
1095
      {"title", getTitle(map)},
5✔
1096
      {"description", description ? description : ""},
7✔
1097
      {"links",
1098
       {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
6✔
1099
         {"type", OGCAPI_MIMETYPE_JSON},
1100
         {"title", "This document as JSON"},
1101
         {"href", api_root + "?f=json" + extra_params}},
5✔
1102
        {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
9✔
1103
         {"type", OGCAPI_MIMETYPE_HTML},
1104
         {"title", "This document as HTML"},
1105
         {"href", api_root + "?f=html" + extra_params}},
5✔
1106
        {{"rel", "conformance"},
1107
         {"type", OGCAPI_MIMETYPE_JSON},
1108
         {"title",
1109
          "OCG API conformance classes implemented by this server (JSON)"},
1110
         {"href", api_root + "/conformance?f=json" + extra_params}},
5✔
1111
        {{"rel", "conformance"},
1112
         {"type", OGCAPI_MIMETYPE_HTML},
1113
         {"title", "OCG API conformance classes implemented by this server"},
1114
         {"href", api_root + "/conformance?f=html" + extra_params}},
5✔
1115
        {{"rel", "data"},
1116
         {"type", OGCAPI_MIMETYPE_JSON},
1117
         {"title", "Information about feature collections available from this "
1118
                   "server (JSON)"},
1119
         {"href", api_root + "/collections?f=json" + extra_params}},
5✔
1120
        {{"rel", "data"},
1121
         {"type", OGCAPI_MIMETYPE_HTML},
1122
         {"title",
1123
          "Information about feature collections available from this server"},
1124
         {"href", api_root + "/collections?f=html" + extra_params}},
5✔
1125
        {{"rel", "service-desc"},
1126
         {"type", OGCAPI_MIMETYPE_OPENAPI_V3},
1127
         {"title", "OpenAPI document"},
1128
         {"href", api_root + "/api?f=json" + extra_params}},
5✔
1129
        {{"rel", "service-doc"},
1130
         {"type", OGCAPI_MIMETYPE_HTML},
1131
         {"title", "API documentation"},
1132
         {"href", api_root + "/api?f=html" + extra_params}}}}};
575✔
1133

1134
  // handle custom links (optional)
1135
  const char *links = msOWSLookupMetadata(&(map->web.metadata), "A", "links");
5✔
1136
  if (links) {
5✔
1137
    std::vector<std::string> names = msStringSplit(links, ',');
5✔
1138
    for (std::string name : names) {
13✔
1139
      try {
1140
        json link = getLink(&(map->web.metadata), name);
8✔
1141
        response["links"].push_back(link);
8✔
1142
      } catch (const std::runtime_error &e) {
×
1143
        msOGCAPIOutputError(OGCAPI_CONFIG_ERROR, std::string(e.what()));
×
1144
        return MS_SUCCESS;
1145
      }
×
1146
    }
1147
  }
1148

1149
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_LANDING, response);
5✔
1150
  return MS_SUCCESS;
5✔
1151
}
765✔
1152

1153
static int processConformanceRequest(mapObj *map, cgiRequestObj *request,
1✔
1154
                                     OGCAPIFormat format) {
1155
  json response;
1156

1157
  // build response object
1158
  response = {
1159
      {"conformsTo",
1160
       {
1161
           "http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core",
1162
           "http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections",
1163
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core",
1164
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/oas30",
1165
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/html",
1166
           "http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/geojson",
1167
           "http://www.opengis.net/spec/ogcapi-features-2/1.0/conf/crs",
1168
       }}};
11✔
1169

1170
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_CONFORMANCE,
2✔
1171
                 response);
1172
  return MS_SUCCESS;
1✔
1173
}
12✔
1174

1175
static int processCollectionItemsRequest(mapObj *map, cgiRequestObj *request,
24✔
1176
                                         const char *collectionId,
1177
                                         const char *featureId,
1178
                                         OGCAPIFormat format) {
1179
  json response;
1180
  int i;
1181
  layerObj *layer;
1182

1183
  int limit;
1184
  rectObj bbox;
1185

1186
  int numberMatched = 0;
1187

1188
  // find the right layer
1189
  for (i = 0; i < map->numlayers; i++) {
31✔
1190
    if (strcmp(map->layers[i]->name, collectionId) == 0)
31✔
1191
      break; // match
1192
  }
1193

1194
  if (i == map->numlayers) { // invalid collectionId
24✔
1195
    msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1196
    return MS_SUCCESS;
×
1197
  }
1198

1199
  layer = map->layers[i]; // for convenience
24✔
1200
  layer->status = MS_ON;  // force on (do we need to save and reset?)
24✔
1201

1202
  if (!includeLayer(map, layer)) {
24✔
1203
    msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1204
    return MS_SUCCESS;
×
1205
  }
1206

1207
  //
1208
  // handle parameters specific to this endpoint
1209
  //
1210
  if (getLimit(map, request, layer, &limit) != MS_SUCCESS) {
24✔
1211
    msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for limit.");
×
1212
    return MS_SUCCESS;
×
1213
  }
1214

1215
  std::string api_root = msOGCAPIGetApiRootUrl(map, request);
24✔
1216
  const char *crs = getRequestParameter(request, "crs");
24✔
1217

1218
  std::string outputCrs = "EPSG:4326";
24✔
1219
  bool outputCrsAxisInverted =
1220
      false; // because above EPSG:4326 is meant to be OGC:CRS84 actually
1221
  std::map<std::string, std::string> extraHeaders;
1222
  if (crs) {
24✔
1223
    bool isExpectedCrs = false;
1224
    for (const auto &crsItem : getCrsList(map, layer)) {
26✔
1225
      if (crs == crsItem.get<std::string>()) {
22✔
1226
        isExpectedCrs = true;
1227
        break;
1228
      }
1229
    }
1230
    if (!isExpectedCrs) {
4✔
1231
      msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for crs.");
2✔
1232
      return MS_SUCCESS;
2✔
1233
    }
1234
    extraHeaders["Content-Crs"] = '<' + std::string(crs) + '>';
6✔
1235
    if (std::string(crs) != CRS84_URL) {
4✔
1236
      if (std::string(crs).find(EPSG_PREFIX_URL) == 0) {
4✔
1237
        const char *code = crs + strlen(EPSG_PREFIX_URL);
2✔
1238
        outputCrs = std::string("EPSG:") + code;
6✔
1239
        outputCrsAxisInverted = msIsAxisInverted(atoi(code));
2✔
1240
      }
1241
    }
1242
  } else {
1243
    extraHeaders["Content-Crs"] = '<' + std::string(CRS84_URL) + '>';
80✔
1244
  }
1245

1246
  struct ReprojectionObjects {
1247
    reprojectionObj *reprojector = NULL;
1248
    projectionObj proj;
1249

1250
    ReprojectionObjects() { msInitProjection(&proj); }
22✔
1251

1252
    ~ReprojectionObjects() {
1253
      msProjectDestroyReprojector(reprojector);
22✔
1254
      msFreeProjection(&proj);
22✔
1255
    }
22✔
1256

1257
    int executeQuery(mapObj *map) {
35✔
1258
      projectionObj backupMapProjection = map->projection;
35✔
1259
      map->projection = proj;
35✔
1260
      int ret = msExecuteQuery(map);
35✔
1261
      map->projection = backupMapProjection;
35✔
1262
      return ret;
35✔
1263
    }
1264
  };
1265
  ReprojectionObjects reprObjs;
1266

1267
  msProjectionInheritContextFrom(&reprObjs.proj, &(map->projection));
22✔
1268
  if (msLoadProjectionString(&reprObjs.proj, outputCrs.c_str()) != 0) {
22✔
1269
    msOGCAPIOutputError(OGCAPI_SERVER_ERROR, "Cannot instantiate output CRS.");
×
1270
    return MS_SUCCESS;
×
1271
  }
1272

1273
  if (layer->projection.numargs > 0) {
22✔
1274
    if (msProjectionsDiffer(&(layer->projection), &reprObjs.proj)) {
22✔
1275
      reprObjs.reprojector =
15✔
1276
          msProjectCreateReprojector(&(layer->projection), &reprObjs.proj);
15✔
1277
      if (reprObjs.reprojector == NULL) {
15✔
1278
        msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
1279
                            "Error creating re-projector.");
1280
        return MS_SUCCESS;
×
1281
      }
1282
    }
1283
  } else if (map->projection.numargs > 0) {
×
1284
    if (msProjectionsDiffer(&(map->projection), &reprObjs.proj)) {
×
1285
      reprObjs.reprojector =
×
1286
          msProjectCreateReprojector(&(map->projection), &reprObjs.proj);
×
1287
      if (reprObjs.reprojector == NULL) {
×
1288
        msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
1289
                            "Error creating re-projector.");
1290
        return MS_SUCCESS;
×
1291
      }
1292
    }
1293
  } else {
1294
    msOGCAPIOutputError(
×
1295
        OGCAPI_CONFIG_ERROR,
1296
        "Unable to transform geometries, no projection defined.");
1297
    return MS_SUCCESS;
×
1298
  }
1299

1300
  if (map->projection.numargs > 0) {
22✔
1301
    msProjectRect(&(map->projection), &reprObjs.proj, &map->extent);
22✔
1302
  }
1303

1304
  if (!getBbox(map, layer, request, &bbox, &reprObjs.proj)) {
22✔
1305
    return MS_SUCCESS;
1306
  }
1307

1308
  int offset = 0;
20✔
1309
  if (featureId) {
20✔
1310
    const char *featureIdItem =
1311
        msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
3✔
1312
    if (featureIdItem == NULL) {
3✔
1313
      msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
×
1314
                          "Missing required featureid metadata.");
1315
      return MS_SUCCESS;
×
1316
    }
1317

1318
    // TODO: does featureIdItem exist in the data?
1319

1320
    // optional validation
1321
    const char *featureIdValidation =
1322
        msLookupHashTable(&(layer->validation), featureIdItem);
3✔
1323
    if (featureIdValidation &&
6✔
1324
        msValidateParameter(featureId, featureIdValidation, NULL, NULL, NULL) !=
3✔
1325
            MS_SUCCESS) {
1326
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid feature id.");
1✔
1327
      return MS_SUCCESS;
1✔
1328
    }
1329

1330
    map->query.type = MS_QUERY_BY_FILTER;
2✔
1331
    map->query.mode = MS_QUERY_SINGLE;
2✔
1332
    map->query.layer = i;
2✔
1333
    map->query.rect = bbox;
2✔
1334
    map->query.filteritem = strdup(featureIdItem);
2✔
1335

1336
    msInitExpression(&map->query.filter);
2✔
1337
    map->query.filter.type = MS_STRING;
2✔
1338
    map->query.filter.string = strdup(featureId);
2✔
1339

1340
    if (reprObjs.executeQuery(map) != MS_SUCCESS) {
2✔
1341
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR,
×
1342
                          "Collection items id query failed.");
1343
      return MS_SUCCESS;
×
1344
    }
1345

1346
    if (!layer->resultcache || layer->resultcache->numresults != 1) {
2✔
1347
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR,
×
1348
                          "Collection items id query failed.");
1349
      return MS_SUCCESS;
×
1350
    }
1351
  } else { // bbox query
1352
    map->query.type = MS_QUERY_BY_RECT;
17✔
1353
    map->query.mode = MS_QUERY_MULTIPLE;
17✔
1354
    map->query.layer = i;
17✔
1355
    map->query.rect = bbox;
17✔
1356
    map->query.only_cache_result_count = MS_TRUE;
17✔
1357

1358
    // get number matched
1359
    if (reprObjs.executeQuery(map) != MS_SUCCESS) {
17✔
1360
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR,
×
1361
                          "Collection items query failed.");
1362
      return MS_SUCCESS;
×
1363
    }
1364

1365
    if (!layer->resultcache) {
17✔
1366
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR,
×
1367
                          "Collection items query failed.");
1368
      return MS_SUCCESS;
×
1369
    }
1370

1371
    numberMatched = layer->resultcache->numresults;
17✔
1372

1373
    if (numberMatched > 0) {
17✔
1374
      map->query.only_cache_result_count = MS_FALSE;
16✔
1375
      map->query.maxfeatures = limit;
16✔
1376

1377
      const char *offsetStr = getRequestParameter(request, "offset");
16✔
1378
      if (offsetStr) {
16✔
1379
        if (msStringToInt(offsetStr, &offset, 10) != MS_SUCCESS) {
1✔
1380
          msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Bad value for offset.");
×
1381
          return MS_SUCCESS;
×
1382
        }
1383

1384
        if (offset < 0 || offset >= numberMatched) {
1✔
1385
          msOGCAPIOutputError(OGCAPI_PARAM_ERROR, "Offset out of range.");
×
1386
          return MS_SUCCESS;
×
1387
        }
1388

1389
        // msExecuteQuery() use a 1-based offset convention, whereas the API
1390
        // uses a 0-based offset convention.
1391
        map->query.startindex = 1 + offset;
1✔
1392
        layer->startindex = 1 + offset;
1✔
1393
      }
1394

1395
      if (reprObjs.executeQuery(map) != MS_SUCCESS || !layer->resultcache) {
16✔
1396
        msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR,
×
1397
                            "Collection items query failed.");
1398
        return MS_SUCCESS;
×
1399
      }
1400
    }
1401
  }
1402

1403
  const std::string extra_params = getExtraParameters(map, layer);
19✔
1404

1405
  // build response object
1406
  if (!featureId) {
19✔
1407
    const char *id = layer->name;
17✔
1408
    char *id_encoded = msEncodeUrl(id); // free after use
17✔
1409

1410
    std::string extra_kvp = "&limit=" + std::to_string(limit);
17✔
1411
    extra_kvp += "&offset=" + std::to_string(offset);
34✔
1412

1413
    std::string other_extra_kvp;
1414
    if (crs)
17✔
1415
      other_extra_kvp += "&crs=" + std::string(crs);
4✔
1416
    const char *bbox = getRequestParameter(request, "bbox");
17✔
1417
    if (bbox)
17✔
1418
      other_extra_kvp += "&bbox=" + std::string(bbox);
6✔
1419
    const char *bboxCrs = getRequestParameter(request, "bbox-crs");
17✔
1420
    if (bboxCrs)
17✔
1421
      other_extra_kvp += "&bbox-crs=" + std::string(bboxCrs);
4✔
1422

1423
    response = {{"type", "FeatureCollection"},
1424
                {"numberMatched", numberMatched},
1425
                {"numberReturned", layer->resultcache->numresults},
17✔
1426
                {"features", json::array()},
17✔
1427
                {"links",
1428
                 {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
21✔
1429
                   {"type", OGCAPI_MIMETYPE_GEOJSON},
1430
                   {"title", "Items for this collection as GeoJSON"},
1431
                   {"href", api_root + "/collections/" +
34✔
1432
                                std::string(id_encoded) + "/items?f=json" +
17✔
1433
                                extra_kvp + other_extra_kvp + extra_params}},
17✔
1434
                  {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
30✔
1435
                   {"type", OGCAPI_MIMETYPE_HTML},
1436
                   {"title", "Items for this collection as HTML"},
1437
                   {"href", api_root + "/collections/" +
34✔
1438
                                std::string(id_encoded) + "/items?f=html" +
17✔
1439
                                extra_kvp + other_extra_kvp + extra_params}}}}};
714✔
1440

1441
    if (offset + layer->resultcache->numresults < numberMatched) {
17✔
1442
      response["links"].push_back(
140✔
1443
          {{"rel", "next"},
1444
           {"type", format == OGCAPIFormat::JSON ? OGCAPI_MIMETYPE_GEOJSON
11✔
1445
                                                 : OGCAPI_MIMETYPE_HTML},
1446
           {"title", "next page"},
1447
           {"href",
1448
            api_root + "/collections/" + std::string(id_encoded) +
20✔
1449
                "/items?f=" + (format == OGCAPIFormat::JSON ? "json" : "html") +
20✔
1450
                "&limit=" + std::to_string(limit) +
30✔
1451
                "&offset=" + std::to_string(offset + limit) + other_extra_kvp +
20✔
1452
                extra_params}});
1453
    }
1454

1455
    if (offset > 0) {
17✔
1456
      response["links"].push_back(
14✔
1457
          {{"rel", "prev"},
1458
           {"type", format == OGCAPIFormat::JSON ? OGCAPI_MIMETYPE_GEOJSON
1✔
1459
                                                 : OGCAPI_MIMETYPE_HTML},
1460
           {"title", "previous page"},
1461
           {"href",
1462
            api_root + "/collections/" + std::string(id_encoded) +
2✔
1463
                "/items?f=" + (format == OGCAPIFormat::JSON ? "json" : "html") +
2✔
1464
                "&limit=" + std::to_string(limit) +
3✔
1465
                "&offset=" + std::to_string(MS_MAX(0, (offset - limit))) +
2✔
1466
                other_extra_kvp + extra_params}});
1✔
1467
    }
1468

1469
    msFree(id_encoded); // done
17✔
1470
  }
1471

1472
  // features (items)
1473
  {
1474
    shapeObj shape;
19✔
1475
    msInitShape(&shape);
19✔
1476

1477
    // we piggyback on GML configuration
1478
    gmlItemListObj *items = msGMLGetItems(layer, "AG");
19✔
1479
    gmlConstantListObj *constants = msGMLGetConstants(layer, "AG");
19✔
1480

1481
    if (!items || !constants) {
19✔
1482
      msGMLFreeItems(items);
×
1483
      msGMLFreeConstants(constants);
×
1484
      msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
1485
                          "Error fetching layer attribute metadata.");
1486
      return MS_SUCCESS;
×
1487
    }
1488

1489
    const int geometry_precision = getGeometryPrecision(map, layer);
19✔
1490

1491
    for (i = 0; i < layer->resultcache->numresults; i++) {
64✔
1492
      int status =
1493
          msLayerGetShape(layer, &shape, &(layer->resultcache->results[i]));
45✔
1494
      if (status != MS_SUCCESS) {
45✔
1495
        msGMLFreeItems(items);
×
1496
        msGMLFreeConstants(constants);
×
1497
        msOGCAPIOutputError(OGCAPI_SERVER_ERROR, "Error fetching feature.");
×
1498
        return MS_SUCCESS;
×
1499
      }
1500

1501
      if (reprObjs.reprojector) {
45✔
1502
        status = msProjectShapeEx(reprObjs.reprojector, &shape);
38✔
1503
        if (status != MS_SUCCESS) {
38✔
1504
          msGMLFreeItems(items);
×
1505
          msGMLFreeConstants(constants);
×
1506
          msFreeShape(&shape);
×
1507
          msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
1508
                              "Error reprojecting feature.");
1509
          return MS_SUCCESS;
×
1510
        }
1511
      }
1512

1513
      try {
1514
        json feature = getFeature(layer, &shape, items, constants,
1515
                                  geometry_precision, outputCrsAxisInverted);
45✔
1516
        if (featureId) {
45✔
1517
          response = std::move(feature);
2✔
1518
        } else {
1519
          response["features"].emplace_back(std::move(feature));
43✔
1520
        }
1521
      } catch (const std::runtime_error &e) {
×
1522
        msGMLFreeItems(items);
×
1523
        msGMLFreeConstants(constants);
×
1524
        msFreeShape(&shape);
×
1525
        msOGCAPIOutputError(OGCAPI_SERVER_ERROR,
×
1526
                            "Error getting feature. " + std::string(e.what()));
×
1527
        return MS_SUCCESS;
1528
      }
×
1529

1530
      msFreeShape(&shape); // next
45✔
1531
    }
1532

1533
    msGMLFreeItems(items); // clean up
19✔
1534
    msGMLFreeConstants(constants);
19✔
1535
  }
19✔
1536

1537
  // extend the response a bit for templating (HERE)
1538
  if (format == OGCAPIFormat::HTML) {
19✔
1539
    const char *title = getCollectionTitle(layer);
1540
    const char *id = layer->name;
4✔
1541
    response["collection"] = {{"id", id}, {"title", title ? title : ""}};
36✔
1542
  }
1543

1544
  if (featureId) {
19✔
1545
    const char *id = layer->name;
2✔
1546
    char *id_encoded = msEncodeUrl(id); // free after use
2✔
1547

1548
    response["links"] = {
2✔
1549
        {{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
2✔
1550
         {"type", OGCAPI_MIMETYPE_GEOJSON},
1551
         {"title", "This document as GeoJSON"},
1552
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1553
                      "/items/" + featureId + "?f=json" + extra_params}},
2✔
1554
        {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
4✔
1555
         {"type", OGCAPI_MIMETYPE_HTML},
1556
         {"title", "This document as HTML"},
1557
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1558
                      "/items/" + featureId + "?f=html" + extra_params}},
2✔
1559
        {{"rel", "collection"},
1560
         {"type", OGCAPI_MIMETYPE_JSON},
1561
         {"title", "This collection as JSON"},
1562
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1563
                      "?f=json" + extra_params}},
2✔
1564
        {{"rel", "collection"},
1565
         {"type", OGCAPI_MIMETYPE_HTML},
1566
         {"title", "This collection as HTML"},
1567
         {"href", api_root + "/collections/" + std::string(id_encoded) +
4✔
1568
                      "?f=html" + extra_params}}};
106✔
1569

1570
    msFree(id_encoded);
2✔
1571

1572
    outputResponse(
2✔
1573
        map, request,
1574
        format == OGCAPIFormat::JSON ? OGCAPIFormat::GeoJSON : format,
1575
        OGCAPI_TEMPLATE_HTML_COLLECTION_ITEM, response, extraHeaders);
1576
  } else {
1577
    outputResponse(
30✔
1578
        map, request,
1579
        format == OGCAPIFormat::JSON ? OGCAPIFormat::GeoJSON : format,
1580
        OGCAPI_TEMPLATE_HTML_COLLECTION_ITEMS, response, extraHeaders);
1581
  }
1582
  return MS_SUCCESS;
1583
}
1,204✔
1584

1585
static int processCollectionRequest(mapObj *map, cgiRequestObj *request,
6✔
1586
                                    const char *collectionId,
1587
                                    OGCAPIFormat format) {
1588
  json response;
1589
  int l;
1590

1591
  for (l = 0; l < map->numlayers; l++) {
8✔
1592
    if (strcmp(map->layers[l]->name, collectionId) == 0)
8✔
1593
      break; // match
1594
  }
1595

1596
  if (l == map->numlayers) { // invalid collectionId
6✔
1597
    msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1598
    return MS_SUCCESS;
×
1599
  }
1600

1601
  try {
1602
    response = getCollection(map, map->layers[l], format,
6✔
1603
                             msOGCAPIGetApiRootUrl(map, request));
12✔
1604
    if (response.is_null()) { // same as not found
6✔
1605
      msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1606
      return MS_SUCCESS;
×
1607
    }
1608
  } catch (const std::runtime_error &e) {
×
1609
    msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
×
1610
                        "Error getting collection. " + std::string(e.what()));
×
1611
    return MS_SUCCESS;
1612
  }
×
1613

1614
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_COLLECTION,
6✔
1615
                 response);
1616
  return MS_SUCCESS;
6✔
1617
}
1618

1619
static int processCollectionsRequest(mapObj *map, cgiRequestObj *request,
3✔
1620
                                     OGCAPIFormat format) {
1621
  json response;
1622
  int i;
1623

1624
  // define api root url
1625
  std::string api_root = msOGCAPIGetApiRootUrl(map, request);
3✔
1626
  const std::string extra_params = getExtraParameters(map, nullptr);
3✔
1627

1628
  // build response object
1629
  response = {{"links",
1630
               {{{"rel", format == OGCAPIFormat::JSON ? "self" : "alternate"},
4✔
1631
                 {"type", OGCAPI_MIMETYPE_JSON},
1632
                 {"title", "This document as JSON"},
1633
                 {"href", api_root + "/collections?f=json" + extra_params}},
3✔
1634
                {{"rel", format == OGCAPIFormat::HTML ? "self" : "alternate"},
5✔
1635
                 {"type", OGCAPI_MIMETYPE_HTML},
1636
                 {"title", "This document as HTML"},
1637
                 {"href", api_root + "/collections?f=html" + extra_params}}}},
3✔
1638
              {"collections", json::array()}};
102✔
1639

1640
  for (i = 0; i < map->numlayers; i++) {
10✔
1641
    try {
1642
      json collection = getCollection(map, map->layers[i], format, api_root);
7✔
1643
      if (!collection.is_null())
7✔
1644
        response["collections"].push_back(collection);
7✔
1645
    } catch (const std::runtime_error &e) {
×
1646
      msOGCAPIOutputError(OGCAPI_CONFIG_ERROR,
×
1647
                          "Error getting collection." + std::string(e.what()));
×
1648
      return MS_SUCCESS;
1649
    }
×
1650
  }
1651

1652
  outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_COLLECTIONS,
3✔
1653
                 response);
1654
  return MS_SUCCESS;
3✔
1655
}
129✔
1656

1657
static int processApiRequest(mapObj *map, cgiRequestObj *request,
1✔
1658
                             OGCAPIFormat format) {
1659
  // Strongly inspired from
1660
  // https://github.com/geopython/pygeoapi/blob/master/pygeoapi/openapi.py
1661

1662
  json response;
1663

1664
  response = {
1665
      {"openapi", "3.0.2"},
1666
      {"tags", json::array()},
1✔
1667
  };
7✔
1668

1669
  response["info"] = {
1✔
1670
      {"title", getTitle(map)},
1✔
1671
      {"version", getWebMetadata(map, "A", "version", "1.0.0")},
1✔
1672
  };
7✔
1673

1674
  for (const char *item : {"description", "termsOfService"}) {
3✔
1675
    const char *value = getWebMetadata(map, "AO", item, nullptr);
2✔
1676
    if (value) {
2✔
1677
      response["info"][item] = value;
4✔
1678
    }
1679
  }
1680

1681
  for (const auto &pair : {
3✔
1682
           std::make_pair("name", "contactperson"),
1683
           std::make_pair("url", "contacturl"),
1684
           std::make_pair("email", "contactelectronicmailaddress"),
1685
       }) {
4✔
1686
    const char *value = getWebMetadata(map, "AO", pair.second, nullptr);
3✔
1687
    if (value) {
3✔
1688
      response["info"]["contact"][pair.first] = value;
6✔
1689
    }
1690
  }
1691

1692
  for (const auto &pair : {
2✔
1693
           std::make_pair("name", "licensename"),
1694
           std::make_pair("url", "licenseurl"),
1695
       }) {
3✔
1696
    const char *value = getWebMetadata(map, "AO", pair.second, nullptr);
2✔
1697
    if (value) {
2✔
1698
      response["info"]["license"][pair.first] = value;
×
1699
    }
1700
  }
1701

1702
  {
1703
    const char *value = getWebMetadata(map, "AO", "keywords", nullptr);
1✔
1704
    if (value) {
1✔
1705
      response["info"]["x-keywords"] = value;
2✔
1706
    }
1707
  }
1708

1709
  json server;
1710
  server["url"] = msOGCAPIGetApiRootUrl(map, request);
3✔
1711

1712
  {
1713
    const char *value =
1714
        getWebMetadata(map, "AO", "server_description", nullptr);
1✔
1715
    if (value) {
1✔
1716
      server["description"] = value;
2✔
1717
    }
1718
  }
1719
  response["servers"].push_back(server);
1✔
1720

1721
  const std::string oapif_schema_base_url = msOWSGetSchemasLocation(map);
1✔
1722
  const std::string oapif_yaml_url = oapif_schema_base_url +
1723
                                     "/ogcapi/features/part1/1.0/openapi/"
1724
                                     "ogcapi-features-1.yaml";
1✔
1725
  const std::string oapif_part2_yaml_url = oapif_schema_base_url +
1726
                                           "/ogcapi/features/part2/1.0/openapi/"
1727
                                           "ogcapi-features-2.yaml";
1✔
1728

1729
  json paths;
1730

1731
  paths["/"]["get"] = {
1✔
1732
      {"summary", "Landing page"},
1733
      {"description", "Landing page"},
1734
      {"tags", {"server"}},
1735
      {"operationId", "getLandingPage"},
1736
      {"parameters",
1737
       {
1738
           {{"$ref", "#/components/parameters/f"}},
1739
       }},
1740
      {"responses",
1741
       {{"200",
1742
         {{"$ref", oapif_yaml_url + "#/components/responses/LandingPage"}}},
1✔
1743
        {"400",
1744
         {{"$ref",
1745
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1746
        {"500",
1747
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1748

1749
  paths["/api"]["get"] = {
1✔
1750
      {"summary", "API documentation"},
1751
      {"description", "API documentation"},
1752
      {"tags", {"server"}},
1753
      {"operationId", "getOpenapi"},
1754
      {"parameters",
1755
       {
1756
           {{"$ref", "#/components/parameters/f"}},
1757
       }},
1758
      {"responses",
1759
       {{"200", {{"$ref", "#/components/responses/200"}}},
1760
        {"400",
1761
         {{"$ref",
1762
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1763
        {"default", {{"$ref", "#/components/responses/default"}}}}}};
42✔
1764

1765
  paths["/conformance"]["get"] = {
1✔
1766
      {"summary", "API conformance definition"},
1767
      {"description", "API conformance definition"},
1768
      {"tags", {"server"}},
1769
      {"operationId", "getConformanceDeclaration"},
1770
      {"parameters",
1771
       {
1772
           {{"$ref", "#/components/parameters/f"}},
1773
       }},
1774
      {"responses",
1775
       {{"200",
1776
         {{"$ref",
1777
           oapif_yaml_url + "#/components/responses/ConformanceDeclaration"}}},
1✔
1778
        {"400",
1779
         {{"$ref",
1780
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1781
        {"500",
1782
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1783

1784
  paths["/collections"]["get"] = {
1✔
1785
      {"summary", "Collections"},
1786
      {"description", "Collections"},
1787
      {"tags", {"server"}},
1788
      {"operationId", "getCollections"},
1789
      {"parameters",
1790
       {
1791
           {{"$ref", "#/components/parameters/f"}},
1792
       }},
1793
      {"responses",
1794
       {{"200",
1795
         {{"$ref", oapif_yaml_url + "#/components/responses/Collections"}}},
1✔
1796
        {"400",
1797
         {{"$ref",
1798
           oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
1✔
1799
        {"500",
1800
         {{"$ref", oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
43✔
1801

1802
  for (int i = 0; i < map->numlayers; i++) {
4✔
1803
    layerObj *layer = map->layers[i];
3✔
1804
    if (!includeLayer(map, layer)) {
3✔
1805
      continue;
×
1806
    }
1807

1808
    json collection_get = {
1809
        {"summary",
1810
         std::string("Get ") + getCollectionTitle(layer) + " metadata"},
3✔
1811
        {"description", getCollectionDescription(layer)},
3✔
1812
        {"tags", {layer->name}},
3✔
1813
        {"operationId", "describe" + std::string(layer->name) + "Collection"},
3✔
1814
        {"parameters",
1815
         {
1816
             {{"$ref", "#/components/parameters/f"}},
1817
         }},
1818
        {"responses",
1819
         {{"200",
1820
           {{"$ref", oapif_yaml_url + "#/components/responses/Collection"}}},
3✔
1821
          {"400",
1822
           {{"$ref",
1823
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1824
          {"500",
1825
           {{"$ref",
1826
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
129✔
1827

1828
    std::string collectionNamePath("/collections/");
×
1829
    collectionNamePath += layer->name;
3✔
1830
    paths[collectionNamePath]["get"] = std::move(collection_get);
3✔
1831

1832
    // check metadata, layer then map
1833
    const char *max_limit_str =
1834
        msOWSLookupMetadata(&(layer->metadata), "A", "max_limit");
3✔
1835
    if (max_limit_str == nullptr)
3✔
1836
      max_limit_str =
1837
          msOWSLookupMetadata(&(map->web.metadata), "A", "max_limit");
3✔
1838
    const int max_limit =
1839
        max_limit_str ? atoi(max_limit_str) : OGCAPI_MAX_LIMIT;
3✔
1840
    const int default_limit = getDefaultLimit(map, layer);
3✔
1841

1842
    json items_get = {
1843
        {"summary", std::string("Get ") + getCollectionTitle(layer) + " items"},
3✔
1844
        {"description", getCollectionDescription(layer)},
3✔
1845
        {"tags", {layer->name}},
1846
        {"operationId", "get" + std::string(layer->name) + "Features"},
3✔
1847
        {"parameters",
1848
         {
1849
             {{"$ref", "#/components/parameters/f"}},
1850
             {{"$ref", oapif_yaml_url + "#/components/parameters/bbox"}},
3✔
1851
             {{"$ref", oapif_yaml_url + "#/components/parameters/datetime"}},
3✔
1852
             {{"$ref",
1853
               oapif_part2_yaml_url + "#/components/parameters/bbox-crs"}},
3✔
1854
             {{"$ref", oapif_part2_yaml_url + "#/components/parameters/crs"}},
3✔
1855
             {{"$ref", "#/components/parameters/offset"}},
1856
             {{"$ref", "#/components/parameters/vendorSpecificParameters"}},
1857
         }},
1858
        {"responses",
1859
         {{"200",
1860
           {{"$ref", oapif_yaml_url + "#/components/responses/Features"}}},
3✔
1861
          {"400",
1862
           {{"$ref",
1863
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1864
          {"500",
1865
           {{"$ref",
1866
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
201✔
1867

1868
    json param_limit = {
1869
        {"name", "limit"},
1870
        {"in", "query"},
1871
        {"description", "The optional limit parameter limits the number of "
1872
                        "items that are presented in the response document."},
1873
        {"required", false},
1874
        {"schema",
1875
         {
1876
             {"type", "integer"},
1877
             {"minimum", 1},
1878
             {"maximum", max_limit},
1879
             {"default", default_limit},
1880
         }},
1881
        {"style", "form"},
1882
        {"explode", false},
1883
    };
102✔
1884
    items_get["parameters"].emplace_back(param_limit);
3✔
1885

1886
    std::string itemsPath(collectionNamePath + "/items");
3✔
1887
    paths[itemsPath]["get"] = std::move(items_get);
6✔
1888

1889
    json feature_id_get = {
1890
        {"summary",
1891
         std::string("Get ") + getCollectionTitle(layer) + " item by id"},
3✔
1892
        {"description", getCollectionDescription(layer)},
3✔
1893
        {"tags", {layer->name}},
1894
        {"operationId", "get" + std::string(layer->name) + "Feature"},
3✔
1895
        {"parameters",
1896
         {
1897
             {{"$ref", "#/components/parameters/f"}},
1898
             {{"$ref", oapif_yaml_url + "#/components/parameters/featureId"}},
3✔
1899
         }},
1900
        {"responses",
1901
         {{"200",
1902
           {{"$ref", oapif_yaml_url + "#/components/responses/Feature"}}},
3✔
1903
          {"400",
1904
           {{"$ref",
1905
             oapif_yaml_url + "#/components/responses/InvalidParameter"}}},
3✔
1906
          {"404",
1907
           {{"$ref", oapif_yaml_url + "#/components/responses/NotFound"}}},
3✔
1908
          {"500",
1909
           {{"$ref",
1910
             oapif_yaml_url + "#/components/responses/ServerError"}}}}}};
159✔
1911
    std::string itemsFeatureIdPath(collectionNamePath + "/items/{featureId}");
3✔
1912
    paths[itemsFeatureIdPath]["get"] = std::move(feature_id_get);
6✔
1913
  }
1914

1915
  response["paths"] = std::move(paths);
2✔
1916

1917
  json components;
1918
  components["responses"]["200"] = {{"description", "successful operation"}};
5✔
1919
  components["responses"]["default"] = {
1✔
1920
      {"description", "unexpected error"},
1921
      {"content",
1922
       {{"application/json",
1923
         {{"schema",
1924
           {{"$ref", "https://schemas.opengis.net/ogcapi/common/part1/1.0/"
1925
                     "openapi/schemas/exception.yaml"}}}}}}}};
16✔
1926

1927
  json parameters;
1928
  parameters["f"] = {
1✔
1929
      {"name", "f"},
1930
      {"in", "query"},
1931
      {"description", "The optional f parameter indicates the output format "
1932
                      "which the server shall provide as part of the response "
1933
                      "document.  The default format is GeoJSON."},
1934
      {"required", false},
1935
      {"schema",
1936
       {{"type", "string"}, {"enum", {"json", "html"}}, {"default", "json"}}},
1937
      {"style", "form"},
1938
      {"explode", false},
1939
  };
33✔
1940

1941
  parameters["offset"] = {
1✔
1942
      {"name", "offset"},
1943
      {"in", "query"},
1944
      {"description",
1945
       "The optional offset parameter indicates the index within the result "
1946
       "set from which the server shall begin presenting results in the "
1947
       "response document.  The first element has an index of 0 (default)."},
1948
      {"required", false},
1949
      {"schema",
1950
       {
1951
           {"type", "integer"},
1952
           {"minimum", 0},
1953
           {"default", 0},
1954
       }},
1955
      {"style", "form"},
1956
      {"explode", false},
1957
  };
31✔
1958

1959
  parameters["vendorSpecificParameters"] = {
1✔
1960
      {"name", "vendorSpecificParameters"},
1961
      {"in", "query"},
1962
      {"description",
1963
       "Additional \"free-form\" parameters that are not explicitly defined"},
1964
      {"schema",
1965
       {
1966
           {"type", "object"},
1967
           {"additionalProperties", true},
1968
       }},
1969
      {"style", "form"},
1970
  };
22✔
1971

1972
  components["parameters"] = std::move(parameters);
2✔
1973

1974
  response["components"] = std::move(components);
2✔
1975

1976
  // TODO: "tags" array ?
1977

1978
  outputResponse(map, request,
3✔
1979
                 format == OGCAPIFormat::JSON ? OGCAPIFormat::OpenAPI_V3
1980
                                              : format,
1981
                 OGCAPI_TEMPLATE_HTML_OPENAPI, response);
1982
  return MS_SUCCESS;
1✔
1983
}
1,210✔
1984

1985
#endif
1986

1987
OGCAPIFormat msOGCAPIGetOutputFormat(cgiRequestObj *request) {
51✔
1988
  OGCAPIFormat format; // all endpoints need a format
1989
  const char *p = getRequestParameter(request, "f");
51✔
1990

1991
  // if f= query parameter is not specified, use HTTP Accept header if available
1992
  if (p == nullptr) {
51✔
1993
    const char *accept = getenv("HTTP_ACCEPT");
2✔
1994
    if (accept) {
2✔
1995
      if (strcmp(accept, "*/*") == 0)
1✔
1996
        p = OGCAPI_MIMETYPE_JSON;
1997
      else
1998
        p = accept;
1999
    }
2000
  }
2001

2002
  if (p &&
50✔
2003
      (strcmp(p, "json") == 0 || strstr(p, OGCAPI_MIMETYPE_JSON) != nullptr ||
50✔
2004
       strstr(p, OGCAPI_MIMETYPE_GEOJSON) != nullptr ||
10✔
2005
       strstr(p, OGCAPI_MIMETYPE_OPENAPI_V3) != nullptr)) {
2006
    format = OGCAPIFormat::JSON;
2007
  } else if (p && (strcmp(p, "html") == 0 ||
10✔
2008
                   strstr(p, OGCAPI_MIMETYPE_HTML) != nullptr)) {
2009
    format = OGCAPIFormat::HTML;
2010
  } else if (p) {
2011
    std::string errorMsg("Unsupported format requested: ");
×
2012
    errorMsg += p;
2013
    msOGCAPIOutputError(OGCAPI_PARAM_ERROR, errorMsg.c_str());
×
2014
    format = OGCAPIFormat::Invalid;
2015
  } else {
2016
    format = OGCAPIFormat::HTML; // default for now
2017
  }
2018

2019
  return format;
51✔
2020
}
2021

2022
int msOGCAPIDispatchRequest(mapObj *map, cgiRequestObj *request) {
41✔
2023
#ifdef USE_OGCAPI_SVR
2024

2025
  // make sure ogcapi requests are enabled for this map
2026
  int status = msOWSRequestIsEnabled(map, NULL, "AO", "OGCAPI", MS_FALSE);
41✔
2027
  if (status != MS_TRUE) {
41✔
2028
    msSetError(MS_OGCAPIERR, "OGC API requests are not enabled.",
×
2029
               "msCGIDispatchAPIRequest()");
2030
    return MS_FAILURE; // let normal error handling take over
×
2031
  }
2032

2033
  for (int i = 0; i < request->NumParams; i++) {
122✔
2034
    for (int j = i + 1; j < request->NumParams; j++) {
151✔
2035
      if (strcmp(request->ParamNames[i], request->ParamNames[j]) == 0) {
70✔
2036
        std::string errorMsg("Query parameter ");
1✔
2037
        errorMsg += request->ParamNames[i];
1✔
2038
        errorMsg += " is repeated";
2039
        msOGCAPIOutputError(OGCAPI_PARAM_ERROR, errorMsg.c_str());
2✔
2040
        return MS_SUCCESS;
2041
      }
2042
    }
2043
  }
2044

2045
  const OGCAPIFormat format = msOGCAPIGetOutputFormat(request);
40✔
2046

2047
  if (format == OGCAPIFormat::Invalid) {
40✔
2048
    return MS_SUCCESS; // avoid any downstream MapServer processing
2049
  }
2050

2051
  if (request->api_path_length == 2) {
40✔
2052

2053
    return processLandingRequest(map, request, format);
5✔
2054

2055
  } else if (request->api_path_length == 3) {
2056

2057
    if (strcmp(request->api_path[2], "conformance") == 0) {
5✔
2058
      return processConformanceRequest(map, request, format);
1✔
2059
    } else if (strcmp(request->api_path[2], "conformance.html") == 0) {
4✔
2060
      return processConformanceRequest(map, request, OGCAPIFormat::HTML);
×
2061
    } else if (strcmp(request->api_path[2], "collections") == 0) {
4✔
2062
      return processCollectionsRequest(map, request, format);
3✔
2063
    } else if (strcmp(request->api_path[2], "collections.html") == 0) {
1✔
2064
      return processCollectionsRequest(map, request, OGCAPIFormat::HTML);
×
2065
    } else if (strcmp(request->api_path[2], "api") == 0) {
1✔
2066
      return processApiRequest(map, request, format);
1✔
2067
    }
2068

2069
  } else if (request->api_path_length == 4) {
2070

2071
    if (strcmp(request->api_path[2], "collections") ==
6✔
2072
        0) { // next argument (3) is collectionId
2073
      return processCollectionRequest(map, request, request->api_path[3],
6✔
2074
                                      format);
6✔
2075
    }
2076

2077
  } else if (request->api_path_length == 5) {
2078

2079
    if (strcmp(request->api_path[2], "collections") == 0 &&
21✔
2080
        strcmp(request->api_path[4], "items") ==
21✔
2081
            0) { // middle argument (3) is the collectionId
2082
      return processCollectionItemsRequest(map, request, request->api_path[3],
21✔
2083
                                           NULL, format);
21✔
2084
    }
2085

2086
  } else if (request->api_path_length == 6) {
2087

2088
    if (strcmp(request->api_path[2], "collections") == 0 &&
3✔
2089
        strcmp(request->api_path[4], "items") ==
3✔
2090
            0) { // middle argument (3) is the collectionId, last argument (5)
2091
                 // is featureId
2092
      return processCollectionItemsRequest(map, request, request->api_path[3],
3✔
2093
                                           request->api_path[5], format);
3✔
2094
    }
2095
  }
2096

2097
  msOGCAPIOutputError(OGCAPI_NOT_FOUND_ERROR, "Invalid API path.");
×
2098
  return MS_SUCCESS; // avoid any downstream MapServer processing
×
2099
#else
2100
  msSetError(MS_OGCAPIERR, "OGC API server support is not enabled.",
2101
             "msOGCAPIDispatchRequest()");
2102
  return MS_FAILURE;
2103
#endif
2104
}
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