-
-
Notifications
You must be signed in to change notification settings - Fork 360
/
mapogcapi.cpp
1700 lines (1465 loc) · 55.8 KB
/
mapogcapi.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* $id$
*
* Project: MapServer
* Purpose: OGCAPI Implementation
* Author: Steve Lime and the MapServer team.
*
**********************************************************************
* Copyright (c) 1996-2005 Regents of the University of Minnesota.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies of this Software or works derived from this Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
****************************************************************************/
#include "mapserver.h"
#include "mapogcapi.h"
#include "mapows.h"
#include "mapgml.h"
#include "maptime.h"
#include "third-party/include_nlohmann_json.hpp"
#include "third-party/include_pantor_inja.hpp"
#include <string>
#include <iostream>
using namespace inja;
using json = nlohmann::json;
#define OGCAPI_DEFAULT_TITLE "MapServer OGC API"
/*
** HTML Templates
*/
#define OGCAPI_TEMPLATE_HTML_LANDING "landing.html"
#define OGCAPI_TEMPLATE_HTML_CONFORMANCE "conformance.html"
#define OGCAPI_TEMPLATE_HTML_COLLECTION "collection.html"
#define OGCAPI_TEMPLATE_HTML_COLLECTIONS "collections.html"
#define OGCAPI_TEMPLATE_HTML_COLLECTION_ITEMS "collection-items.html"
#define OGCAPI_TEMPLATE_HTML_COLLECTION_ITEM "collection-item.html"
#define OGCAPI_TEMPLATE_HTML_OPENAPI "openapi.html"
enum class OGCAPIFormat
{
JSON,
GeoJSON,
OpenAPI_V3,
HTML
};
#define OGCAPI_MIMETYPE_JSON "application/json"
#define OGCAPI_MIMETYPE_GEOJSON "application/geo+json"
#define OGCAPI_MIMETYPE_OPENAPI_V3 "application/vnd.oai.openapi+json;version=3.0"
#define OGCAPI_MIMETYPE_HTML "text/html"
#define OGCAPI_DEFAULT_LIMIT 10 // by specification
#define OGCAPI_MAX_LIMIT 10000
#define OGCAPI_DEFAULT_GEOMETRY_PRECISION 6
#ifdef USE_OGCAPI_SVR
#define OGCAPI_SERVER_ERROR 0 // error codes
#define OGCAPI_CONFIG_ERROR 1
#define OGCAPI_PARAM_ERROR 2
#define OGCAPI_NOT_FOUND_ERROR 3
#define OGCAPI_NUM_ERROR_CODES 4
/*
** Returns a JSON object using and a description.
*/
static void outputError(int code, const std::string& description)
{
if(code < 0 || code >= OGCAPI_NUM_ERROR_CODES) code = 0;
json error_codes = {
{ {"text", "ServerError"}, {"status", "500"} },
{ {"text", "ConfigError"}, {"status", "500"} },
{ {"text", "InvalidParamterValue"}, {"status", "400"} },
{ {"text", "NotFound"}, {"status", "404"} }
};
json j = {
{ "code", error_codes[code]["text"] },
{ "description", description }
};
std::string status = error_codes[code]["status"];
msIO_setHeader("Content-Type", "%s", OGCAPI_MIMETYPE_JSON);
msIO_setHeader("Status", "%s", status.c_str());
msIO_sendHeaders();
msIO_printf("%s\n", j.dump().c_str());
}
static int includeLayer(mapObj *map, layerObj *layer) {
if(!msOWSRequestIsEnabled(map, layer, "AO", "OGCAPI", MS_FALSE) ||
!msWFSIsLayerSupported(layer) ||
!msIsLayerQueryable(layer)) {
return MS_FALSE;
} else {
return MS_TRUE;
}
}
/*
** Get stuff...
*/
/*
** Returns the value associated with an item from the request's query string and NULL if the item was not found.
*/
static const char *getRequestParameter(cgiRequestObj *request, const char *item)
{
int i;
for(i=0; i<request->NumParams; i++) {
if(strcmp(item, request->ParamNames[i]) == 0)
return request->ParamValues[i];
}
return NULL;
}
static int getMaxLimit(mapObj *map, layerObj *layer)
{
int max_limit = OGCAPI_MAX_LIMIT;
const char *value;
// check metadata, layer then map
value = msOWSLookupMetadata(&(layer->metadata), "A", "max_limit");
if(value == NULL) value = msOWSLookupMetadata(&(map->web.metadata), "A", "max_limit");
if(value != NULL) {
int status = msStringToInt(value, &max_limit, 10);
if(status != MS_SUCCESS) max_limit = OGCAPI_MAX_LIMIT; // conversion failed
}
return max_limit;
}
static int getDefaultLimit(mapObj *map, layerObj *layer)
{
int default_limit = OGCAPI_DEFAULT_LIMIT;
// check metadata, layer then map
const char* value = msOWSLookupMetadata(&(layer->metadata), "A", "default_limit");
if(value == NULL) value = msOWSLookupMetadata(&(map->web.metadata), "A", "default_limit");
if(value != NULL) {
int status = msStringToInt(value, &default_limit, 10);
if(status != MS_SUCCESS) default_limit = OGCAPI_DEFAULT_LIMIT; // conversion failed
}
return default_limit;
}
/*
** Returns the limit as an int - between 1 and getMaxLimit(). We always return a valid value...
*/
static int getLimit(mapObj *map, cgiRequestObj *request, layerObj *layer, int *limit)
{
int status;
const char *p;
int max_limit;
max_limit = getMaxLimit(map, layer);
p = getRequestParameter(request, "limit");
if(!p || (p && strlen(p) == 0)) { // missing or empty
*limit = MS_MIN(getDefaultLimit(map, layer), max_limit); // max could be smaller than the default
} else {
status = msStringToInt(p, limit, 10);
if(status != MS_SUCCESS)
return MS_FAILURE;
if(*limit <= 0) {
*limit = MS_MIN(getDefaultLimit(map, layer), max_limit); // max could be smaller than the default
} else {
*limit = MS_MIN(*limit, max_limit);
}
}
return MS_SUCCESS;
}
/*
** Returns the bbox in SRS of the map.
*/
static bool getBbox(mapObj *map, cgiRequestObj *request, rectObj *bbox)
{
int status;
const char *p;
p = getRequestParameter(request, "bbox");
if(!p || (p && strlen(p) == 0)) { // missing or empty - assign map->extent (no projection necessary)
bbox->minx = map->extent.minx;
bbox->miny = map->extent.miny;
bbox->maxx = map->extent.maxx;
bbox->maxy = map->extent.maxy;
} else {
const auto tokens = msStringSplit(p, ',');
if(tokens.size() != 4) {
return false;
}
double values[4];
for(int i=0; i<4; i++) {
status = msStringToDouble(tokens[i].c_str(), &values[i]);
if(status != MS_SUCCESS) {
return false;
}
}
bbox->minx = values[0]; // assign
bbox->miny = values[1];
bbox->maxx = values[2];
bbox->maxy = values[3];
// validate bbox is well-formed (degenerate is ok)
if(MS_VALID_SEARCH_EXTENT(*bbox) != MS_TRUE) return false;
// at the moment we are assuming the bbox is given in lat/lon
status = msProjectRect(&map->latlon, &map->projection, bbox);
if(status != MS_SUCCESS) return false;
}
return true;
}
/*
** Returns the template directory location or NULL if it isn't set.
*/
static const char *getTemplateDirectory(mapObj *map, const char *key, const char *envvar)
{
const char *directory;
// TODO: if directory is provided then perhaps we need to check for a trailing slash
if((directory = msOWSLookupMetadata(&(map->web.metadata), "A", key)) != NULL)
return directory;
else if((directory = getenv(envvar)) != NULL)
return directory;
else
return NULL;
}
/*
** Returns the service title from oga_{key} and/or ows_{key} or a default value if not set.
*/
static const char *getWebMetadata(mapObj *map, const char* domain, const char* key, const char* defaultVal)
{
const char *value;
if((value = msOWSLookupMetadata(&(map->web.metadata), domain, key)) != NULL)
return value;
else
return defaultVal;
}
/*
** Returns the service title from oga|ows_title or a default value if not set.
*/
static const char *getTitle(mapObj *map)
{
return getWebMetadata(map, "OA", "title", OGCAPI_DEFAULT_TITLE);
}
/*
** Returns the API root URL from oga_onlineresource or builds a value if not set.
*/
static std::string getApiRootUrl(mapObj *map)
{
const char *root;
if((root = msOWSLookupMetadata(&(map->web.metadata), "A", "onlineresource")) != NULL)
return std::string(root);
else
return "http://" + std::string(getenv("SERVER_NAME")) + ":" + std::string(getenv("SERVER_PORT")) + std::string(getenv("SCRIPT_NAME")) + std::string(getenv("PATH_INFO"));
}
static json getFeatureConstant(const gmlConstantObj *constant)
{
json j; // empty (null)
if(!constant) throw std::runtime_error("Null constant metadata.");
if(!constant->value) return j;
// initialize
j = { { constant->name, constant->value } };
return j;
}
static json getFeatureItem(const gmlItemObj *item, const char *value)
{
json j; // empty (null)
const char *key;
if(!item) throw std::runtime_error("Null item metadata.");
if(!item->visible) return j;
if(item->alias)
key = item->alias;
else
key = item->name;
// initialize
j = { { key, value } };
if( item->type && (EQUAL(item->type, "Date") ||
EQUAL(item->type, "DateTime") ||
EQUAL(item->type, "Time")) ) {
struct tm tm;
if( msParseTime(value, &tm) == MS_TRUE ) {
char tmpValue[64];
if( EQUAL(item->type, "Date") )
snprintf(tmpValue, sizeof(tmpValue),
"%04d-%02d-%02d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
else if( EQUAL(item->type, "Time") )
snprintf(tmpValue, sizeof(tmpValue),
"%02d:%02d:%02dZ",
tm.tm_hour, tm.tm_min, tm.tm_sec);
else
snprintf(tmpValue, sizeof(tmpValue),
"%04d-%02d-%02dT%02d:%02d:%02dZ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
j = { { key, tmpValue } };
}
}
else if( item->type && (EQUAL(item->type, "Integer") ||
EQUAL(item->type, "Long")) )
{
try
{
j = { { key, std::stoll(value) } };
}
catch( const std::exception& )
{
}
}
else if( item->type && EQUAL(item->type, "Real"))
{
try
{
j = { { key, std::stod(value) } };
}
catch( const std::exception& )
{
}
}
else if( item->type && EQUAL(item->type, "Boolean"))
{
if( EQUAL(value,"0") || EQUAL(value,"false") )
{
j = { { key, false } };
}
else
{
j = { { key, true } };
}
}
return j;
}
static double round_down(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::floor(value * multiplier) / multiplier;
}
// https://stackoverflow.com/questions/25925290/c-round-a-double-up-to-2-decimal-places
static double round_up(double value, int decimal_places) {
const double multiplier = std::pow(10.0, decimal_places);
return std::ceil(value * multiplier) / multiplier;
}
static json getFeatureGeometry(shapeObj *shape, int precision)
{
json geometry; // empty (null)
int *outerList=NULL, numOuterRings=0;
if(!shape) throw std::runtime_error("Null shape.");
switch(shape->type) {
case(MS_SHAPE_POINT):
if(shape->numlines == 0 || shape->line[0].numpoints == 0) // not enough info for a point
return geometry;
if(shape->line[0].numpoints == 1) {
geometry["type"] = "Point";
geometry["coordinates"] = { round_up(shape->line[0].point[0].x, precision), round_up(shape->line[0].point[0].y, precision) };
} else {
geometry["type"] = "MultiPoint";
geometry["coordinates"] = json::array();
for(int j=0; j<shape->line[0].numpoints; j++) {
geometry["coordinates"].push_back( { round_up(shape->line[0].point[j].x, precision), round_up(shape->line[0].point[j].y, precision) } );
}
}
break;
case(MS_SHAPE_LINE):
if(shape->numlines == 0 || shape->line[0].numpoints < 2) // not enough info for a line
return geometry;
if(shape->numlines == 1) {
geometry["type"] = "LineString";
geometry["coordinates"] = json::array();
for(int j=0; j<shape->line[0].numpoints; j++) {
geometry["coordinates"].push_back( { round_up(shape->line[0].point[j].x, precision), round_up(shape->line[0].point[j].y, precision) } );
}
} else {
geometry["type"] = "MultiLineString";
geometry["coordinates"] = json::array();
for(int i=0; i<shape->numlines; i++) {
json part = json::array();
for(int j=0; j<shape->line[i].numpoints; j++) {
part.push_back( { round_up(shape->line[i].point[j].x, precision), round_up(shape->line[i].point[j].y, precision) } );
}
geometry["coordinates"].push_back(part);
}
}
break;
case(MS_SHAPE_POLYGON):
if(shape->numlines == 0 || shape->line[0].numpoints < 4) // not enough info for a polygon (first=last)
return geometry;
outerList = msGetOuterList(shape);
if(outerList == NULL) throw std::runtime_error("Unable to allocate list of outer rings.");
for(int k=0; k<shape->numlines; k++) {
if(outerList[k] == MS_TRUE)
numOuterRings++;
}
if(numOuterRings == 1) {
geometry["type"] = "Polygon";
geometry["coordinates"] = json::array();
for(int i=0; i<shape->numlines; i++) {
json part = json::array();
for(int j=0; j<shape->line[i].numpoints; j++) {
part.push_back( { round_up(shape->line[i].point[j].x, precision), round_up(shape->line[i].point[j].y, precision) } );
}
geometry["coordinates"].push_back(part);
}
} else {
geometry["type"] = "MultiPolygon";
geometry["coordinates"] = json::array();
for(int k=0; k<shape->numlines; k++) {
if(outerList[k] == MS_TRUE) { // outer ring: generate polygon and add to coordinates
int *innerList = msGetInnerList(shape, k, outerList);
if(innerList == NULL) {
msFree(outerList);
throw std::runtime_error("Unable to allocate list of inner rings.");
}
json polygon = json::array();
for(int i=0; i<shape->numlines; i++) {
if(i == k || outerList[i] == MS_TRUE) { // add outer ring (k) and any inner rings
json part = json::array();
for(int j=0; j<shape->line[i].numpoints; j++) {
part.push_back( { round_up(shape->line[i].point[j].x, precision), round_up(shape->line[i].point[j].y, precision) } );
}
polygon.push_back(part);
}
}
msFree(innerList);
geometry["coordinates"].push_back(polygon);
}
}
}
msFree(outerList);
break;
default:
throw std::runtime_error("Invalid shape type.");
break;
}
return geometry;
}
/*
** Return a GeoJSON representation of a shape.
*/
static json getFeature(layerObj *layer, shapeObj *shape, gmlItemListObj *items, gmlConstantListObj *constants, int geometry_precision)
{
int i;
json feature; // empty (null)
if(!layer || !shape) throw std::runtime_error("Null arguments.");
// initialize
feature = {
{ "type", "Feature" },
{ "properties", json::object() }
};
// id
const char *featureIdItem = msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
if(featureIdItem == NULL) throw std::runtime_error("Missing required featureid metadata."); // should have been trapped earlier
for(i=0; i<items->numitems; i++) {
if(strcasecmp(featureIdItem, items->items[i].name) == 0) {
feature["id"] = shape->values[i];
break;
}
}
if(i == items->numitems) throw std::runtime_error("Feature id not found.");
// properties - build from items and constants, no group support for now
for(int i=0; i<items->numitems; i++) {
try {
json item = getFeatureItem(&(items->items[i]), shape->values[i]);
if(!item.is_null()) feature["properties"].insert(item.begin(), item.end());
} catch (const std::runtime_error) {
throw std::runtime_error("Error fetching item.");
}
}
for(int i=0; i<constants->numconstants; i++) {
try {
json constant = getFeatureConstant(&(constants->constants[i]));
if(!constant.is_null()) feature["properties"].insert(constant.begin(), constant.end());
} catch (const std::runtime_error) {
throw std::runtime_error("Error fetching constant.");
}
}
// geometry
try {
json geometry = getFeatureGeometry(shape, geometry_precision);
if(!geometry.is_null()) feature["geometry"] = geometry;
} catch (const std::runtime_error) {
throw std::runtime_error("Error fetching geometry.");
}
return feature;
}
static json getLink(hashTableObj *metadata, const std::string& name)
{
json link;
const char *href = msOWSLookupMetadata(metadata, "A", (name + "_href").c_str());
if(!href) throw std::runtime_error("Missing required link href property.");
const char *title = msOWSLookupMetadata(metadata, "A", (name + "_title").c_str());
const char *type = msOWSLookupMetadata(metadata, "A", (name + "_type").c_str());
link = {
{ "href", href },
{ "title", title?title:href },
{ "type", type?type:"text/html" }
};
return link;
}
static const char* getCollectionDescription(layerObj* layer)
{
const char *description = msOWSLookupMetadata(&(layer->metadata), "A", "description");
if(!description) description = msOWSLookupMetadata(&(layer->metadata), "OF", "abstract"); // fallback on abstract
if(!description) description = "<!-- Warning: unable to set the collection description. -->"; // finally a warning...
return description;
}
static const char* getCollectionTitle(layerObj* layer)
{
const char* title = msOWSLookupMetadata(&(layer->metadata), "AOF", "title");
if(!title) title = layer->name; // revert to layer name if no title found
return title;
}
static int getGeometryPrecision(mapObj *map, layerObj *layer)
{
int geometry_precision = OGCAPI_DEFAULT_GEOMETRY_PRECISION;
if(msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision")) {
geometry_precision = atoi(msOWSLookupMetadata(&(layer->metadata), "AF", "geometry_precision"));
} else if(msOWSLookupMetadata(&map->web.metadata, "AF", "geometry_precision")) {
geometry_precision = atoi(msOWSLookupMetadata(&map->web.metadata, "AF", "geometry_precision"));
}
return geometry_precision;
}
static json getCollection(mapObj *map, layerObj *layer, OGCAPIFormat format)
{
json collection; // empty (null)
rectObj bbox;
if(!map || !layer) return collection;
if(!includeLayer(map, layer)) return collection;
// initialize some things
std::string api_root = getApiRootUrl(map);
if(msOWSGetLayerExtent(map, layer, "AOF", &bbox) == MS_SUCCESS) {
if (layer->projection.numargs > 0)
msOWSProjectToWGS84(&layer->projection, &bbox);
else if (map->projection.numargs > 0)
msOWSProjectToWGS84(&map->projection, &bbox);
else
throw std::runtime_error("Unable to transform bounding box, no projection defined.");
} else {
throw std::runtime_error("Unable to get collection bounding box."); // might be too harsh since extent is optional
}
const char *description = getCollectionDescription(layer);
const char *title = getCollectionTitle(layer);
const char *id = layer->name;
char *id_encoded = msEncodeUrl(id); // free after use
const int geometry_precision = getGeometryPrecision(map, layer);
// build collection object
collection = {
{ "id", id },
{ "description", description },
{ "title", title },
{ "extent", {
{ "spatial", {
{ "bbox", {{ round_down(bbox.minx, geometry_precision),
round_down(bbox.miny, geometry_precision),
round_up(bbox.maxx, geometry_precision),
round_up(bbox.maxy, geometry_precision) }}},
{ "crs", "http://www.opengis.net/def/crs/OGC/1.3/CRS84" }
}
}
}
},
{ "links", {
{
{ "rel", format==OGCAPIFormat::JSON?"self":"alternate" },
{ "type", OGCAPI_MIMETYPE_JSON },
{ "title", "This collection as JSON" },
{ "href", api_root + "/collections/" + std::string(id_encoded) + "?f=json" }
},{
{ "rel", format==OGCAPIFormat::HTML?"self":"alternate" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "This collection as HTML" },
{ "href", api_root + "/collections/" + std::string(id_encoded) + "?f=html" }
},{
{ "rel", "items" },
{ "type", OGCAPI_MIMETYPE_GEOJSON },
{ "title", "Items for this collection as GeoJSON" },
{ "href", api_root + "/collections/" + std::string(id_encoded) + "/items?f=json" }
},{
{ "rel", "items" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "Items for this collection as HTML" },
{ "href", api_root + "/collections/" + std::string(id_encoded) + "/items?f=html" }
}
}
},
{ "itemType", "feature" }
};
msFree(id_encoded); // done
// handle optional configuration (keywords and links)
const char *value = msOWSLookupMetadata(&(layer->metadata), "A", "keywords");
if(!value) value = msOWSLookupMetadata(&(layer->metadata), "OF", "keywordlist"); // fallback on keywordlist
if(value) {
std::vector<std::string> keywords = msStringSplit(value, ',');
for(std::string keyword : keywords) {
collection["keywords"].push_back(keyword);
}
}
value = msOWSLookupMetadata(&(layer->metadata), "A", "links");
if(value) {
std::vector<std::string> names = msStringSplit(value, ',');
for(std::string name : names) {
try {
json link = getLink(&(layer->metadata), name);
collection["links"].push_back(link);
} catch(const std::runtime_error &e) {
throw e;
}
}
}
return collection;
}
/*
** Output stuff...
*/
static void outputJson(const json& j, const char *mimetype)
{
msIO_setHeader("Content-Type", "%s", mimetype);
msIO_sendHeaders();
msIO_printf("%s\n", j.dump().c_str());
}
static void outputTemplate(const char *directory, const char *filename, const json& j, const char *mimetype)
{
std::string _directory(directory);
std::string _filename(filename);
Environment env {_directory}; // catch
// somehow need to limit include processing to the directory
// ERB-style instead of Mustache (we'll see)
// env.set_expression("<%=", "%>");
// env.set_statement("<%", "%>");
// callbacks, need:
// - match (regex)
// - contains (substring)
// - URL encode
try {
Template t = env.parse_template(_filename); // catch
std::string result = env.render(t, j);
msIO_setHeader("Content-Type", "%s", mimetype);
msIO_sendHeaders();
msIO_printf("%s\n", result.c_str());
} catch(const inja::RenderError &e) {
outputError(OGCAPI_CONFIG_ERROR, "Template rendering error. " + std::string(e.what()) + " (" + std::string(filename) + ").");
return;
}
catch (const inja::InjaError& e) {
outputError(OGCAPI_CONFIG_ERROR, "InjaError error. " + std::string(e.what()) + " (" + std::string(filename) + ")."
+ " (" + std::string(directory) + ").");
return;
} catch(...) {
outputError(OGCAPI_SERVER_ERROR, "General template handling error.");
return;
}
}
/*
** Generic response outputr.
*/
static void outputResponse(mapObj *map, cgiRequestObj *request, OGCAPIFormat format, const char *filename, const json& response)
{
const char *path = NULL;
char fullpath[MS_MAXPATHLEN];
if(format == OGCAPIFormat::JSON) {
outputJson(response, OGCAPI_MIMETYPE_JSON);
} else if(format == OGCAPIFormat::GeoJSON) {
outputJson(response, OGCAPI_MIMETYPE_GEOJSON);
} else if(format == OGCAPIFormat::OpenAPI_V3) {
outputJson(response, OGCAPI_MIMETYPE_OPENAPI_V3);
} else if(format == OGCAPIFormat::HTML) {
if((path = getTemplateDirectory(map, "html_template_directory", "OGCAPI_HTML_TEMPLATE_DIRECTORY")) == NULL) {
outputError(OGCAPI_CONFIG_ERROR, "Template directory not set.");
return; // bail
}
msBuildPath(fullpath, map->mappath, path);
json j;
j["response"] = response; // nest the response so we could write the whole object in the template
// extend the JSON with a few things that we need for templating
j["template"] = {
{ "path", json::array() },
{ "params", json::object() },
{ "api_root", getApiRootUrl(map) },
{ "title", getTitle(map) },
{ "tags", json::object() }
};
// api path
for( int i=0; i<request->api_path_length; i++ )
j["template"]["path"].push_back(request->api_path[i]);
// parameters (optional)
for( int i=0; i<request->NumParams; i++) {
if(request->ParamValues[i] && strlen(request->ParamValues[i]) > 0) { // skip empty params
j["template"]["params"].update({{ request->ParamNames[i], request->ParamValues[i] }});
}
}
// add custom tags (optional)
const char *tags = msOWSLookupMetadata(&(map->web.metadata), "A", "html_tags");
if(tags) {
std::vector<std::string> names = msStringSplit(tags, ',');
for(std::string name : names) {
const char *value = msOWSLookupMetadata(&(map->web.metadata), "A", ("tag_" + name).c_str());
if(value) {
j["template"]["tags"].update({{ name, value }}); // add object
}
}
}
outputTemplate(fullpath, filename, j, OGCAPI_MIMETYPE_HTML);
} else {
outputError(OGCAPI_PARAM_ERROR, "Unsupported format requested.");
}
}
/*
** Process stuff...
*/
static int processLandingRequest(mapObj *map, cgiRequestObj *request, OGCAPIFormat format)
{
json response;
// define ambiguous elements
const char *description = msOWSLookupMetadata(&(map->web.metadata), "A", "description");
if(!description) description = msOWSLookupMetadata(&(map->web.metadata), "OF", "abstract"); // fallback on abstract if necessary
// define api root url
std::string api_root = getApiRootUrl(map);
// build response object
// - consider conditionally excluding links for HTML format
response = {
{ "title", getTitle(map) },
{ "description", description?description:"" },
{ "links", {
{
{ "rel", format==OGCAPIFormat::JSON?"self":"alternate" },
{ "type", OGCAPI_MIMETYPE_JSON },
{ "title", "This document as JSON" },
{ "href", api_root + "?f=json" }
},{
{ "rel", format==OGCAPIFormat::HTML?"self":"alternate" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "This document as HTML" },
{ "href", api_root + "?f=html" }
},{
{ "rel", "conformance" },
{ "type", OGCAPI_MIMETYPE_JSON },
{ "title", "OCG API conformance classes implemented by this server (JSON)" },
{ "href", api_root + "/conformance?f=json" }
},{
{ "rel", "conformance" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "OCG API conformance classes implemented by this server" },
{ "href", api_root + "/conformance?f=html" }
},{
{ "rel", "data" },
{ "type", OGCAPI_MIMETYPE_JSON },
{ "title", "Information about feature collections available from this server (JSON)" },
{ "href", api_root + "/collections?f=json" }
},{
{ "rel", "data" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "Information about feature collections available from this server" },
{ "href", api_root + "/collections?f=html" }
},{
{ "rel", "service-desc" },
{ "type", OGCAPI_MIMETYPE_OPENAPI_V3 },
{ "title", "OpenAPI document" },
{ "href", api_root + "/api?f=json" }
},{
{ "rel", "service-doc" },
{ "type", OGCAPI_MIMETYPE_HTML },
{ "title", "API documentation" },
{ "href", api_root + "/api?f=html" }
}
}
}
};
// handle custom links (optional)
const char *links = msOWSLookupMetadata(&(map->web.metadata), "A", "links");
if(links) {
std::vector<std::string> names = msStringSplit(links, ',');
for(std::string name : names) {
try {
json link = getLink(&(map->web.metadata), name);
response["links"].push_back(link);
} catch(const std::runtime_error &e) {
outputError(OGCAPI_CONFIG_ERROR, std::string(e.what()));
return MS_SUCCESS;
}
}
}
outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_LANDING, response);
return MS_SUCCESS;
}
static int processConformanceRequest(mapObj *map, cgiRequestObj *request, OGCAPIFormat format)
{
json response;
// build response object
response = {
{ "conformsTo", {
"http://www.opengis.net/spec/ogcapi-common-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-common-2/1.0/conf/collections",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/core",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/oas30",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/html",
"http://www.opengis.net/spec/ogcapi-features-1/1.0/conf/geojson",
}
}
};
outputResponse(map, request, format, OGCAPI_TEMPLATE_HTML_CONFORMANCE, response);
return MS_SUCCESS;
}
static int processCollectionItemsRequest(mapObj *map, cgiRequestObj *request, const char *collectionId, const char *featureId, OGCAPIFormat format)
{
json response;
int i;
layerObj *layer;
int limit;
rectObj bbox;
int numberMatched = 0;
// find the right layer
for(i=0; i<map->numlayers; i++) {
if(strcmp(map->layers[i]->name, collectionId) == 0) break; // match
}
if(i == map->numlayers) { // invalid collectionId
outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
return MS_SUCCESS;
}
layer = map->layers[i]; // for convenience
layer->status = MS_ON; // force on (do we need to save and reset?)
if(!includeLayer(map, layer)) {
outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid collection.");
return MS_SUCCESS;
}
//
// handle parameters specific to this endpoint
//
if(getLimit(map, request, layer, &limit) != MS_SUCCESS) {
outputError(OGCAPI_PARAM_ERROR, "Bad value for limit.");
return MS_SUCCESS;
}
if(!getBbox(map, request, &bbox)) {
outputError(OGCAPI_PARAM_ERROR, "Bad value for bbox.");
return MS_SUCCESS;
}
int offset = 0;
if(featureId) {
const char *featureIdItem = msOWSLookupMetadata(&(layer->metadata), "AGFO", "featureid");
if(featureIdItem == NULL) {
outputError(OGCAPI_CONFIG_ERROR, "Missing required featureid metadata.");
return MS_SUCCESS;
}
// TODO: does featureIdItem exist in the data?
// optional validation
const char *featureIdValidation = msLookupHashTable(&(layer->validation), featureIdItem);
if(featureIdValidation && msValidateParameter(featureId, featureIdValidation, NULL, NULL, NULL) != MS_SUCCESS) {
outputError(OGCAPI_NOT_FOUND_ERROR, "Invalid feature id.");
return MS_SUCCESS;
}
map->query.type = MS_QUERY_BY_FILTER;
map->query.mode = MS_QUERY_SINGLE;
map->query.layer = i;
map->query.rect = bbox;
map->query.filteritem = strdup(featureIdItem);
msInitExpression(&map->query.filter);
map->query.filter.type = MS_STRING;
map->query.filter.string = strdup(featureId);
if(msExecuteQuery(map) != MS_SUCCESS) {
outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items id query failed.");
return MS_SUCCESS;
}
if(!layer->resultcache || layer->resultcache->numresults != 1) {
outputError(OGCAPI_NOT_FOUND_ERROR, "Collection items id query failed.");
return MS_SUCCESS;
}
} else { // bbox query