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

geographika / mapserver / 17709373190

14 Sep 2025 09:32AM UTC coverage: 41.466% (+0.09%) from 41.375%
17709373190

push

github

geographika
Add index templates

62086 of 149729 relevant lines covered (41.47%)

25036.08 hits per line

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

78.05
/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
static std::string getEnvVar(const char *envVar) {
4✔
404
  const char *value = getenv(envVar);
4✔
405
  return value ? std::string(value) : std::string();
4✔
406
}
407

408
/*
409
** Returns the API root URL from oga_onlineresource or builds a value if not
410
*set.
411
*/
412
std::string getApiRootUrl(mapObj *map, const char *namespaces = "A") {
32✔
413
  const char *root;
414

415
  if ((root = msOWSLookupMetadata(&(map->web.metadata), namespaces,
32✔
416
                                  "onlineresource")) != NULL) {
417
    return std::string(root);
31✔
418
  } else {
419
    std::string serverName = getEnvVar("SERVER_NAME");
1✔
420
    std::string serverPort = getEnvVar("SERVER_PORT");
1✔
421
    std::string scriptName = getEnvVar("SCRIPT_NAME");
1✔
422
    std::string pathInfo = getEnvVar("PATH_INFO");
1✔
423

424
    return "http://" + serverName + ":" + serverPort + scriptName + pathInfo;
2✔
425
  }
426
}
427

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

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

436
  // initialize
437
  j = {{constant->name, constant->value}};
×
438

439
  return j;
×
440
}
×
441

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

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

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

456
  // initialize
457
  j = {{key, value}};
432✔
458

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

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

497
  return j;
498
}
736✔
499

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

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

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

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

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

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

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

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

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

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

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

648
  return geometry;
649
}
650

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

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

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

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

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

683
  // properties - build from items and constants, no group support for now
684

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

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

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

715
  return feature;
23✔
716
}
184✔
717

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

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

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

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

735
  return link;
11✔
736
}
110✔
737

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

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

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

772
static json getCollection(mapObj *map, layerObj *layer, OGCAPIFormat format) {
5✔
773
  json collection; // empty (null)
774
  rectObj bbox;
775

776
  if (!map || !layer)
5✔
777
    return collection;
778

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

782
  // initialize some things
783
  std::string api_root = getApiRootUrl(map);
5✔
784

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

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

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

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

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

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

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

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

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

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

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

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

884
  return collection;
885
}
525✔
886

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

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

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

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

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

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

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

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

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

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

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

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

982
    json j;
983

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1136
  int limit;
1137
  rectObj bbox;
1138

1139
  int numberMatched = 0;
1140

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

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

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

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

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

1168
  const char *crs = getRequestParameter(request, "crs");
22✔
1169

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

1198
  struct ReprojectionObjects {
1199
    reprojectionObj *reprojector = NULL;
1200
    projectionObj proj;
1201

1202
    ReprojectionObjects() { msInitProjection(&proj); }
20✔
1203

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

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

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

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

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

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

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

1266
    // TODO: does featureIdItem exist in the data?
1267

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

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

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

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

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

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

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

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

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

1336
    numberMatched = layer->resultcache->numresults;
14✔
1337

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

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

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

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

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

1367
  // build response object
1368
  if (!featureId) {
16✔
1369
    std::string api_root = getApiRootUrl(map);
14✔
1370
    const char *id = layer->name;
14✔
1371
    char *id_encoded = msEncodeUrl(id); // free after use
14✔
1372

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1504
  if (featureId) {
16✔
1505
    std::string api_root = getApiRootUrl(map);
2✔
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 = getCollection(map, map->layers[l], format);
4✔
1564
    if (response.is_null()) { // same as not found
2✔
1565
      outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
×
1566
      return MS_SUCCESS;
×
1567
    }
1568
  } catch (const std::runtime_error &e) {
×
1569
    outputError(OGCAPI_CONFIG_ERROR,
×
1570
                "Error getting collection. " + std::string(e.what()));
×
1571
    return MS_SUCCESS;
1572
  }
×
1573

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

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

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

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

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

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

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

1621
  json response;
1622

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

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

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

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

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

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

1668
  json server;
1669
  server["url"] = getApiRootUrl(map);
3✔
1670
  {
1671
    const char *value =
1672
        getWebMetadata(map, "AO", "server_description", nullptr);
1✔
1673
    if (value) {
1✔
1674
      server["description"] = value;
2✔
1675
    }
1676
  }
1677
  response["servers"].push_back(server);
1✔
1678

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

1687
  json paths;
1688

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

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

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

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

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

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

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

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

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

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

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

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

1872
  response["paths"] = std::move(paths);
2✔
1873

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

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

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

1916
  components["parameters"] = std::move(parameters);
2✔
1917

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

1920
  // TODO: "tags" array ?
1921

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

1929
#endif
1930

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

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

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

1963
  return format;
31✔
1964
}
1965

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

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

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

1989
  OGCAPIFormat format;
1990
  format = msGetOutputFormat(request);
30✔
1991

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

1996
  if (request->api_path_length == 2) {
30✔
1997

1998
    return processLandingRequest(map, request, format);
3✔
1999

2000
  } else if (request->api_path_length == 3) {
2001

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

2014
  } else if (request->api_path_length == 4) {
2015

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

2022
  } else if (request->api_path_length == 5) {
2023

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

2031
  } else if (request->api_path_length == 6) {
2032

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

2042
  outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid API path.");
×
2043
  return MS_SUCCESS; // avoid any downstream MapServer processing
×
2044
#else
2045
  msSetError(MS_OGCAPIERR, "OGC API server support is not enabled.",
2046
             "msOGCAPIDispatchRequest()");
2047
  return MS_FAILURE;
2048
#endif
2049
}
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