Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: OGR
4 : * Purpose: Implements OGC API - Features (previously known as WFS3)
5 : * Author: Even Rouault, even dot rouault at spatialys dot com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2018-2019, Even Rouault <even dot rouault at spatialys dot com>
9 : *
10 : * SPDX-License-Identifier: MIT
11 : ****************************************************************************/
12 :
13 : #include "ogrsf_frmts.h"
14 : #include "cpl_conv.h"
15 : #include "cpl_minixml.h"
16 : #include "cpl_http.h"
17 : #include "ogr_swq.h"
18 : #include "parsexsd.h"
19 :
20 : #include <algorithm>
21 : #include <cinttypes>
22 : #include <memory>
23 : #include <vector>
24 : #include <set>
25 :
26 : // g++ -Wshadow -Wextra -std=c++11 -fPIC -g -Wall
27 : // ogr/ogrsf_frmts/wfs/ogroapif*.cpp -shared -o ogr_OAPIF.so -Iport -Igcore
28 : // -Iogr -Iogr/ogrsf_frmts -Iogr/ogrsf_frmts/gml -Iogr/ogrsf_frmts/wfs -L.
29 : // -lgdal
30 :
31 : extern "C" void RegisterOGROAPIF();
32 :
33 : #define MEDIA_TYPE_OAPI_3_0 "application/vnd.oai.openapi+json;version=3.0"
34 : #define MEDIA_TYPE_OAPI_3_0_ALT "application/openapi+json;version=3.0"
35 : #define MEDIA_TYPE_JSON "application/json"
36 : #define MEDIA_TYPE_GEOJSON "application/geo+json"
37 : #define MEDIA_TYPE_TEXT_XML "text/xml"
38 : #define MEDIA_TYPE_APPLICATION_XML "application/xml"
39 : #define MEDIA_TYPE_JSON_SCHEMA "application/schema+json"
40 :
41 : constexpr const char *OGC_CRS84_WKT =
42 : "GEOGCRS[\"WGS 84 (CRS84)\",ENSEMBLE[\"World Geodetic System 1984 "
43 : "ensemble\",MEMBER[\"World Geodetic System 1984 "
44 : "(Transit)\"],MEMBER[\"World Geodetic System 1984 (G730)\"],MEMBER[\"World "
45 : "Geodetic System 1984 (G873)\"],MEMBER[\"World Geodetic System 1984 "
46 : "(G1150)\"],MEMBER[\"World Geodetic System 1984 (G1674)\"],MEMBER[\"World "
47 : "Geodetic System 1984 (G1762)\"],MEMBER[\"World Geodetic System 1984 "
48 : "(G2139)\"],ELLIPSOID[\"WGS "
49 : "84\",6378137,298.257223563,LENGTHUNIT[\"metre\",1]],ENSEMBLEACCURACY[2.0]]"
50 : ",PRIMEM[\"Greenwich\",0,ANGLEUNIT[\"degree\",0.0174532925199433]],CS["
51 : "ellipsoidal,2],AXIS[\"geodetic longitude "
52 : "(Lon)\",east,ORDER[1],ANGLEUNIT[\"degree\",0.0174532925199433]],AXIS["
53 : "\"geodetic latitude "
54 : "(Lat)\",north,ORDER[2],ANGLEUNIT[\"degree\",0.0174532925199433]],USAGE["
55 : "SCOPE[\"Not "
56 : "known.\"],AREA[\"World.\"],BBOX[-90,-180,90,180]],ID[\"OGC\",\"CRS84\"]]";
57 :
58 : /************************************************************************/
59 : /* OGROAPIFDataset */
60 : /************************************************************************/
61 : class OGROAPIFLayer;
62 :
63 : class OGROAPIFDataset final : public GDALDataset
64 : {
65 : friend class OGROAPIFLayer;
66 :
67 : bool m_bMustCleanPersistent = false;
68 :
69 : // Server base URL. Like "https://example.com"
70 : // Relative links are relative to it
71 : CPLString m_osServerBaseURL{};
72 :
73 : // Service base URL. Like "https://example.com/ogcapi"
74 : CPLString m_osRootURL{};
75 :
76 : CPLString m_osUserQueryParams{};
77 : CPLString m_osUserPwd{};
78 : int m_nPageSize = 1000;
79 : int m_nInitialRequestPageSize = 20;
80 : bool m_bPageSizeSetFromOpenOptions = false;
81 : std::vector<std::unique_ptr<OGRLayer>> m_apoLayers{};
82 : std::string m_osAskedCRS{};
83 : OGRSpatialReference m_oAskedCRS{};
84 : bool m_bAskedCRSIsRequired = false;
85 : bool m_bServerFeaturesAxisOrderGISFriendly = false;
86 :
87 : bool m_bAPIDocLoaded = false;
88 : CPLJSONDocument m_oAPIDoc{};
89 :
90 : bool m_bLandingPageDocLoaded = false;
91 : CPLJSONDocument m_oLandingPageDoc{};
92 :
93 : bool m_bIgnoreSchema = false;
94 :
95 : std::string m_osDateTime{};
96 :
97 : bool Download(const CPLString &osURL, const char *pszAccept,
98 : CPLString &osResult, CPLString &osContentType,
99 : CPLStringList *paosHeaders = nullptr);
100 :
101 : bool DownloadJSon(const CPLString &osURL, CPLJSONDocument &oDoc,
102 : const char *pszAccept = MEDIA_TYPE_GEOJSON
103 : ", " MEDIA_TYPE_JSON,
104 : CPLStringList *paosHeaders = nullptr);
105 :
106 : bool LoadJSONCollection(const CPLJSONObject &oCollection,
107 : const CPLJSONArray &oGlobalCRSList);
108 : bool LoadJSONCollections(const CPLString &osResultIn,
109 : const std::string &osCollectionsURL);
110 :
111 : /**
112 : * Determines the page size by making a call to the API endpoint to get the server's
113 : * default and max limits for the collection items specified by itemsUrl
114 : */
115 : void DeterminePageSizeFromAPI(const std::string &itemsUrl);
116 :
117 : public:
118 42 : OGROAPIFDataset() = default;
119 : ~OGROAPIFDataset();
120 :
121 45 : int GetLayerCount() override
122 : {
123 45 : return static_cast<int>(m_apoLayers.size());
124 : }
125 :
126 : OGRLayer *GetLayer(int idx) override;
127 :
128 : bool Open(GDALOpenInfo *);
129 : const CPLJSONDocument &GetAPIDoc(std::string &osURLOut);
130 : const CPLJSONDocument &GetLandingPageDoc(std::string &osURLOut);
131 :
132 : CPLString ResolveURL(const CPLString &osURL,
133 : const std::string &osRequestURL) const;
134 : };
135 :
136 : /************************************************************************/
137 : /* OGROAPIFLayer */
138 : /************************************************************************/
139 :
140 : class OGROAPIFLayer final : public OGRLayer
141 : {
142 : OGROAPIFDataset *m_poDS = nullptr;
143 : OGRFeatureDefn *m_poFeatureDefn = nullptr;
144 : bool m_bIsGeographicCRS = false;
145 : bool m_bCRSHasGISFriendlyOrder = false;
146 : bool m_bHasEmittedContentCRSWarning = false;
147 : bool m_bHasEmittedJsonCRWarning = false;
148 : std::string m_osActiveCRS{};
149 : CPLString m_osURL{};
150 : CPLString m_osPath{};
151 : OGREnvelope m_oExtent{};
152 : OGREnvelope m_oOriginalExtent{};
153 : OGRSpatialReference m_oOriginalExtentCRS{};
154 : bool m_bFeatureDefnEstablished = false;
155 : std::unique_ptr<GDALDataset> m_poUnderlyingDS{};
156 : OGRLayer *m_poUnderlyingLayer = nullptr;
157 : GIntBig m_nFID = 1;
158 : CPLString m_osGetURL{};
159 : CPLString m_osAttributeFilter{};
160 : CPLString m_osGetID{};
161 : std::vector<std::string> m_oSupportedCRSList{};
162 : OGRLayer::GetSupportedSRSListRetType m_apoSupportedCRSList{};
163 : bool m_bFilterMustBeClientSideEvaluated = false;
164 : bool m_bGotQueryableAttributes = false;
165 : std::set<CPLString> m_aoSetQueryableAttributes{};
166 : bool m_bHasCQLText = false;
167 : // https://github.com/tschaub/ogcapi-features/blob/json-array-expression/extensions/cql/jfe/readme.md
168 : bool m_bHasJSONFilterExpression = false;
169 : GIntBig m_nTotalFeatureCount = -1;
170 : bool m_bHasIntIdMember = false;
171 : bool m_bHasStringIdMember = false;
172 : std::vector<std::unique_ptr<OGRFieldDefn>> m_apoFieldsFromSchema{};
173 : CPLString m_osDescribedByURL{};
174 : CPLString m_osDescribedByType{};
175 : bool m_bDescribedByIsXML = false;
176 : CPLString m_osQueryablesURL{};
177 : std::vector<std::string> m_aosItemAssetNames{}; // STAC specific
178 : CPLJSONDocument m_oCurDoc{};
179 : int m_iFeatureInPage = 0;
180 :
181 : void EstablishFeatureDefn();
182 : OGRFeature *GetNextRawFeature();
183 : CPLString AddFilters(const CPLString &osURL);
184 : CPLString BuildFilter(const swq_expr_node *poNode);
185 : CPLString BuildFilterCQLText(const swq_expr_node *poNode);
186 : CPLString BuildFilterJSONFilterExpr(const swq_expr_node *poNode);
187 : bool SupportsResultTypeHits();
188 : void GetQueryableAttributes();
189 : void GetSchema();
190 : void ComputeExtent();
191 :
192 : CPL_DISALLOW_COPY_ASSIGN(OGROAPIFLayer)
193 :
194 : public:
195 : OGROAPIFLayer(OGROAPIFDataset *poDS, const CPLString &osName,
196 : const CPLJSONArray &oBBOX, const std::string &osBBOXCrs,
197 : std::vector<std::string> &&oCRSList,
198 : const std::string &osActiveCRS, double dfCoordinateEpoch,
199 : const CPLJSONArray &oLinks);
200 :
201 : ~OGROAPIFLayer();
202 :
203 : void SetItemAssets(const CPLJSONObject &oItemAssets);
204 :
205 11 : const char *GetName() override
206 : {
207 11 : return GetDescription();
208 : }
209 :
210 : OGRFeatureDefn *GetLayerDefn() override;
211 : void ResetReading() override;
212 : OGRFeature *GetNextFeature() override;
213 : OGRFeature *GetFeature(GIntBig) override;
214 : int TestCapability(const char *) override;
215 : GIntBig GetFeatureCount(int bForce = FALSE) override;
216 : OGRErr IGetExtent(int iGeomField, OGREnvelope *psExtent,
217 : bool bForce) override;
218 :
219 : OGRErr ISetSpatialFilter(int iGeomField,
220 : const OGRGeometry *poGeom) override;
221 :
222 : OGRErr SetAttributeFilter(const char *pszQuery) override;
223 :
224 : const OGRLayer::GetSupportedSRSListRetType &
225 : GetSupportedSRSList(int iGeomField) override;
226 : OGRErr SetActiveSRS(int iGeomField,
227 : const OGRSpatialReference *poSRS) override;
228 :
229 1 : void SetTotalItemCount(GIntBig nCount)
230 : {
231 1 : m_nTotalFeatureCount = nCount;
232 1 : }
233 : };
234 :
235 : /************************************************************************/
236 : /* CheckContentType() */
237 : /************************************************************************/
238 :
239 : // We may ask for "application/openapi+json;version=3.0"
240 : // and the server returns "application/openapi+json; charset=utf-8; version=3.0"
241 371 : static bool CheckContentType(const char *pszGotContentType,
242 : const char *pszExpectedContentType)
243 : {
244 742 : CPLStringList aosGotTokens(CSLTokenizeString2(pszGotContentType, "; ", 0));
245 : CPLStringList aosExpectedTokens(
246 742 : CSLTokenizeString2(pszExpectedContentType, "; ", 0));
247 632 : for (int i = 0; i < aosExpectedTokens.size(); i++)
248 : {
249 372 : bool bFound = false;
250 491 : for (int j = 0; j < aosGotTokens.size(); j++)
251 : {
252 380 : if (EQUAL(aosExpectedTokens[i], aosGotTokens[j]))
253 : {
254 261 : bFound = true;
255 261 : break;
256 : }
257 : }
258 372 : if (!bFound)
259 111 : return false;
260 : }
261 260 : return true;
262 : }
263 :
264 : /************************************************************************/
265 : /* ~OGROAPIFDataset() */
266 : /************************************************************************/
267 :
268 84 : OGROAPIFDataset::~OGROAPIFDataset()
269 : {
270 42 : if (m_bMustCleanPersistent)
271 : {
272 42 : char **papszOptions = CSLSetNameValue(nullptr, "CLOSE_PERSISTENT",
273 : CPLSPrintf("OAPIF:%p", this));
274 42 : CPLHTTPDestroyResult(CPLHTTPFetch(m_osRootURL, papszOptions));
275 42 : CSLDestroy(papszOptions);
276 : }
277 84 : }
278 :
279 : /************************************************************************/
280 : /* ResolveURL() */
281 : /************************************************************************/
282 :
283 : // Resolve relative links and re-inject authentication elements.
284 : // If source URL is https://user:pwd@server.com/bla
285 : // and link only contains https://server.com/bla, then insert
286 : // into it user:pwd
287 20 : CPLString OGROAPIFDataset::ResolveURL(const CPLString &osURL,
288 : const std::string &osRequestURL) const
289 : {
290 20 : const auto CleanURL = [](const std::string &osStr)
291 : {
292 20 : std::string osRet(osStr);
293 20 : const auto nPos = osRet.rfind('?');
294 20 : if (nPos != std::string::npos)
295 1 : osRet.resize(nPos);
296 20 : if (!osRet.empty() && osRet.back() == '/')
297 0 : osRet.pop_back();
298 20 : return osRet;
299 : };
300 :
301 20 : CPLString osRet(osURL);
302 : // Cf https://datatracker.ietf.org/doc/html/rfc3986#section-5.4
303 : // Partial implementation for usual cases...
304 : std::string osRequestURLBase =
305 40 : CPLGetPathSafe(CleanURL(osRequestURL).c_str());
306 20 : if (!osURL.empty() && osURL[0] == '/')
307 1 : osRet = m_osServerBaseURL + osURL;
308 19 : else if (osURL.size() > 2 && osURL[0] == '.' && osURL[1] == '/')
309 1 : osRet = osRequestURLBase + osURL.substr(1);
310 19 : else if (osURL.size() > 3 && osURL[0] == '.' && osURL[1] == '.' &&
311 1 : osURL[2] == '/')
312 : {
313 1 : std::string osModifiedRequestURL(std::move(osRequestURLBase));
314 3 : while (osRet.size() > 3 && osRet[0] == '.' && osRet[1] == '.' &&
315 1 : osRet[2] == '/')
316 : {
317 1 : osModifiedRequestURL = CPLGetPathSafe(osModifiedRequestURL.c_str());
318 1 : osRet = osRet.substr(3);
319 : }
320 1 : osRet = osModifiedRequestURL + "/" + osRet;
321 : }
322 17 : else if (!STARTS_WITH(osURL.c_str(), "http://") &&
323 18 : !STARTS_WITH(osURL.c_str(), "https://") &&
324 1 : !STARTS_WITH(osURL.c_str(), "file://"))
325 : {
326 1 : osRet = osRequestURLBase + "/" + osURL;
327 : }
328 :
329 20 : const auto nArobaseInURLPos = m_osServerBaseURL.find('@');
330 40 : if (!osRet.empty() && STARTS_WITH(m_osServerBaseURL, "https://") &&
331 0 : STARTS_WITH(osRet, "https://") &&
332 40 : nArobaseInURLPos != std::string::npos &&
333 0 : osRet.find('@') == std::string::npos)
334 : {
335 : const auto nFirstSlashPos =
336 0 : m_osServerBaseURL.find('/', strlen("https://"));
337 0 : if (nFirstSlashPos == std::string::npos ||
338 : nFirstSlashPos > nArobaseInURLPos)
339 : {
340 : auto osUserPwd = m_osServerBaseURL.substr(
341 0 : strlen("https://"), nArobaseInURLPos - strlen("https://"));
342 : std::string osServer(
343 : nFirstSlashPos == std::string::npos
344 : ? m_osServerBaseURL.substr(nArobaseInURLPos + 1)
345 : : m_osServerBaseURL.substr(nArobaseInURLPos + 1,
346 : nFirstSlashPos -
347 0 : nArobaseInURLPos));
348 0 : if (STARTS_WITH(osRet, ("https://" + osServer).c_str()))
349 : {
350 0 : osRet = "https://" + osUserPwd + "@" +
351 0 : osRet.substr(strlen("https://"));
352 : }
353 : }
354 : }
355 40 : return osRet;
356 : }
357 :
358 : /************************************************************************/
359 : /* Download() */
360 : /************************************************************************/
361 :
362 199 : bool OGROAPIFDataset::Download(const CPLString &osURL, const char *pszAccept,
363 : CPLString &osResult, CPLString &osContentType,
364 : CPLStringList *paosHeaders)
365 : {
366 : #ifndef REMOVE_HACK
367 : VSIStatBufL sStatBuf;
368 199 : if (VSIStatL(osURL, &sStatBuf) == 0)
369 : {
370 0 : CPLDebug("OAPIF", "Reading %s", osURL.c_str());
371 0 : GByte *pabyRet = nullptr;
372 0 : if (VSIIngestFile(nullptr, osURL, &pabyRet, nullptr, -1))
373 : {
374 0 : osResult = reinterpret_cast<char *>(pabyRet);
375 0 : CPLFree(pabyRet);
376 : }
377 0 : return false;
378 : }
379 : #endif
380 199 : char **papszOptions = nullptr;
381 :
382 199 : if (pszAccept)
383 : {
384 : papszOptions =
385 198 : CSLSetNameValue(papszOptions, "HEADERS",
386 396 : (CPLString("Accept: ") + pszAccept).c_str());
387 : }
388 :
389 199 : if (!m_osUserPwd.empty())
390 : {
391 : papszOptions =
392 0 : CSLSetNameValue(papszOptions, "USERPWD", m_osUserPwd.c_str());
393 : }
394 199 : m_bMustCleanPersistent = true;
395 : papszOptions =
396 199 : CSLAddString(papszOptions, CPLSPrintf("PERSISTENT=OAPIF:%p", this));
397 398 : CPLString osURLWithQueryParameters(osURL);
398 15 : if (!m_osUserQueryParams.empty() &&
399 413 : osURL.find('?' + m_osUserQueryParams) == std::string::npos &&
400 210 : osURL.find('&' + m_osUserQueryParams) == std::string::npos)
401 : {
402 11 : if (osURL.find('?') == std::string::npos)
403 : {
404 6 : osURLWithQueryParameters += '?';
405 : }
406 : else
407 : {
408 5 : osURLWithQueryParameters += '&';
409 : }
410 11 : osURLWithQueryParameters += m_osUserQueryParams;
411 : }
412 : CPLHTTPResult *psResult =
413 199 : CPLHTTPFetch(osURLWithQueryParameters, papszOptions);
414 199 : CSLDestroy(papszOptions);
415 199 : if (!psResult)
416 0 : return false;
417 :
418 199 : if (psResult->pszErrBuf != nullptr)
419 : {
420 62 : std::string osErrorMsg(psResult->pszErrBuf);
421 62 : const char *pszData =
422 : reinterpret_cast<const char *>(psResult->pabyData);
423 62 : if (pszData)
424 : {
425 61 : osErrorMsg += ", ";
426 61 : osErrorMsg.append(pszData, CPLStrnlen(pszData, 1000));
427 : }
428 62 : CPLError(CE_Failure, CPLE_AppDefined, "%s", osErrorMsg.c_str());
429 62 : CPLHTTPDestroyResult(psResult);
430 62 : return false;
431 : }
432 :
433 137 : if (psResult->pszContentType)
434 133 : osContentType = psResult->pszContentType;
435 :
436 : // Do not check content type if not specified
437 137 : bool bFoundExpectedContentType = pszAccept ? false : true;
438 :
439 137 : if (!bFoundExpectedContentType)
440 : {
441 : #ifndef REMOVE_HACK
442 : // cppcheck-suppress nullPointer
443 136 : if (strstr(pszAccept, "json"))
444 : {
445 136 : if (strstr(osURL, "raw.githubusercontent.com") &&
446 0 : strstr(osURL, ".json"))
447 : {
448 0 : bFoundExpectedContentType = true;
449 : }
450 268 : else if (psResult->pszContentType != nullptr &&
451 132 : (CheckContentType(psResult->pszContentType,
452 54 : MEDIA_TYPE_JSON) ||
453 54 : CheckContentType(psResult->pszContentType,
454 : MEDIA_TYPE_GEOJSON)))
455 : {
456 129 : bFoundExpectedContentType = true;
457 : }
458 : }
459 : #endif
460 :
461 : // cppcheck-suppress nullPointer
462 136 : if (strstr(pszAccept, "xml") && psResult->pszContentType != nullptr &&
463 0 : (CheckContentType(psResult->pszContentType, MEDIA_TYPE_TEXT_XML) ||
464 0 : CheckContentType(psResult->pszContentType,
465 : MEDIA_TYPE_APPLICATION_XML)))
466 : {
467 0 : bFoundExpectedContentType = true;
468 : }
469 :
470 : // cppcheck-suppress nullPointer
471 273 : if (strstr(pszAccept, MEDIA_TYPE_JSON_SCHEMA) &&
472 137 : psResult->pszContentType != nullptr &&
473 1 : (CheckContentType(psResult->pszContentType, MEDIA_TYPE_JSON) ||
474 1 : CheckContentType(psResult->pszContentType,
475 : MEDIA_TYPE_JSON_SCHEMA)))
476 : {
477 1 : bFoundExpectedContentType = true;
478 : }
479 :
480 77 : for (const char *pszMediaType : {
481 : MEDIA_TYPE_JSON,
482 : MEDIA_TYPE_GEOJSON,
483 : MEDIA_TYPE_OAPI_3_0,
484 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
485 : MEDIA_TYPE_OAPI_3_0_ALT,
486 : #endif
487 213 : })
488 : {
489 : // cppcheck-suppress nullPointer
490 605 : if (strstr(pszAccept, pszMediaType) &&
491 390 : psResult->pszContentType != nullptr &&
492 183 : CheckContentType(psResult->pszContentType, pszMediaType))
493 : {
494 130 : bFoundExpectedContentType = true;
495 130 : break;
496 : }
497 : }
498 : }
499 :
500 137 : if (!bFoundExpectedContentType)
501 : {
502 5 : CPLError(CE_Failure, CPLE_AppDefined, "Unexpected Content-Type: %s",
503 5 : psResult->pszContentType ? psResult->pszContentType
504 : : "(null)");
505 5 : CPLHTTPDestroyResult(psResult);
506 5 : return false;
507 : }
508 :
509 132 : if (psResult->pabyData == nullptr)
510 : {
511 0 : CPLError(CE_Failure, CPLE_AppDefined,
512 : "Empty content returned by server");
513 0 : CPLHTTPDestroyResult(psResult);
514 0 : return false;
515 : }
516 :
517 132 : if (paosHeaders)
518 : {
519 38 : *paosHeaders = CSLDuplicate(psResult->papszHeaders);
520 : }
521 :
522 132 : osResult = reinterpret_cast<const char *>(psResult->pabyData);
523 132 : CPLHTTPDestroyResult(psResult);
524 132 : return true;
525 : }
526 :
527 : /************************************************************************/
528 : /* DownloadJSon() */
529 : /************************************************************************/
530 :
531 154 : bool OGROAPIFDataset::DownloadJSon(const CPLString &osURL,
532 : CPLJSONDocument &oDoc, const char *pszAccept,
533 : CPLStringList *paosHeaders)
534 : {
535 308 : CPLString osResult;
536 308 : CPLString osContentType;
537 154 : if (!Download(osURL, pszAccept, osResult, osContentType, paosHeaders))
538 63 : return false;
539 91 : return oDoc.LoadMemory(osResult);
540 : }
541 :
542 : /************************************************************************/
543 : /* GetLandingPageDoc() */
544 : /************************************************************************/
545 :
546 31 : const CPLJSONDocument &OGROAPIFDataset::GetLandingPageDoc(std::string &osURLOut)
547 : {
548 31 : if (m_bLandingPageDocLoaded)
549 0 : return m_oLandingPageDoc;
550 31 : m_bLandingPageDocLoaded = true;
551 31 : osURLOut = m_osRootURL;
552 31 : CPL_IGNORE_RET_VAL(
553 31 : DownloadJSon(osURLOut, m_oLandingPageDoc, MEDIA_TYPE_JSON));
554 31 : return m_oLandingPageDoc;
555 : }
556 :
557 : /************************************************************************/
558 : /* GetAPIDoc() */
559 : /************************************************************************/
560 :
561 36 : const CPLJSONDocument &OGROAPIFDataset::GetAPIDoc(std::string &osURLOut)
562 : {
563 36 : if (m_bAPIDocLoaded)
564 5 : return m_oAPIDoc;
565 31 : m_bAPIDocLoaded = true;
566 :
567 : // Fetch the /api URL from the links of the landing page
568 62 : CPLString osAPIURL;
569 62 : std::string osLandingPageURL;
570 31 : const auto &oLandingPage = GetLandingPageDoc(osLandingPageURL);
571 31 : if (oLandingPage.GetRoot().IsValid())
572 : {
573 93 : const auto oLinks = oLandingPage.GetRoot().GetArray("links");
574 31 : if (oLinks.IsValid())
575 : {
576 10 : int nCountRelAPI = 0;
577 16 : for (int i = 0; i < oLinks.Size(); i++)
578 : {
579 16 : CPLJSONObject oLink = oLinks[i];
580 32 : if (!oLink.IsValid() ||
581 16 : oLink.GetType() != CPLJSONObject::Type::Object)
582 : {
583 0 : continue;
584 : }
585 32 : const auto osRel(oLink.GetString("rel"));
586 32 : const auto osType(oLink.GetString("type"));
587 16 : if (EQUAL(osRel.c_str(), "service-desc")
588 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
589 : // Needed for http://beta.fmi.fi/data/3/wfs/sofp
590 16 : || EQUAL(osRel.c_str(), "service")
591 : #endif
592 : )
593 : {
594 10 : nCountRelAPI++;
595 : osAPIURL =
596 10 : ResolveURL(oLink.GetString("href"), osLandingPageURL);
597 10 : if (osType == MEDIA_TYPE_OAPI_3_0
598 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
599 : // Needed for http://beta.fmi.fi/data/3/wfs/sofp
600 10 : || osType == MEDIA_TYPE_OAPI_3_0_ALT
601 : #endif
602 : )
603 : {
604 10 : nCountRelAPI = 1;
605 10 : break;
606 : }
607 : }
608 : }
609 10 : if (!osAPIURL.empty() && nCountRelAPI > 1)
610 : {
611 0 : osAPIURL.clear();
612 : }
613 : }
614 : }
615 :
616 31 : const char *pszAccept = MEDIA_TYPE_OAPI_3_0
617 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
618 : ", " MEDIA_TYPE_OAPI_3_0_ALT ", " MEDIA_TYPE_JSON
619 : #endif
620 : ;
621 :
622 31 : if (!osAPIURL.empty())
623 : {
624 10 : osURLOut = osAPIURL;
625 10 : CPL_IGNORE_RET_VAL(DownloadJSon(osAPIURL, m_oAPIDoc, pszAccept));
626 10 : return m_oAPIDoc;
627 : }
628 :
629 : #ifndef REMOVE_HACK
630 21 : CPLPushErrorHandler(CPLQuietErrorHandler);
631 42 : CPLString osURL(m_osRootURL + "/api");
632 21 : osURL = CPLGetConfigOption("OGR_WFS3_API_URL", osURL.c_str());
633 21 : bool bOK = DownloadJSon(osURL, m_oAPIDoc, pszAccept);
634 21 : CPLPopErrorHandler();
635 21 : CPLErrorReset();
636 21 : if (bOK)
637 : {
638 0 : return m_oAPIDoc;
639 : }
640 :
641 21 : osURLOut = m_osRootURL + "/api/";
642 21 : if (DownloadJSon(osURLOut, m_oAPIDoc, pszAccept))
643 : {
644 0 : return m_oAPIDoc;
645 : }
646 : #endif
647 21 : return m_oAPIDoc;
648 : }
649 :
650 : /************************************************************************/
651 : /* LoadJSONCollection() */
652 : /************************************************************************/
653 :
654 37 : bool OGROAPIFDataset::LoadJSONCollection(const CPLJSONObject &oCollection,
655 : const CPLJSONArray &oGlobalCRSList)
656 : {
657 37 : if (oCollection.GetType() != CPLJSONObject::Type::Object)
658 1 : return false;
659 :
660 : // As used by https://maps.ecere.com/ogcapi/collections?f=json
661 108 : const auto osLayerDataType = oCollection.GetString("layerDataType");
662 36 : if (osLayerDataType == "Raster" || osLayerDataType == "Coverage")
663 0 : return false;
664 :
665 108 : CPLString osName(oCollection.GetString("id"));
666 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
667 36 : if (osName.empty())
668 21 : osName = oCollection.GetString("name");
669 36 : if (osName.empty())
670 1 : osName = oCollection.GetString("collectionId");
671 : #endif
672 36 : if (osName.empty())
673 1 : return false;
674 :
675 105 : CPLString osTitle(oCollection.GetString("title"));
676 105 : CPLString osDescription(oCollection.GetString("description"));
677 105 : CPLJSONArray oBBOX = oCollection.GetArray("extent/spatial/bbox");
678 : #ifndef REMOVE_HACK_FOR_NLS_FINLAND_SERVICES
679 35 : if (!oBBOX.IsValid())
680 32 : oBBOX = oCollection.GetArray("extent/spatialExtent/bbox");
681 : #endif
682 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
683 35 : if (!oBBOX.IsValid())
684 32 : oBBOX = oCollection.GetArray("extent/spatial");
685 : #endif
686 105 : const std::string osBBOXCrs = oCollection.GetString("extent/spatial/crs");
687 :
688 : // Deal with CRS list
689 105 : const CPLJSONArray oCRSListOri = oCollection.GetArray("crs");
690 70 : std::vector<std::string> oCRSList;
691 70 : std::string osActiveCRS;
692 35 : double dfCoordinateEpoch = 0.0;
693 35 : if (oCRSListOri.IsValid())
694 : {
695 12 : std::set<std::string> oSetCRS;
696 40 : for (const auto &oCRS : oCRSListOri)
697 : {
698 28 : if (oCRS.ToString() == "#/crs")
699 : {
700 4 : if (!oGlobalCRSList.IsValid())
701 : {
702 0 : CPLError(CE_Failure, CPLE_AppDefined,
703 : "Collection %s refer to #/crs global CRS list, "
704 : "which is missing",
705 : osTitle.c_str());
706 : }
707 : else
708 : {
709 8 : for (const auto &oGlobalCRS : oGlobalCRSList)
710 : {
711 12 : std::string osCRS = oGlobalCRS.ToString();
712 4 : if (oSetCRS.find(osCRS) == oSetCRS.end())
713 : {
714 4 : oSetCRS.insert(osCRS);
715 4 : oCRSList.push_back(std::move(osCRS));
716 : }
717 : }
718 : }
719 : }
720 : else
721 : {
722 72 : std::string osCRS = oCRS.ToString();
723 24 : if (oSetCRS.find(osCRS) == oSetCRS.end())
724 : {
725 24 : oSetCRS.insert(osCRS);
726 24 : oCRSList.push_back(std::move(osCRS));
727 : }
728 : }
729 : }
730 :
731 12 : if (!m_oAskedCRS.IsEmpty())
732 : {
733 8 : for (const auto &osCRS : oCRSList)
734 : {
735 6 : OGRSpatialReference oSRS;
736 6 : if (oSRS.SetFromUserInput(
737 : osCRS.c_str(),
738 : OGRSpatialReference::
739 6 : SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
740 : OGRERR_NONE)
741 : {
742 6 : if (oSRS.IsSame(&m_oAskedCRS))
743 : {
744 2 : osActiveCRS = osCRS;
745 2 : break;
746 : }
747 : }
748 : }
749 4 : if (osActiveCRS.empty())
750 : {
751 2 : if (m_bAskedCRSIsRequired)
752 : {
753 1 : std::string osList;
754 3 : for (const auto &osCRS : oCRSList)
755 : {
756 2 : if (!osList.empty())
757 1 : osList += ", ";
758 2 : if (osCRS.find(
759 2 : "http://www.opengis.net/def/crs/EPSG/0/") == 0)
760 : osList +=
761 2 : "EPSG:" +
762 2 : osCRS.substr(strlen(
763 1 : "http://www.opengis.net/def/crs/EPSG/0/"));
764 1 : else if (osCRS.find("https://www.opengis.net/def/crs/"
765 1 : "EPSG/0/") == 0)
766 : osList +=
767 0 : "EPSG:" +
768 0 : osCRS.substr(strlen(
769 0 : "https://www.opengis.net/def/crs/EPSG/0/"));
770 1 : else if (osCRS.find("http://www.opengis.net/def/crs/"
771 1 : "OGC/1.3/") == 0)
772 : osList +=
773 2 : "OGC:" +
774 2 : osCRS.substr(strlen(
775 1 : "http://www.opengis.net/def/crs/OGC/1.3/"));
776 0 : else if (osCRS.find("https://www.opengis.net/def/crs/"
777 0 : "OGC/1.3/") == 0)
778 0 : osList += "OGC:" + osCRS.substr(strlen(
779 : "https://www.opengis.net/"
780 0 : "def/crs/OGC/1.3/"));
781 : else
782 0 : osList += osCRS;
783 : }
784 1 : CPLError(CE_Failure, CPLE_AppDefined,
785 : "CRS %s not found in list of CRS valid for "
786 : "collection %s. Available CRS are %s.",
787 : m_osAskedCRS.c_str(), osTitle.c_str(),
788 : osList.c_str());
789 1 : return false;
790 : }
791 : else
792 : {
793 1 : CPLDebug("OAPIF",
794 : "CRS %s not found in list of CRS valid for "
795 : "collection %s",
796 : m_osAskedCRS.c_str(), osTitle.c_str());
797 : }
798 : }
799 : }
800 : }
801 :
802 : // storageCRS is in the "OGC API - Features - Part 2: Coordinate Reference
803 : // Systems" extension
804 102 : std::string osStorageCRS = oCollection.GetString("storageCrs");
805 : const double dfStorageCrsCoordinateEpoch =
806 34 : oCollection.GetDouble("storageCrsCoordinateEpoch");
807 34 : if (osActiveCRS.empty() || osActiveCRS == osStorageCRS)
808 : {
809 32 : osActiveCRS = std::move(osStorageCRS);
810 32 : dfCoordinateEpoch = dfStorageCrsCoordinateEpoch;
811 : }
812 :
813 102 : const auto oLinks = oCollection.GetArray("links");
814 : auto poLayer = std::make_unique<OGROAPIFLayer>(
815 34 : this, osName, oBBOX, osBBOXCrs, std::move(oCRSList), osActiveCRS,
816 68 : dfCoordinateEpoch, oLinks);
817 34 : if (!osTitle.empty())
818 2 : poLayer->SetMetadataItem("TITLE", osTitle.c_str());
819 34 : if (!osDescription.empty())
820 0 : poLayer->SetMetadataItem("DESCRIPTION", osDescription.c_str());
821 102 : auto oTemporalInterval = oCollection.GetArray("extent/temporal/interval");
822 34 : if (oTemporalInterval.IsValid() && oTemporalInterval.Size() == 1 &&
823 34 : oTemporalInterval[0].GetType() == CPLJSONObject::Type::Array)
824 : {
825 0 : auto oArray = oTemporalInterval[0].ToArray();
826 0 : if (oArray.Size() == 2)
827 : {
828 0 : if (oArray[0].GetType() == CPLJSONObject::Type::String)
829 : {
830 0 : poLayer->SetMetadataItem("TEMPORAL_INTERVAL_MIN",
831 0 : oArray[0].ToString().c_str());
832 : }
833 0 : if (oArray[1].GetType() == CPLJSONObject::Type::String)
834 : {
835 0 : poLayer->SetMetadataItem("TEMPORAL_INTERVAL_MAX",
836 0 : oArray[1].ToString().c_str());
837 : }
838 : }
839 : }
840 :
841 : // STAC specific
842 102 : auto oItemAssets = oCollection.GetObj("item_assets");
843 35 : if (oItemAssets.IsValid() &&
844 1 : oItemAssets.GetType() == CPLJSONObject::Type::Object)
845 : {
846 1 : poLayer->SetItemAssets(oItemAssets);
847 : }
848 :
849 : // LDProxy extension (https://github.com/opengeospatial/ogcapi-features/issues/261#issuecomment-1271010859)
850 34 : const auto nItemCount = oCollection.GetLong("itemCount", -1);
851 34 : if (nItemCount >= 0)
852 1 : poLayer->SetTotalItemCount(nItemCount);
853 :
854 34 : auto oJSONStr = oCollection.Format(CPLJSONObject::PrettyFormat::Pretty);
855 34 : char *apszMetadata[2] = {&oJSONStr[0], nullptr};
856 34 : poLayer->SetMetadata(apszMetadata, "json:metadata");
857 :
858 34 : m_apoLayers.emplace_back(std::move(poLayer));
859 34 : return true;
860 : }
861 :
862 : /************************************************************************/
863 : /* LoadJSONCollections() */
864 : /************************************************************************/
865 :
866 34 : bool OGROAPIFDataset::LoadJSONCollections(const CPLString &osResultIn,
867 : const std::string &osCollectionsURL)
868 : {
869 68 : std::string osParentURL(osCollectionsURL);
870 68 : CPLString osResult(osResultIn);
871 66 : while (!osResult.empty())
872 : {
873 35 : CPLJSONDocument oDoc;
874 35 : if (!oDoc.LoadMemory(osResult))
875 : {
876 1 : return false;
877 : }
878 34 : const auto &oRoot = oDoc.GetRoot();
879 68 : CPLJSONArray oCollections = oRoot.GetArray("collections");
880 34 : if (!oCollections.IsValid())
881 : {
882 2 : CPLError(CE_Failure, CPLE_AppDefined, "No collections array");
883 2 : return false;
884 : }
885 :
886 64 : const auto oGlobalCRSList = oRoot.GetArray("crs");
887 :
888 65 : for (int i = 0; i < oCollections.Size(); i++)
889 : {
890 33 : LoadJSONCollection(oCollections[i], oGlobalCRSList);
891 : }
892 :
893 32 : osResult.clear();
894 :
895 : // Paging is a (unspecified) extension to the core used by
896 : // https://{api_key}:@api.planet.com/analytics
897 64 : const auto oLinks = oRoot.GetArray("links");
898 32 : if (oLinks.IsValid())
899 : {
900 1 : CPLString osNextURL;
901 1 : int nCountRelNext = 0;
902 1 : for (int i = 0; i < oLinks.Size(); i++)
903 : {
904 1 : CPLJSONObject oLink = oLinks[i];
905 2 : if (!oLink.IsValid() ||
906 1 : oLink.GetType() != CPLJSONObject::Type::Object)
907 : {
908 0 : continue;
909 : }
910 1 : if (EQUAL(oLink.GetString("rel").c_str(), "next"))
911 : {
912 1 : osNextURL = oLink.GetString("href");
913 1 : nCountRelNext++;
914 2 : auto type = oLink.GetString("type");
915 1 : if (type == MEDIA_TYPE_GEOJSON || type == MEDIA_TYPE_JSON)
916 : {
917 1 : nCountRelNext = 1;
918 1 : break;
919 : }
920 : }
921 : }
922 1 : if (nCountRelNext == 1 && !osNextURL.empty())
923 : {
924 1 : CPLString osContentType;
925 1 : osNextURL = ResolveURL(osNextURL, osParentURL);
926 1 : osParentURL = osNextURL;
927 1 : if (!Download(osNextURL, MEDIA_TYPE_JSON, osResult,
928 : osContentType))
929 : {
930 0 : return false;
931 : }
932 : }
933 : }
934 : }
935 31 : return !m_apoLayers.empty();
936 : }
937 :
938 31 : void OGROAPIFDataset::DeterminePageSizeFromAPI(const std::string &itemsUrl)
939 : {
940 : // Try to get max limit from api
941 31 : int nMaximum{-1};
942 31 : int nDefault{-1};
943 : // Not sure if min should be considered
944 : //int nMinimum { -1 };
945 31 : std::string osAPIURL;
946 31 : const CPLJSONDocument &oDoc{GetAPIDoc(osAPIURL)};
947 31 : const auto &oRoot = oDoc.GetRoot();
948 :
949 31 : bool bFound{false};
950 :
951 : // limit from api document
952 31 : if (oRoot.IsValid())
953 : {
954 :
955 62 : const auto paths{oRoot.GetObj("paths")};
956 :
957 31 : if (paths.IsValid())
958 : {
959 :
960 10 : const auto pathName{itemsUrl.substr(m_osRootURL.length())};
961 10 : const auto path{paths.GetObj(pathName)};
962 :
963 10 : if (path.IsValid())
964 : {
965 :
966 16 : const auto parameters{path.GetArray("get/parameters")};
967 :
968 : // check $ref
969 15 : for (const auto ¶m : parameters)
970 : {
971 14 : const auto ref{param.GetString("$ref")};
972 7 : if (ref.find("limit") != std::string::npos)
973 : {
974 : // Examine ref
975 5 : if (ref.find("http") == 0 &&
976 5 : ref.find(".yml") == std::string::npos &&
977 1 : ref.find(".yaml") ==
978 : std::string::
979 : npos) // Remote document, skip yaml
980 : {
981 : // Only reinject auth if the URL matches
982 1 : auto limitUrl{ref.find(m_osRootURL) == 0
983 3 : ? ResolveURL(ref, osAPIURL)
984 2 : : ref};
985 1 : std::string fragment;
986 1 : const auto hashPos{limitUrl.find('#')};
987 1 : if (hashPos != std::string::npos)
988 : {
989 : // Remove leading #
990 1 : fragment = limitUrl.substr(hashPos + 1);
991 1 : limitUrl = limitUrl.substr(0, hashPos);
992 : }
993 1 : CPLString osResult;
994 1 : CPLString osContentType;
995 : // Do not limit accepted content-types, external resources may have any
996 1 : if (!Download(limitUrl, nullptr, osResult,
997 : osContentType))
998 : {
999 0 : CPLDebug("OAPIF",
1000 : "Could not download OPENAPI $ref: %s",
1001 : ref.c_str());
1002 0 : return;
1003 : }
1004 :
1005 : // We cannot trust the content-type, try JSON (YAML not implemented)
1006 :
1007 : // Try JSON
1008 2 : CPLJSONDocument oLimitDoc;
1009 1 : if (oLimitDoc.LoadMemory(osResult))
1010 : {
1011 2 : const auto oLimitRoot{oLimitDoc.GetRoot()};
1012 1 : if (oLimitRoot.IsValid())
1013 : {
1014 : const auto oLimit{
1015 2 : oLimitRoot.GetObj(fragment)};
1016 1 : if (oLimit.IsValid())
1017 : {
1018 1 : nMaximum = oLimit.GetInteger(
1019 : "schema/maximum", -1);
1020 : //nMinimum = oLimit.GetInteger( "schema/minimum", -1 );
1021 1 : nDefault = oLimit.GetInteger(
1022 : "schema/default", -1);
1023 1 : bFound = true;
1024 : }
1025 : }
1026 : }
1027 : }
1028 3 : else if (ref.find('#') == 0) // Local ref
1029 : {
1030 6 : const auto oLimit{oRoot.GetObj(ref.substr(1))};
1031 3 : if (oLimit.IsValid())
1032 : {
1033 3 : nMaximum =
1034 3 : oLimit.GetInteger("schema/maximum", -1);
1035 : //nMinimum = oLimit.GetInteger( "schema/minimum", -1 );
1036 3 : nDefault =
1037 3 : oLimit.GetInteger("schema/default", -1);
1038 3 : bFound = true;
1039 : }
1040 : }
1041 : else
1042 : {
1043 0 : CPLDebug("OAPIF", "Could not open OPENAPI $ref: %s",
1044 : ref.c_str());
1045 : }
1046 : }
1047 : }
1048 : }
1049 : }
1050 : }
1051 :
1052 31 : if (bFound)
1053 : {
1054 : // Initially set to GDAL's default (1000)
1055 4 : int pageSize{m_nPageSize};
1056 4 : if (nDefault > 0 && nMaximum > 0)
1057 : {
1058 : // Use the default, but if it is below GDAL's default (1000), aim for 1000
1059 : // but clamp to the maximum limit
1060 4 : pageSize = std::min(std::max(pageSize, nDefault), nMaximum);
1061 : }
1062 0 : else if (nDefault > 0)
1063 0 : pageSize = std::max(pageSize, nDefault);
1064 0 : else if (nMaximum > 0)
1065 0 : pageSize = nMaximum;
1066 :
1067 4 : if (m_nPageSize != pageSize)
1068 : {
1069 2 : CPLDebug("OAPIF", "Page size set from OPENAPI schema: %d",
1070 : pageSize);
1071 2 : m_nPageSize = pageSize;
1072 : }
1073 : }
1074 : }
1075 :
1076 : /************************************************************************/
1077 : /* ConcatenateURLParts() */
1078 : /************************************************************************/
1079 :
1080 72 : static std::string ConcatenateURLParts(const std::string &osPart1,
1081 : const std::string &osPart2)
1082 : {
1083 72 : if (!osPart1.empty() && osPart1.back() == '/' && !osPart2.empty() &&
1084 0 : osPart2.front() == '/')
1085 : {
1086 0 : return osPart1.substr(0, osPart1.size() - 1) + osPart2;
1087 : }
1088 72 : return osPart1 + osPart2;
1089 : }
1090 :
1091 : /************************************************************************/
1092 : /* Open() */
1093 : /************************************************************************/
1094 :
1095 42 : bool OGROAPIFDataset::Open(GDALOpenInfo *poOpenInfo)
1096 : {
1097 84 : CPLString osCollectionDescURL;
1098 :
1099 42 : m_osRootURL = CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "URL",
1100 42 : poOpenInfo->pszFilename);
1101 42 : if (STARTS_WITH_CI(m_osRootURL, "WFS3:"))
1102 1 : m_osRootURL = m_osRootURL.substr(strlen("WFS3:"));
1103 41 : else if (STARTS_WITH_CI(m_osRootURL, "OAPIF:"))
1104 37 : m_osRootURL = m_osRootURL.substr(strlen("OAPIF:"));
1105 4 : else if (STARTS_WITH_CI(m_osRootURL, "OAPIF_COLLECTION:"))
1106 : {
1107 : // Used by the OGCAPI driver
1108 2 : osCollectionDescURL = m_osRootURL.substr(strlen("OAPIF_COLLECTION:"));
1109 2 : m_osRootURL = osCollectionDescURL;
1110 : }
1111 :
1112 42 : const auto nPosQuestionMark = m_osRootURL.find('?');
1113 42 : if (nPosQuestionMark != std::string::npos)
1114 : {
1115 3 : m_osUserQueryParams = m_osRootURL.substr(nPosQuestionMark + 1);
1116 3 : m_osRootURL.resize(nPosQuestionMark);
1117 : }
1118 :
1119 42 : const auto nCollectionsPos = m_osRootURL.find("/collections/");
1120 42 : if (nCollectionsPos != std::string::npos)
1121 : {
1122 4 : if (osCollectionDescURL.empty())
1123 2 : osCollectionDescURL = m_osRootURL;
1124 4 : m_osRootURL.resize(nCollectionsPos);
1125 : }
1126 :
1127 : // m_osServerBaseURL is just the "https://example.com" part from
1128 : // "https://example.com/foo/bar"
1129 42 : m_osServerBaseURL = m_osRootURL;
1130 : {
1131 42 : const char *pszStr = m_osServerBaseURL.c_str();
1132 42 : const char *pszPtr = pszStr;
1133 42 : if (STARTS_WITH(pszPtr, "http://"))
1134 42 : pszPtr += strlen("http://");
1135 0 : else if (STARTS_WITH(pszPtr, "https://"))
1136 0 : pszPtr += strlen("https://");
1137 42 : pszPtr = strchr(pszPtr, '/');
1138 42 : if (pszPtr)
1139 42 : m_osServerBaseURL.assign(pszStr, pszPtr - pszStr);
1140 : }
1141 :
1142 42 : m_bIgnoreSchema = CPLTestBool(CSLFetchNameValueDef(
1143 42 : poOpenInfo->papszOpenOptions, "IGNORE_SCHEMA", "FALSE"));
1144 :
1145 84 : const int pageSize = atoi(
1146 42 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "PAGE_SIZE", "-1"));
1147 :
1148 42 : if (pageSize > 0)
1149 : {
1150 0 : m_nPageSize = pageSize;
1151 0 : m_bPageSizeSetFromOpenOptions = true;
1152 : }
1153 :
1154 : m_osDateTime =
1155 42 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "DATETIME", "");
1156 :
1157 84 : const int initialRequestPageSize = atoi(CSLFetchNameValueDef(
1158 42 : poOpenInfo->papszOpenOptions, "INITIAL_REQUEST_PAGE_SIZE", "-1"));
1159 :
1160 42 : if (initialRequestPageSize >= 1)
1161 : {
1162 2 : m_nInitialRequestPageSize = initialRequestPageSize;
1163 : }
1164 :
1165 : m_osUserPwd =
1166 42 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "USERPWD", "");
1167 : std::string osCRS =
1168 84 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "CRS", "");
1169 : std::string osPreferredCRS =
1170 84 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "PREFERRED_CRS", "");
1171 42 : if (!osCRS.empty())
1172 : {
1173 2 : if (!osPreferredCRS.empty())
1174 : {
1175 0 : CPLError(
1176 : CE_Failure, CPLE_AppDefined,
1177 : "CRS and PREFERRED_CRS open options are mutually exclusive.");
1178 0 : return false;
1179 : }
1180 2 : m_osAskedCRS = osCRS;
1181 2 : if (m_oAskedCRS.SetFromUserInput(
1182 : osCRS.c_str(),
1183 2 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
1184 : OGRERR_NONE)
1185 : {
1186 0 : CPLError(CE_Failure, CPLE_AppDefined, "Invalid value for CRS");
1187 0 : return false;
1188 : }
1189 2 : m_bAskedCRSIsRequired = true;
1190 : }
1191 40 : else if (!osPreferredCRS.empty())
1192 : {
1193 2 : m_osAskedCRS = osPreferredCRS;
1194 2 : if (m_oAskedCRS.SetFromUserInput(
1195 : osPreferredCRS.c_str(),
1196 2 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
1197 : OGRERR_NONE)
1198 : {
1199 0 : CPLError(CE_Failure, CPLE_AppDefined,
1200 : "Invalid value for PREFERRED_CRS");
1201 0 : return false;
1202 : }
1203 : }
1204 :
1205 42 : m_bServerFeaturesAxisOrderGISFriendly =
1206 42 : EQUAL(CSLFetchNameValueDef(poOpenInfo->papszOpenOptions,
1207 : "SERVER_FEATURE_AXIS_ORDER",
1208 : "AUTHORITY_COMPLIANT"),
1209 : "GIS_FRIENDLY");
1210 :
1211 84 : CPLString osResult;
1212 84 : CPLString osContentType;
1213 :
1214 42 : if (!osCollectionDescURL.empty())
1215 : {
1216 4 : if (!Download(osCollectionDescURL, MEDIA_TYPE_JSON, osResult,
1217 : osContentType))
1218 : {
1219 0 : return false;
1220 : }
1221 8 : CPLJSONDocument oDoc;
1222 4 : if (!oDoc.LoadMemory(osResult))
1223 : {
1224 0 : return false;
1225 : }
1226 4 : const auto &oRoot = oDoc.GetRoot();
1227 4 : return LoadJSONCollection(oRoot, CPLJSONArray());
1228 : }
1229 :
1230 : const std::string osCollectionsURL(
1231 114 : ConcatenateURLParts(m_osRootURL, "/collections"));
1232 38 : if (!Download(osCollectionsURL, MEDIA_TYPE_JSON, osResult, osContentType))
1233 : {
1234 4 : return false;
1235 : }
1236 :
1237 34 : if (osContentType.find("json") != std::string::npos)
1238 : {
1239 34 : return LoadJSONCollections(osResult, osCollectionsURL);
1240 : }
1241 :
1242 0 : return true;
1243 : }
1244 :
1245 : /************************************************************************/
1246 : /* GetLayer() */
1247 : /************************************************************************/
1248 :
1249 37 : OGRLayer *OGROAPIFDataset::GetLayer(int nIndex)
1250 : {
1251 37 : if (nIndex < 0 || nIndex >= GetLayerCount())
1252 0 : return nullptr;
1253 37 : return m_apoLayers[nIndex].get();
1254 : }
1255 :
1256 : /************************************************************************/
1257 : /* Identify() */
1258 : /************************************************************************/
1259 :
1260 51906 : static int OGROAPIFDriverIdentify(GDALOpenInfo *poOpenInfo)
1261 :
1262 : {
1263 103810 : return STARTS_WITH_CI(poOpenInfo->pszFilename, "WFS3:") ||
1264 51904 : STARTS_WITH_CI(poOpenInfo->pszFilename, "OAPIF:") ||
1265 155636 : STARTS_WITH_CI(poOpenInfo->pszFilename, "OAPIF_COLLECTION:") ||
1266 51826 : (poOpenInfo->IsSingleAllowedDriver("OAPIF") &&
1267 4 : (STARTS_WITH(poOpenInfo->pszFilename, "http://") ||
1268 51906 : STARTS_WITH(poOpenInfo->pszFilename, "https://")));
1269 : }
1270 :
1271 : /************************************************************************/
1272 : /* HasGISFriendlyAxisOrder() */
1273 : /************************************************************************/
1274 :
1275 20 : static bool HasGISFriendlyAxisOrder(const OGRSpatialReference *poSRS)
1276 : {
1277 20 : const auto &axisMapping = poSRS->GetDataAxisToSRSAxisMapping();
1278 38 : return axisMapping.size() >= 2 && axisMapping[0] == 1 &&
1279 38 : axisMapping[1] == 2;
1280 : }
1281 :
1282 : /************************************************************************/
1283 : /* OGROAPIFLayer() */
1284 : /************************************************************************/
1285 :
1286 34 : OGROAPIFLayer::OGROAPIFLayer(OGROAPIFDataset *poDS, const CPLString &osName,
1287 : const CPLJSONArray &oBBOX,
1288 : const std::string &osBBOXCrs,
1289 : std::vector<std::string> &&oCRSList,
1290 : const std::string &osActiveCRS,
1291 : double dfCoordinateEpoch,
1292 34 : const CPLJSONArray &oLinks)
1293 34 : : m_poDS(poDS)
1294 : {
1295 34 : m_poFeatureDefn = new OGRFeatureDefn(osName);
1296 34 : m_poFeatureDefn->Reference();
1297 34 : SetDescription(osName);
1298 34 : m_oSupportedCRSList = std::move(oCRSList);
1299 :
1300 34 : OGRSpatialReference *poSRS = new OGRSpatialReference();
1301 68 : poSRS->SetFromUserInput(
1302 34 : !osActiveCRS.empty() ? osActiveCRS.c_str() : SRS_WKT_WGS84_LAT_LONG,
1303 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
1304 34 : poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1305 34 : m_bIsGeographicCRS = poSRS->IsGeographic();
1306 34 : m_bCRSHasGISFriendlyOrder =
1307 34 : osActiveCRS.empty() || HasGISFriendlyAxisOrder(poSRS);
1308 34 : m_osActiveCRS = osActiveCRS;
1309 34 : if (dfCoordinateEpoch > 0)
1310 2 : poSRS->SetCoordinateEpoch(dfCoordinateEpoch);
1311 34 : m_poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(poSRS);
1312 :
1313 34 : poSRS->Release();
1314 :
1315 34 : if (oBBOX.IsValid() && oBBOX.Size() > 0)
1316 : {
1317 20 : CPLJSONArray oRealBBOX;
1318 : // In the final 1.0.0 spec, spatial.bbox is an array (normally with
1319 : // a single element) of 4-element arrays
1320 10 : if (oBBOX[0].GetType() == CPLJSONObject::Type::Array)
1321 : {
1322 3 : oRealBBOX = oBBOX[0].ToArray();
1323 : }
1324 : #ifndef REMOVE_SUPPORT_FOR_OLD_VERSIONS
1325 7 : else if (oBBOX.Size() == 4 || oBBOX.Size() == 6)
1326 : {
1327 7 : oRealBBOX = oBBOX;
1328 : }
1329 : #endif
1330 10 : if (oRealBBOX.Size() == 4 || oRealBBOX.Size() == 6)
1331 : {
1332 10 : m_oOriginalExtent.MinX = oRealBBOX[0].ToDouble();
1333 10 : m_oOriginalExtent.MinY = oRealBBOX[1].ToDouble();
1334 10 : m_oOriginalExtent.MaxX =
1335 10 : oRealBBOX[oRealBBOX.Size() == 6 ? 3 : 2].ToDouble();
1336 10 : m_oOriginalExtent.MaxY =
1337 10 : oRealBBOX[oRealBBOX.Size() == 6 ? 4 : 3].ToDouble();
1338 :
1339 20 : m_oOriginalExtentCRS.SetFromUserInput(
1340 10 : !osBBOXCrs.empty() ? osBBOXCrs.c_str() : OGC_CRS84_WKT,
1341 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get());
1342 :
1343 : // Handle bbox over antimeridian, which we do not support properly
1344 : // in OGR
1345 10 : if (m_oOriginalExtentCRS.IsGeographic())
1346 : {
1347 : const bool bSwitchXY =
1348 10 : !HasGISFriendlyAxisOrder(&m_oOriginalExtentCRS);
1349 10 : if (bSwitchXY)
1350 : {
1351 0 : std::swap(m_oOriginalExtent.MinX, m_oOriginalExtent.MinY);
1352 0 : std::swap(m_oOriginalExtent.MaxX, m_oOriginalExtent.MaxY);
1353 : }
1354 :
1355 10 : if (m_oOriginalExtent.MinX > m_oOriginalExtent.MaxX &&
1356 0 : fabs(m_oOriginalExtent.MinX) <= 180.0 &&
1357 0 : fabs(m_oOriginalExtent.MaxX) <= 180.0)
1358 : {
1359 0 : m_oOriginalExtent.MinX = -180.0;
1360 0 : m_oOriginalExtent.MaxX = 180.0;
1361 : }
1362 :
1363 10 : if (bSwitchXY)
1364 : {
1365 0 : std::swap(m_oOriginalExtent.MinX, m_oOriginalExtent.MinY);
1366 0 : std::swap(m_oOriginalExtent.MaxX, m_oOriginalExtent.MaxY);
1367 : }
1368 : }
1369 : }
1370 : }
1371 :
1372 : // Default to what the spec mandates for the /items URL, but check links
1373 : // later
1374 34 : m_osURL = ConcatenateURLParts(m_poDS->m_osRootURL,
1375 68 : "/collections/" + osName + "/items");
1376 68 : const std::string osParentURL(m_osURL);
1377 34 : m_osPath = "/collections/" + osName + "/items";
1378 :
1379 34 : if (oLinks.IsValid())
1380 : {
1381 76 : for (int i = 0; i < oLinks.Size(); i++)
1382 : {
1383 72 : CPLJSONObject oLink = oLinks[i];
1384 144 : if (!oLink.IsValid() ||
1385 72 : oLink.GetType() != CPLJSONObject::Type::Object)
1386 : {
1387 0 : continue;
1388 : }
1389 216 : const auto osRel(oLink.GetString("rel"));
1390 216 : const auto osURL = oLink.GetString("href");
1391 216 : const auto type = oLink.GetString("type");
1392 72 : if (EQUAL(osRel.c_str(), "describedby"))
1393 : {
1394 4 : if (type == MEDIA_TYPE_TEXT_XML ||
1395 2 : type == MEDIA_TYPE_APPLICATION_XML)
1396 : {
1397 1 : m_osDescribedByURL = osURL;
1398 1 : m_osDescribedByType = type;
1399 1 : m_bDescribedByIsXML = true;
1400 : }
1401 2 : else if (type == MEDIA_TYPE_JSON_SCHEMA &&
1402 1 : m_osDescribedByURL.empty())
1403 : {
1404 1 : m_osDescribedByURL = osURL;
1405 1 : m_osDescribedByType = type;
1406 1 : m_bDescribedByIsXML = false;
1407 : }
1408 : }
1409 70 : else if (EQUAL(osRel.c_str(), "queryables"))
1410 : {
1411 0 : if (type == MEDIA_TYPE_JSON || m_osQueryablesURL.empty())
1412 : {
1413 0 : m_osQueryablesURL = m_poDS->ResolveURL(osURL, osParentURL);
1414 : }
1415 : }
1416 70 : else if (EQUAL(osRel.c_str(), "items"))
1417 : {
1418 12 : if (type == MEDIA_TYPE_GEOJSON)
1419 : {
1420 2 : m_osURL = m_poDS->ResolveURL(osURL, osParentURL);
1421 : }
1422 : }
1423 : }
1424 4 : if (!m_osDescribedByURL.empty())
1425 : {
1426 : m_osDescribedByURL =
1427 2 : m_poDS->ResolveURL(m_osDescribedByURL, osParentURL);
1428 : }
1429 : }
1430 :
1431 34 : OGROAPIFLayer::ResetReading();
1432 34 : }
1433 :
1434 : /************************************************************************/
1435 : /* ~OGROAPIFLayer() */
1436 : /************************************************************************/
1437 :
1438 68 : OGROAPIFLayer::~OGROAPIFLayer()
1439 : {
1440 34 : m_poFeatureDefn->Release();
1441 68 : }
1442 :
1443 : /************************************************************************/
1444 : /* GetSupportedSRSList() */
1445 : /************************************************************************/
1446 :
1447 : const OGRLayer::GetSupportedSRSListRetType &
1448 5 : OGROAPIFLayer::GetSupportedSRSList(int /*iGeomField*/)
1449 : {
1450 5 : if (!m_oSupportedCRSList.empty() && m_apoSupportedCRSList.empty())
1451 : {
1452 6 : for (const auto &osCRS : m_oSupportedCRSList)
1453 : {
1454 : auto poSRS = std::unique_ptr<OGRSpatialReference,
1455 : OGRSpatialReferenceReleaser>(
1456 8 : new OGRSpatialReference());
1457 4 : if (poSRS->SetFromUserInput(
1458 : osCRS.c_str(),
1459 : OGRSpatialReference::
1460 4 : SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
1461 : {
1462 4 : m_apoSupportedCRSList.emplace_back(std::move(poSRS));
1463 : }
1464 : }
1465 : }
1466 5 : return m_apoSupportedCRSList;
1467 : }
1468 :
1469 : /************************************************************************/
1470 : /* SetActiveSRS() */
1471 : /************************************************************************/
1472 :
1473 5 : OGRErr OGROAPIFLayer::SetActiveSRS(int /*iGeomField*/,
1474 : const OGRSpatialReference *poSRS)
1475 : {
1476 5 : if (poSRS == nullptr)
1477 1 : return OGRERR_FAILURE;
1478 4 : const char *const apszOptions[] = {
1479 : "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
1480 7 : for (const auto &osCRS : m_oSupportedCRSList)
1481 : {
1482 6 : OGRSpatialReference oTmpSRS;
1483 6 : if (oTmpSRS.SetFromUserInput(
1484 : osCRS.c_str(),
1485 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) ==
1486 12 : OGRERR_NONE &&
1487 6 : oTmpSRS.IsSame(poSRS, apszOptions))
1488 : {
1489 3 : m_osActiveCRS = osCRS;
1490 3 : auto poGeomFieldDefn = m_poFeatureDefn->GetGeomFieldDefn(0);
1491 3 : if (poGeomFieldDefn)
1492 : {
1493 3 : OGRSpatialReference *poSRSClone = poSRS->Clone();
1494 3 : poSRSClone->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
1495 3 : poGeomFieldDefn->SetSpatialRef(poSRSClone);
1496 3 : m_bIsGeographicCRS = poSRSClone->IsGeographic();
1497 3 : m_bCRSHasGISFriendlyOrder = HasGISFriendlyAxisOrder(poSRSClone);
1498 3 : poSRSClone->Release();
1499 : }
1500 3 : m_oExtent = OGREnvelope();
1501 3 : SetSpatialFilter(nullptr);
1502 3 : ResetReading();
1503 3 : return OGRERR_NONE;
1504 : }
1505 : }
1506 1 : return OGRERR_FAILURE;
1507 : }
1508 :
1509 : /************************************************************************/
1510 : /* ComputeExtent() */
1511 : /************************************************************************/
1512 :
1513 8 : void OGROAPIFLayer::ComputeExtent()
1514 : {
1515 8 : m_oExtent = m_oOriginalExtent;
1516 8 : const auto poGeomFieldDefn = m_poFeatureDefn->GetGeomFieldDefn(0);
1517 8 : if (poGeomFieldDefn)
1518 : {
1519 8 : const OGRSpatialReference *poSRS = poGeomFieldDefn->GetSpatialRef();
1520 8 : if (poSRS && !poSRS->IsSame(&m_oOriginalExtentCRS))
1521 : {
1522 : auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
1523 8 : OGRCreateCoordinateTransformation(&m_oOriginalExtentCRS,
1524 16 : poSRS));
1525 8 : if (poCT)
1526 : {
1527 8 : poCT->TransformBounds(
1528 : m_oOriginalExtent.MinX, m_oOriginalExtent.MinY,
1529 : m_oOriginalExtent.MaxX, m_oOriginalExtent.MaxY,
1530 : &m_oExtent.MinX, &m_oExtent.MinY, &m_oExtent.MaxX,
1531 8 : &m_oExtent.MaxY, 20);
1532 : }
1533 : }
1534 : }
1535 8 : }
1536 :
1537 : /************************************************************************/
1538 : /* SetItemAssets() */
1539 : /************************************************************************/
1540 :
1541 1 : void OGROAPIFLayer::SetItemAssets(const CPLJSONObject &oItemAssets)
1542 : {
1543 2 : auto oChildren = oItemAssets.GetChildren();
1544 3 : for (const auto &oItemAsset : oChildren)
1545 : {
1546 2 : m_aosItemAssetNames.emplace_back(oItemAsset.GetName());
1547 : }
1548 1 : }
1549 :
1550 : /************************************************************************/
1551 : /* ResolveRefs() */
1552 : /************************************************************************/
1553 :
1554 205 : static CPLJSONObject ResolveRefs(const CPLJSONObject &oRoot,
1555 : const CPLJSONObject &oObj)
1556 : {
1557 615 : const auto osRef = oObj.GetString("$ref");
1558 205 : if (osRef.empty())
1559 179 : return oObj;
1560 26 : if (STARTS_WITH(osRef.c_str(), "#/"))
1561 : {
1562 25 : return oRoot.GetObj(osRef.c_str() + 2);
1563 : }
1564 2 : CPLJSONObject oInvalid;
1565 1 : oInvalid.Deinit();
1566 1 : return oInvalid;
1567 : }
1568 :
1569 : /************************************************************************/
1570 : /* BuildExampleRecursively() */
1571 : /************************************************************************/
1572 :
1573 205 : static bool BuildExampleRecursively(CPLJSONObject &oRes,
1574 : const CPLJSONObject &oRoot,
1575 : const CPLJSONObject &oObjIn)
1576 : {
1577 410 : auto oResolvedObj = ResolveRefs(oRoot, oObjIn);
1578 205 : if (!oResolvedObj.IsValid())
1579 1 : return false;
1580 612 : const auto osType = oResolvedObj.GetString("type");
1581 204 : if (osType == "object")
1582 : {
1583 87 : const auto oAllOf = oResolvedObj.GetArray("allOf");
1584 58 : const auto oProperties = oResolvedObj.GetObj("properties");
1585 29 : if (oAllOf.IsValid())
1586 : {
1587 13 : for (int i = 0; i < oAllOf.Size(); i++)
1588 : {
1589 20 : CPLJSONObject oChildRes;
1590 20 : if (BuildExampleRecursively(oChildRes, oRoot, oAllOf[i]) &&
1591 10 : oChildRes.GetType() == CPLJSONObject::Type::Object)
1592 : {
1593 20 : auto oChildren = oChildRes.GetChildren();
1594 89 : for (const auto &oChild : oChildren)
1595 : {
1596 79 : oRes.Add(oChild.GetName(), oChild);
1597 : }
1598 : }
1599 : }
1600 : }
1601 26 : else if (oProperties.IsValid())
1602 : {
1603 50 : auto oChildren = oProperties.GetChildren();
1604 206 : for (const auto &oChild : oChildren)
1605 : {
1606 362 : CPLJSONObject oChildRes;
1607 181 : if (BuildExampleRecursively(oChildRes, oRoot, oChild))
1608 : {
1609 180 : oRes.Add(oChild.GetName(), oChildRes);
1610 : }
1611 : else
1612 : {
1613 1 : oRes.Add(oChild.GetName(), "unknown type");
1614 : }
1615 : }
1616 : }
1617 29 : return true;
1618 : }
1619 175 : else if (osType == "array")
1620 : {
1621 26 : CPLJSONArray oArray;
1622 26 : const auto oItems = oResolvedObj.GetObj("items");
1623 13 : if (oItems.IsValid())
1624 : {
1625 26 : CPLJSONObject oChildRes;
1626 13 : if (BuildExampleRecursively(oChildRes, oRoot, oItems))
1627 : {
1628 12 : oArray.Add(oChildRes);
1629 : }
1630 : }
1631 13 : oRes = std::move(oArray);
1632 13 : return true;
1633 : }
1634 162 : else if (osType == "string")
1635 : {
1636 234 : CPLJSONObject oTemp;
1637 234 : const auto osFormat = oResolvedObj.GetString("format");
1638 117 : if (!osFormat.empty())
1639 27 : oTemp.Set("_", osFormat);
1640 : else
1641 90 : oTemp.Set("_", "string");
1642 117 : oRes = oTemp.GetObj("_");
1643 117 : return true;
1644 : }
1645 45 : else if (osType == "number")
1646 : {
1647 30 : CPLJSONObject oTemp;
1648 30 : oTemp.Set("_", 1.25);
1649 30 : oRes = oTemp.GetObj("_");
1650 30 : return true;
1651 : }
1652 15 : else if (osType == "integer")
1653 : {
1654 14 : CPLJSONObject oTemp;
1655 14 : oTemp.Set("_", 1);
1656 14 : oRes = oTemp.GetObj("_");
1657 14 : return true;
1658 : }
1659 1 : else if (osType == "boolean")
1660 : {
1661 0 : CPLJSONObject oTemp;
1662 0 : oTemp.Set("_", true);
1663 0 : oRes = oTemp.GetObj("_");
1664 0 : return true;
1665 : }
1666 1 : else if (osType == "null")
1667 : {
1668 0 : CPLJSONObject oTemp;
1669 0 : oTemp.SetNull("_");
1670 0 : oRes = oTemp.GetObj("_");
1671 0 : return true;
1672 : }
1673 :
1674 1 : return false;
1675 : }
1676 :
1677 : /************************************************************************/
1678 : /* GetObjectExampleFromSchema() */
1679 : /************************************************************************/
1680 :
1681 1 : static CPLJSONObject GetObjectExampleFromSchema(const std::string &osJSONSchema)
1682 : {
1683 2 : CPLJSONDocument oDoc;
1684 1 : if (!oDoc.LoadMemory(osJSONSchema))
1685 : {
1686 0 : CPLJSONObject oInvalid;
1687 0 : oInvalid.Deinit();
1688 0 : return oInvalid;
1689 : }
1690 2 : const auto &oRoot = oDoc.GetRoot();
1691 2 : CPLJSONObject oRes;
1692 1 : BuildExampleRecursively(oRes, oRoot, oRoot);
1693 1 : return oRes;
1694 : }
1695 :
1696 : /************************************************************************/
1697 : /* GetSchema() */
1698 : /************************************************************************/
1699 :
1700 31 : void OGROAPIFLayer::GetSchema()
1701 : {
1702 31 : if (m_osDescribedByURL.empty() || m_poDS->m_bIgnoreSchema)
1703 29 : return;
1704 :
1705 4 : CPLErrorStateBackuper oErrorStateBackuper(CPLQuietErrorHandler);
1706 :
1707 2 : if (m_bDescribedByIsXML)
1708 : {
1709 2 : std::vector<GMLFeatureClass *> apoClasses;
1710 1 : bool bFullyUnderstood = false;
1711 1 : bool bUseSchemaImports = false;
1712 1 : bool bHaveSchema = GMLParseXSD(m_osDescribedByURL, bUseSchemaImports,
1713 : apoClasses, bFullyUnderstood);
1714 1 : if (bHaveSchema && apoClasses.size() == 1)
1715 : {
1716 1 : CPLDebug("OAPIF", "Using XML schema");
1717 1 : auto poGMLFeatureClass = apoClasses[0];
1718 1 : if (poGMLFeatureClass->GetGeometryPropertyCount() == 1)
1719 : {
1720 : // Force linear type as we work with GeoJSON data
1721 1 : m_poFeatureDefn->SetGeomType(
1722 : OGR_GT_GetLinear(static_cast<OGRwkbGeometryType>(
1723 1 : poGMLFeatureClass->GetGeometryProperty(0)->GetType())));
1724 : }
1725 :
1726 1 : const int nPropertyCount = poGMLFeatureClass->GetPropertyCount();
1727 : // This is a hack for
1728 : // http://www.pvretano.com/cubewerx/cubeserv/default/wfs/3.0.0/framework/collections/UNINCORPORATED_PL/schema
1729 : // The GML representation has attributes starting all with
1730 : // "UNINCORPORATED_PL." whereas the GeoJSON output not
1731 2 : CPLString osPropertyNamePrefix(GetName());
1732 1 : osPropertyNamePrefix += '.';
1733 1 : bool bAllPrefixed = true;
1734 2 : for (int iField = 0; iField < nPropertyCount; iField++)
1735 : {
1736 1 : const auto poProperty = poGMLFeatureClass->GetProperty(iField);
1737 1 : if (!STARTS_WITH(poProperty->GetName(),
1738 : osPropertyNamePrefix.c_str()))
1739 : {
1740 1 : bAllPrefixed = false;
1741 : }
1742 : }
1743 2 : for (int iField = 0; iField < nPropertyCount; iField++)
1744 : {
1745 1 : const auto poProperty = poGMLFeatureClass->GetProperty(iField);
1746 1 : OGRFieldSubType eSubType = OFSTNone;
1747 : const OGRFieldType eFType =
1748 1 : GML_GetOGRFieldType(poProperty->GetType(), eSubType);
1749 :
1750 : const char *pszName =
1751 1 : poProperty->GetName() +
1752 0 : (bAllPrefixed ? osPropertyNamePrefix.size() : 0);
1753 2 : auto poField = std::make_unique<OGRFieldDefn>(pszName, eFType);
1754 1 : poField->SetSubType(eSubType);
1755 1 : m_apoFieldsFromSchema.emplace_back(std::move(poField));
1756 : }
1757 : }
1758 :
1759 2 : for (auto poFeatureClass : apoClasses)
1760 1 : delete poFeatureClass;
1761 : }
1762 : else
1763 : {
1764 2 : CPLString osContentType;
1765 2 : CPLString osResult;
1766 1 : if (!m_poDS->Download(m_osDescribedByURL, m_osDescribedByType, osResult,
1767 : osContentType))
1768 : {
1769 0 : CPLDebug("OAPIF", "Could not download schema");
1770 : }
1771 : else
1772 : {
1773 2 : const auto oExample = GetObjectExampleFromSchema(osResult);
1774 : // CPLDebug("OAPIF", "Example from schema: %s",
1775 : // oExample.Format(CPLJSONObject::PrettyFormat::Pretty).c_str());
1776 2 : if (oExample.IsValid() &&
1777 1 : oExample.GetType() == CPLJSONObject::Type::Object)
1778 : {
1779 3 : const auto oProperties = oExample.GetObj("properties");
1780 2 : if (oProperties.IsValid() &&
1781 1 : oProperties.GetType() == CPLJSONObject::Type::Object)
1782 : {
1783 1 : CPLDebug("OAPIF", "Using JSON schema");
1784 2 : const auto oProps = oProperties.GetChildren();
1785 19 : for (const auto &oProp : oProps)
1786 : {
1787 18 : OGRFieldType eType = OFTString;
1788 18 : OGRFieldSubType eSubType = OFSTNone;
1789 18 : const auto oType = oProp.GetType();
1790 18 : if (oType == CPLJSONObject::Type::String)
1791 : {
1792 13 : if (oProp.ToString() == "date-time")
1793 : {
1794 4 : eType = OFTDateTime;
1795 : }
1796 9 : else if (oProp.ToString() == "date")
1797 : {
1798 0 : eType = OFTDate;
1799 : }
1800 : }
1801 5 : else if (oType == CPLJSONObject::Type::Boolean)
1802 : {
1803 0 : eType = OFTInteger;
1804 0 : eSubType = OFSTBoolean;
1805 : }
1806 5 : else if (oType == CPLJSONObject::Type::Double)
1807 : {
1808 0 : eType = OFTReal;
1809 : }
1810 5 : else if (oType == CPLJSONObject::Type::Integer)
1811 : {
1812 0 : eType = OFTInteger;
1813 : }
1814 5 : else if (oType == CPLJSONObject::Type::Long)
1815 : {
1816 0 : eType = OFTInteger64;
1817 : }
1818 5 : else if (oType == CPLJSONObject::Type::Array)
1819 : {
1820 4 : const auto oArray = oProp.ToArray();
1821 2 : if (oArray.Size() > 0)
1822 : {
1823 1 : if (oArray[0].GetType() ==
1824 : CPLJSONObject::Type::String)
1825 0 : eType = OFTStringList;
1826 1 : else if (oArray[0].GetType() ==
1827 : CPLJSONObject::Type::Integer)
1828 0 : eType = OFTIntegerList;
1829 : }
1830 : }
1831 :
1832 : auto poField = std::make_unique<OGRFieldDefn>(
1833 36 : oProp.GetName().c_str(), eType);
1834 18 : poField->SetSubType(eSubType);
1835 18 : m_apoFieldsFromSchema.emplace_back(std::move(poField));
1836 : }
1837 : }
1838 : }
1839 : }
1840 : }
1841 : }
1842 :
1843 : /************************************************************************/
1844 : /* GetLayerDefn() */
1845 : /************************************************************************/
1846 :
1847 140 : OGRFeatureDefn *OGROAPIFLayer::GetLayerDefn()
1848 : {
1849 140 : if (!m_bFeatureDefnEstablished)
1850 26 : EstablishFeatureDefn();
1851 140 : return m_poFeatureDefn;
1852 : }
1853 :
1854 : /************************************************************************/
1855 : /* EstablishFeatureDefn() */
1856 : /************************************************************************/
1857 :
1858 31 : void OGROAPIFLayer::EstablishFeatureDefn()
1859 : {
1860 31 : CPLAssert(!m_bFeatureDefnEstablished);
1861 31 : m_bFeatureDefnEstablished = true;
1862 :
1863 31 : GetSchema();
1864 :
1865 31 : if (!m_poDS->m_bPageSizeSetFromOpenOptions)
1866 : {
1867 31 : const int nOldPageSize{m_poDS->m_nPageSize};
1868 31 : m_poDS->DeterminePageSizeFromAPI(m_osURL);
1869 : // cppcheck-suppress knownConditionTrueFalse
1870 31 : if (nOldPageSize != m_poDS->m_nPageSize)
1871 : {
1872 4 : m_osGetURL = CPLURLAddKVP(m_osGetURL, "limit",
1873 4 : CPLSPrintf("%d", m_poDS->m_nPageSize));
1874 : }
1875 : }
1876 :
1877 31 : CPLJSONDocument oDoc;
1878 31 : CPLString osURL(m_osURL);
1879 :
1880 62 : osURL = CPLURLAddKVP(
1881 : osURL, "limit",
1882 31 : CPLSPrintf("%d", std::min(m_poDS->m_nInitialRequestPageSize,
1883 62 : m_poDS->m_nPageSize)));
1884 31 : if (!m_poDS->DownloadJSon(osURL, oDoc))
1885 0 : return;
1886 :
1887 31 : const CPLString osTmpFilename(VSIMemGenerateHiddenFilename("oapif.json"));
1888 31 : oDoc.Save(osTmpFilename);
1889 : std::unique_ptr<GDALDataset> poDS(GDALDataset::FromHandle(
1890 : GDALOpenEx(osTmpFilename, GDAL_OF_VECTOR | GDAL_OF_INTERNAL, nullptr,
1891 31 : nullptr, nullptr)));
1892 31 : VSIUnlink(osTmpFilename);
1893 31 : if (!poDS.get())
1894 1 : return;
1895 30 : OGRLayer *poLayer = poDS->GetLayer(0);
1896 30 : if (!poLayer)
1897 0 : return;
1898 30 : OGRFeatureDefn *poFeatureDefn = poLayer->GetLayerDefn();
1899 30 : if (m_poFeatureDefn->GetGeomType() == wkbUnknown)
1900 : {
1901 29 : m_poFeatureDefn->SetGeomType(poFeatureDefn->GetGeomType());
1902 : }
1903 30 : if (m_apoFieldsFromSchema.empty())
1904 : {
1905 87 : for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
1906 : {
1907 59 : m_poFeatureDefn->AddFieldDefn(poFeatureDefn->GetFieldDefn(i));
1908 : }
1909 : }
1910 : else
1911 : {
1912 3 : if (poFeatureDefn->GetFieldCount() > 0 &&
1913 1 : strcmp(poFeatureDefn->GetFieldDefn(0)->GetNameRef(), "id") == 0)
1914 : {
1915 0 : m_poFeatureDefn->AddFieldDefn(poFeatureDefn->GetFieldDefn(0));
1916 : }
1917 21 : for (const auto &poField : m_apoFieldsFromSchema)
1918 : {
1919 19 : m_poFeatureDefn->AddFieldDefn(poField.get());
1920 : }
1921 : // In case there would be properties found in sample, but not in
1922 : // schema...
1923 3 : for (int i = 0; i < poFeatureDefn->GetFieldCount(); i++)
1924 : {
1925 1 : auto poFDefn = poFeatureDefn->GetFieldDefn(i);
1926 1 : if (m_poFeatureDefn->GetFieldIndex(poFDefn->GetNameRef()) < 0)
1927 : {
1928 1 : m_poFeatureDefn->AddFieldDefn(poFDefn);
1929 : }
1930 : }
1931 : }
1932 :
1933 32 : for (const auto &osItemAsset : m_aosItemAssetNames)
1934 : {
1935 4 : OGRFieldDefn oFieldDefn(("asset_" + osItemAsset + "_href").c_str(),
1936 4 : OFTString);
1937 : // cppcheck-suppress danglingTemporaryLifetime
1938 2 : m_poFeatureDefn->AddFieldDefn(&oFieldDefn);
1939 : }
1940 :
1941 60 : const auto &oRoot = oDoc.GetRoot();
1942 30 : GIntBig nFeatures = oRoot.GetLong("numberMatched", -1);
1943 30 : if (nFeatures >= 0)
1944 : {
1945 9 : m_nTotalFeatureCount = nFeatures;
1946 : }
1947 :
1948 90 : auto oFeatures = oRoot.GetArray("features");
1949 30 : if (oFeatures.IsValid() && oFeatures.Size() > 0)
1950 : {
1951 26 : auto eType = oFeatures[0].GetObj("id").GetType();
1952 26 : if (eType == CPLJSONObject::Type::Integer ||
1953 : eType == CPLJSONObject::Type::Long)
1954 : {
1955 3 : m_bHasIntIdMember = true;
1956 : }
1957 23 : else if (eType == CPLJSONObject::Type::String)
1958 : {
1959 7 : m_bHasStringIdMember = true;
1960 : }
1961 : }
1962 : }
1963 :
1964 : /************************************************************************/
1965 : /* ResetReading() */
1966 : /************************************************************************/
1967 :
1968 80 : void OGROAPIFLayer::ResetReading()
1969 : {
1970 80 : m_poUnderlyingDS.reset();
1971 80 : m_poUnderlyingLayer = nullptr;
1972 80 : m_nFID = 1;
1973 80 : m_osGetURL = m_osURL;
1974 80 : if (!m_osGetID.empty())
1975 : {
1976 4 : m_osGetURL += "/" + m_osGetID;
1977 : }
1978 : else
1979 : {
1980 76 : if (m_poDS->m_nPageSize > 0)
1981 : {
1982 152 : m_osGetURL = CPLURLAddKVP(m_osGetURL, "limit",
1983 152 : CPLSPrintf("%d", m_poDS->m_nPageSize));
1984 : }
1985 76 : m_osGetURL = AddFilters(m_osGetURL);
1986 : }
1987 80 : m_oCurDoc = CPLJSONDocument();
1988 80 : m_iFeatureInPage = 0;
1989 80 : }
1990 :
1991 : /************************************************************************/
1992 : /* AddFilters() */
1993 : /************************************************************************/
1994 :
1995 78 : CPLString OGROAPIFLayer::AddFilters(const CPLString &osURL)
1996 : {
1997 78 : CPLString osURLNew(osURL);
1998 78 : if (m_poFilterGeom)
1999 : {
2000 8 : double dfMinX = m_sFilterEnvelope.MinX;
2001 8 : double dfMinY = m_sFilterEnvelope.MinY;
2002 8 : double dfMaxX = m_sFilterEnvelope.MaxX;
2003 8 : double dfMaxY = m_sFilterEnvelope.MaxY;
2004 8 : bool bAddBBoxFilter = true;
2005 8 : if (m_bIsGeographicCRS)
2006 : {
2007 6 : dfMinX = std::max(dfMinX, -180.0);
2008 6 : dfMinY = std::max(dfMinY, -90.0);
2009 6 : dfMaxX = std::min(dfMaxX, 180.0);
2010 6 : dfMaxY = std::min(dfMaxY, 90.0);
2011 8 : bAddBBoxFilter = dfMinX > -180.0 || dfMinY > -90.0 ||
2012 8 : dfMaxX < 180.0 || dfMaxY < 90.0;
2013 : }
2014 8 : if (bAddBBoxFilter)
2015 : {
2016 7 : if (!m_bCRSHasGISFriendlyOrder)
2017 : {
2018 2 : std::swap(dfMinX, dfMinY);
2019 2 : std::swap(dfMaxX, dfMaxY);
2020 : }
2021 14 : osURLNew = CPLURLAddKVP(osURLNew, "bbox",
2022 : CPLSPrintf("%.17g,%.17g,%.17g,%.17g",
2023 7 : dfMinX, dfMinY, dfMaxX, dfMaxY));
2024 7 : if (!m_osActiveCRS.empty())
2025 : {
2026 : osURLNew =
2027 4 : CPLURLAddKVP(osURLNew, "bbox-crs", m_osActiveCRS.c_str());
2028 : }
2029 : }
2030 : }
2031 78 : if (!m_osActiveCRS.empty())
2032 : {
2033 17 : osURLNew = CPLURLAddKVP(osURLNew, "crs", m_osActiveCRS.c_str());
2034 : }
2035 78 : if (!m_osAttributeFilter.empty())
2036 : {
2037 15 : if (osURLNew.find('?') == std::string::npos)
2038 0 : osURLNew += "?";
2039 : else
2040 15 : osURLNew += "&";
2041 15 : osURLNew += m_osAttributeFilter;
2042 : }
2043 78 : if (!m_poDS->m_osDateTime.empty())
2044 : {
2045 3 : if (osURLNew.find('?') == std::string::npos)
2046 0 : osURLNew += "?";
2047 : else
2048 3 : osURLNew += "&";
2049 3 : osURLNew += "datetime=";
2050 3 : osURLNew += m_poDS->m_osDateTime;
2051 : }
2052 78 : return osURLNew;
2053 : }
2054 :
2055 : /************************************************************************/
2056 : /* GetNextRawFeature() */
2057 : /************************************************************************/
2058 :
2059 45 : OGRFeature *OGROAPIFLayer::GetNextRawFeature()
2060 : {
2061 45 : if (!m_bFeatureDefnEstablished)
2062 4 : EstablishFeatureDefn();
2063 :
2064 45 : OGRFeature *poSrcFeature = nullptr;
2065 : while (true)
2066 : {
2067 52 : if (m_poUnderlyingLayer == nullptr)
2068 : {
2069 41 : if (m_osGetURL.empty())
2070 3 : return nullptr;
2071 :
2072 38 : m_oCurDoc = CPLJSONDocument();
2073 :
2074 38 : const CPLString osURL(m_osGetURL);
2075 38 : m_osGetURL.clear();
2076 38 : CPLStringList aosHeaders;
2077 38 : if (!m_poDS->DownloadJSon(osURL, m_oCurDoc,
2078 : MEDIA_TYPE_GEOJSON ", " MEDIA_TYPE_JSON,
2079 : &aosHeaders))
2080 : {
2081 0 : return nullptr;
2082 : }
2083 :
2084 : const std::string osContentCRS =
2085 38 : aosHeaders.FetchNameValueDef("Content-Crs", "");
2086 38 : if (!m_bHasEmittedContentCRSWarning && !osContentCRS.empty())
2087 : {
2088 7 : if (m_osActiveCRS.empty())
2089 : {
2090 0 : if (osContentCRS !=
2091 0 : "<http://www.opengis.net/def/crs/OGC/1.3/CRS84>" &&
2092 0 : osContentCRS !=
2093 : "<http://www.opengis.net/def/crs/OGC/0/CRS84h>")
2094 : {
2095 0 : m_bHasEmittedContentCRSWarning = true;
2096 0 : CPLDebug("OAPIF",
2097 : "Got Content-CRS = %s, but expected OGC:CRS84 "
2098 : "instead. "
2099 : "Content-CRS will be ignored",
2100 : osContentCRS.c_str());
2101 : }
2102 : }
2103 : else
2104 : {
2105 7 : if (osContentCRS != '<' + m_osActiveCRS + '>')
2106 : {
2107 0 : m_bHasEmittedContentCRSWarning = true;
2108 0 : CPLDebug(
2109 : "OAPIF",
2110 : "Got Content-CRS = %s, but expected %s instead. "
2111 : "Content-CRS will be ignored",
2112 : osContentCRS.c_str(), m_osActiveCRS.c_str());
2113 : }
2114 : }
2115 : }
2116 31 : else if (!m_bHasEmittedContentCRSWarning)
2117 : {
2118 31 : if (!m_osActiveCRS.empty())
2119 : {
2120 1 : m_bHasEmittedContentCRSWarning = true;
2121 1 : CPLDebug("OAPIF",
2122 : "Dit not get Content-CRS header. "
2123 : "Assuming %s is returned",
2124 : m_osActiveCRS.c_str());
2125 : }
2126 : }
2127 :
2128 38 : if (!m_bHasEmittedJsonCRWarning)
2129 : {
2130 114 : const auto oJsonCRS = m_oCurDoc.GetRoot().GetObj("crs");
2131 38 : if (oJsonCRS.IsValid())
2132 : {
2133 0 : m_bHasEmittedJsonCRWarning = true;
2134 0 : CPLDebug("OAPIF",
2135 : "JSON response contains %s. It will be ignored.",
2136 0 : oJsonCRS.ToString().c_str());
2137 : }
2138 : }
2139 :
2140 : const CPLString osTmpFilename(
2141 38 : VSIMemGenerateHiddenFilename("oapif.json"));
2142 38 : m_oCurDoc.Save(osTmpFilename);
2143 : m_poUnderlyingDS =
2144 76 : std::unique_ptr<GDALDataset>(GDALDataset::FromHandle(
2145 : GDALOpenEx(osTmpFilename, GDAL_OF_VECTOR | GDAL_OF_INTERNAL,
2146 38 : nullptr, nullptr, nullptr)));
2147 38 : VSIUnlink(osTmpFilename);
2148 38 : if (!m_poUnderlyingDS.get())
2149 : {
2150 0 : return nullptr;
2151 : }
2152 38 : m_poUnderlyingLayer = m_poUnderlyingDS->GetLayer(0);
2153 38 : if (!m_poUnderlyingLayer)
2154 : {
2155 0 : m_poUnderlyingDS.reset();
2156 0 : return nullptr;
2157 : }
2158 :
2159 : // To avoid issues with implementations having a non-relevant
2160 : // next link, make sure the current page is not empty
2161 : // We could even check that the feature count is the page size
2162 : // actually
2163 38 : if (m_poUnderlyingLayer->GetFeatureCount() > 0 && m_osGetID.empty())
2164 : {
2165 108 : CPLJSONArray oLinks = m_oCurDoc.GetRoot().GetArray("links");
2166 36 : if (oLinks.IsValid())
2167 : {
2168 6 : int nCountRelNext = 0;
2169 12 : std::string osNextURL;
2170 12 : for (int i = 0; i < oLinks.Size(); i++)
2171 : {
2172 10 : CPLJSONObject oLink = oLinks[i];
2173 20 : if (!oLink.IsValid() ||
2174 10 : oLink.GetType() != CPLJSONObject::Type::Object)
2175 : {
2176 0 : continue;
2177 : }
2178 10 : if (EQUAL(oLink.GetString("rel").c_str(), "next"))
2179 : {
2180 4 : nCountRelNext++;
2181 8 : auto type = oLink.GetString("type");
2182 4 : if (type == MEDIA_TYPE_GEOJSON ||
2183 0 : type == MEDIA_TYPE_JSON)
2184 : {
2185 4 : m_osGetURL = oLink.GetString("href");
2186 4 : break;
2187 : }
2188 0 : else if (type.empty())
2189 : {
2190 0 : osNextURL = oLink.GetString("href");
2191 : }
2192 : }
2193 : }
2194 6 : if (nCountRelNext == 1 && m_osGetURL.empty())
2195 : {
2196 : // In case we go a "rel": "next" without a "type"
2197 0 : m_osGetURL = std::move(osNextURL);
2198 : }
2199 : }
2200 :
2201 : #ifdef no_longer_used
2202 : // Recommendation /rec/core/link-header
2203 : if (m_osGetURL.empty())
2204 : {
2205 : for (int i = 0; i < aosHeaders.size(); i++)
2206 : {
2207 : CPLDebug("OAPIF", "%s", aosHeaders[i]);
2208 : if (STARTS_WITH_CI(aosHeaders[i], "Link=") &&
2209 : strstr(aosHeaders[i], "rel=\"next\"") &&
2210 : strstr(aosHeaders[i],
2211 : "type=\"" MEDIA_TYPE_GEOJSON "\""))
2212 : {
2213 : const char *pszStart = strchr(aosHeaders[i], '<');
2214 : if (pszStart)
2215 : {
2216 : const char *pszEnd = strchr(pszStart + 1, '>');
2217 : if (pszEnd)
2218 : {
2219 : m_osGetURL = pszStart + 1;
2220 : m_osGetURL.resize(pszEnd - pszStart - 1);
2221 : }
2222 : }
2223 : break;
2224 : }
2225 : }
2226 : }
2227 : #endif
2228 :
2229 36 : if (!m_osGetURL.empty())
2230 : {
2231 4 : m_osGetURL = m_poDS->ResolveURL(m_osGetURL, osURL);
2232 : }
2233 : }
2234 : }
2235 :
2236 : // cppcheck-suppress nullPointerRedundantCheck
2237 49 : poSrcFeature = m_poUnderlyingLayer->GetNextFeature();
2238 49 : if (poSrcFeature)
2239 : {
2240 42 : break;
2241 : }
2242 7 : m_poUnderlyingDS.reset();
2243 7 : m_poUnderlyingLayer = nullptr;
2244 7 : m_iFeatureInPage = 0;
2245 7 : }
2246 :
2247 42 : OGRFeature *poFeature = new OGRFeature(m_poFeatureDefn);
2248 42 : poFeature->SetFrom(poSrcFeature);
2249 :
2250 : // Collect STAC assets href
2251 2 : if (!m_aosItemAssetNames.empty() && m_poUnderlyingLayer != nullptr &&
2252 44 : m_oCurDoc.GetRoot().GetArray("features").Size() ==
2253 46 : m_poUnderlyingLayer->GetFeatureCount() &&
2254 44 : m_iFeatureInPage < m_oCurDoc.GetRoot().GetArray("features").Size())
2255 : {
2256 : auto m_oFeature =
2257 6 : m_oCurDoc.GetRoot().GetArray("features")[m_iFeatureInPage];
2258 6 : auto oAssets = m_oFeature["assets"];
2259 6 : for (const auto &osAssetName : m_aosItemAssetNames)
2260 : {
2261 12 : auto href = oAssets[osAssetName]["href"];
2262 4 : if (href.IsValid() && href.GetType() == CPLJSONObject::Type::String)
2263 : {
2264 2 : poFeature->SetField(("asset_" + osAssetName + "_href").c_str(),
2265 4 : href.ToString().c_str());
2266 : }
2267 : }
2268 : }
2269 42 : m_iFeatureInPage++;
2270 :
2271 42 : auto poGeom = poFeature->GetGeometryRef();
2272 42 : if (poGeom)
2273 : {
2274 20 : if (!m_bCRSHasGISFriendlyOrder &&
2275 3 : !m_poDS->m_bServerFeaturesAxisOrderGISFriendly)
2276 2 : poGeom->swapXY();
2277 20 : poGeom->assignSpatialReference(GetSpatialRef());
2278 : }
2279 42 : if (m_bHasIntIdMember)
2280 : {
2281 4 : poFeature->SetFID(poSrcFeature->GetFID());
2282 : }
2283 : else
2284 : {
2285 38 : poFeature->SetFID(m_nFID);
2286 38 : m_nFID++;
2287 : }
2288 42 : delete poSrcFeature;
2289 42 : return poFeature;
2290 : }
2291 :
2292 : /************************************************************************/
2293 : /* GetFeature() */
2294 : /************************************************************************/
2295 :
2296 1 : OGRFeature *OGROAPIFLayer::GetFeature(GIntBig nFID)
2297 : {
2298 1 : if (!m_bFeatureDefnEstablished)
2299 0 : EstablishFeatureDefn();
2300 1 : if (!m_bHasIntIdMember)
2301 0 : return OGRLayer::GetFeature(nFID);
2302 :
2303 1 : m_osGetID.Printf(CPL_FRMT_GIB, nFID);
2304 1 : ResetReading();
2305 1 : auto poRet = GetNextRawFeature();
2306 1 : m_osGetID.clear();
2307 1 : ResetReading();
2308 1 : return poRet;
2309 : }
2310 :
2311 : /************************************************************************/
2312 : /* GetNextFeature() */
2313 : /************************************************************************/
2314 :
2315 44 : OGRFeature *OGROAPIFLayer::GetNextFeature()
2316 : {
2317 : while (true)
2318 : {
2319 44 : OGRFeature *poFeature = GetNextRawFeature();
2320 44 : if (poFeature == nullptr)
2321 3 : return nullptr;
2322 :
2323 88 : if ((m_poFilterGeom == nullptr ||
2324 82 : FilterGeometry(poFeature->GetGeometryRef())) &&
2325 41 : (m_poAttrQuery == nullptr || !m_bFilterMustBeClientSideEvaluated ||
2326 4 : m_poAttrQuery->Evaluate(poFeature)))
2327 : {
2328 40 : return poFeature;
2329 : }
2330 : else
2331 : {
2332 1 : delete poFeature;
2333 : }
2334 1 : }
2335 : }
2336 :
2337 : /************************************************************************/
2338 : /* SupportsResultTypeHits() */
2339 : /************************************************************************/
2340 :
2341 4 : bool OGROAPIFLayer::SupportsResultTypeHits()
2342 : {
2343 8 : std::string osAPIURL;
2344 8 : CPLJSONDocument oDoc = m_poDS->GetAPIDoc(osAPIURL);
2345 4 : if (oDoc.GetRoot().GetString("openapi").empty())
2346 2 : return false;
2347 :
2348 : CPLJSONArray oParameters =
2349 4 : oDoc.GetRoot().GetObj("paths").GetObj(m_osPath).GetObj("get").GetArray(
2350 6 : "parameters");
2351 2 : if (!oParameters.IsValid())
2352 0 : return false;
2353 2 : for (int i = 0; i < oParameters.Size(); i++)
2354 : {
2355 2 : CPLJSONObject oParam = oParameters[i];
2356 4 : CPLString osRef = oParam.GetString("$ref");
2357 2 : if (!osRef.empty() && osRef.find("#/") == 0)
2358 : {
2359 2 : oParam = oDoc.GetRoot().GetObj(osRef.substr(2));
2360 : #ifndef REMOVE_HACK
2361 : // Needed for
2362 : // http://www.pvretano.com/cubewerx/cubeserv/default/wfs/3.0.0/foundation/api
2363 : // that doesn't define #/components/parameters/resultType
2364 2 : if (osRef == "#/components/parameters/resultType")
2365 2 : return true;
2366 : #endif
2367 : }
2368 0 : if (oParam.GetString("name") == "resultType" &&
2369 0 : oParam.GetString("in") == "query")
2370 : {
2371 0 : CPLJSONArray oEnum = oParam.GetArray("schema/enum");
2372 0 : for (int j = 0; j < oEnum.Size(); j++)
2373 : {
2374 0 : if (oEnum[j].ToString() == "hits")
2375 0 : return true;
2376 : }
2377 0 : return false;
2378 : }
2379 : }
2380 :
2381 0 : return false;
2382 : }
2383 :
2384 : /************************************************************************/
2385 : /* GetFeatureCount() */
2386 : /************************************************************************/
2387 :
2388 12 : GIntBig OGROAPIFLayer::GetFeatureCount(int bForce)
2389 : {
2390 :
2391 24 : if (m_poFilterGeom == nullptr && m_poAttrQuery == nullptr &&
2392 12 : m_poDS->m_osDateTime.empty())
2393 : {
2394 11 : if (m_nTotalFeatureCount >= 0)
2395 : {
2396 2 : return m_nTotalFeatureCount;
2397 : }
2398 9 : GetLayerDefn();
2399 9 : if (m_nTotalFeatureCount >= 0)
2400 : {
2401 6 : return m_nTotalFeatureCount;
2402 : }
2403 : }
2404 :
2405 4 : if (SupportsResultTypeHits() && !m_bFilterMustBeClientSideEvaluated)
2406 : {
2407 2 : CPLString osURL(m_osURL);
2408 2 : osURL = CPLURLAddKVP(osURL, "resultType", "hits");
2409 2 : osURL = AddFilters(osURL);
2410 : #ifndef REMOVE_HACK
2411 2 : bool bGMLRequest = m_osURL.find("cubeserv") != std::string::npos;
2412 : #else
2413 : constexpr bool bGMLRequest = false;
2414 : #endif
2415 2 : if (bGMLRequest)
2416 : {
2417 0 : CPLString osResult;
2418 0 : CPLString osContentType;
2419 0 : if (m_poDS->Download(osURL, MEDIA_TYPE_TEXT_XML, osResult,
2420 : osContentType))
2421 : {
2422 0 : CPLXMLNode *psDoc = CPLParseXMLString(osResult);
2423 0 : if (psDoc)
2424 : {
2425 0 : CPLXMLTreeCloser oCloser(psDoc);
2426 0 : CPL_IGNORE_RET_VAL(oCloser);
2427 0 : CPLStripXMLNamespace(psDoc, nullptr, true);
2428 : CPLString osNumberMatched = CPLGetXMLValue(
2429 0 : psDoc, "=FeatureCollection.numberMatched", "");
2430 0 : if (!osNumberMatched.empty())
2431 0 : return CPLAtoGIntBig(osNumberMatched);
2432 : }
2433 : }
2434 : }
2435 : else
2436 : {
2437 2 : CPLJSONDocument oDoc;
2438 2 : if (m_poDS->DownloadJSon(osURL, oDoc))
2439 : {
2440 2 : GIntBig nFeatures = oDoc.GetRoot().GetLong("numberMatched", -1);
2441 2 : if (nFeatures >= 0)
2442 2 : return nFeatures;
2443 : }
2444 : }
2445 : }
2446 :
2447 2 : return OGRLayer::GetFeatureCount(bForce);
2448 : }
2449 :
2450 : /************************************************************************/
2451 : /* IGetExtent() */
2452 : /************************************************************************/
2453 :
2454 10 : OGRErr OGROAPIFLayer::IGetExtent(int iGeomField, OGREnvelope *psEnvelope,
2455 : bool bForce)
2456 : {
2457 10 : if (m_oOriginalExtent.IsInit())
2458 : {
2459 10 : if (!m_oExtent.IsInit())
2460 8 : ComputeExtent();
2461 10 : *psEnvelope = m_oExtent;
2462 10 : return OGRERR_NONE;
2463 : }
2464 0 : return OGRLayer::IGetExtent(iGeomField, psEnvelope, bForce);
2465 : }
2466 :
2467 : /************************************************************************/
2468 : /* ISetSpatialFilter() */
2469 : /************************************************************************/
2470 :
2471 10 : OGRErr OGROAPIFLayer::ISetSpatialFilter(int, const OGRGeometry *poGeomIn)
2472 : {
2473 10 : InstallFilter(poGeomIn);
2474 :
2475 10 : ResetReading();
2476 10 : return OGRERR_NONE;
2477 : }
2478 :
2479 : /************************************************************************/
2480 : /* OGRWF3ParseDateTime() */
2481 : /************************************************************************/
2482 :
2483 5 : static int OGRWF3ParseDateTime(const char *pszValue, int &nYear, int &nMonth,
2484 : int &nDay, int &nHour, int &nMinute,
2485 : int &nSecond)
2486 : {
2487 5 : int ret = sscanf(pszValue, "%04d/%02d/%02d %02d:%02d:%02d", &nYear, &nMonth,
2488 : &nDay, &nHour, &nMinute, &nSecond);
2489 5 : if (ret >= 3)
2490 0 : return ret;
2491 5 : return sscanf(pszValue, "%04d-%02d-%02dT%02d:%02d:%02d", &nYear, &nMonth,
2492 5 : &nDay, &nHour, &nMinute, &nSecond);
2493 : }
2494 :
2495 : /************************************************************************/
2496 : /* SerializeDateTime() */
2497 : /************************************************************************/
2498 :
2499 5 : static CPLString SerializeDateTime(int nDateComponents, int nYear, int nMonth,
2500 : int nDay, int nHour, int nMinute,
2501 : int nSecond)
2502 : {
2503 5 : CPLString osRet;
2504 5 : osRet.Printf("%04d-%02d-%02dT", nYear, nMonth, nDay);
2505 5 : if (nDateComponents >= 4)
2506 : {
2507 3 : osRet += CPLSPrintf("%02d", nHour);
2508 3 : if (nDateComponents >= 5)
2509 3 : osRet += CPLSPrintf(":%02d", nMinute);
2510 3 : if (nDateComponents >= 6)
2511 3 : osRet += CPLSPrintf(":%02d", nSecond);
2512 3 : osRet += "Z";
2513 : }
2514 5 : return osRet;
2515 : }
2516 :
2517 : /************************************************************************/
2518 : /* BuildFilter() */
2519 : /************************************************************************/
2520 :
2521 11 : CPLString OGROAPIFLayer::BuildFilter(const swq_expr_node *poNode)
2522 : {
2523 11 : if (poNode->eNodeType == SNT_OPERATION && poNode->nOperation == SWQ_AND &&
2524 3 : poNode->nSubExprCount == 2)
2525 : {
2526 3 : const auto leftExpr = poNode->papoSubExpr[0];
2527 3 : const auto rightExpr = poNode->papoSubExpr[1];
2528 :
2529 : // Detect expression: datetime >=|> XXX and datetime <=|< XXXX
2530 3 : if (leftExpr->eNodeType == SNT_OPERATION &&
2531 3 : (leftExpr->nOperation == SWQ_GT ||
2532 3 : leftExpr->nOperation == SWQ_GE) &&
2533 1 : leftExpr->nSubExprCount == 2 &&
2534 1 : leftExpr->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2535 1 : leftExpr->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
2536 1 : rightExpr->eNodeType == SNT_OPERATION &&
2537 1 : (rightExpr->nOperation == SWQ_LT ||
2538 1 : rightExpr->nOperation == SWQ_LE) &&
2539 1 : rightExpr->nSubExprCount == 2 &&
2540 1 : rightExpr->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2541 1 : rightExpr->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
2542 1 : leftExpr->papoSubExpr[0]->field_index ==
2543 1 : rightExpr->papoSubExpr[0]->field_index &&
2544 1 : leftExpr->papoSubExpr[1]->field_type == SWQ_TIMESTAMP &&
2545 1 : rightExpr->papoSubExpr[1]->field_type == SWQ_TIMESTAMP)
2546 : {
2547 1 : const OGRFieldDefn *poFieldDefn = GetLayerDefn()->GetFieldDefn(
2548 1 : leftExpr->papoSubExpr[0]->field_index);
2549 2 : if (poFieldDefn && (poFieldDefn->GetType() == OFTDate ||
2550 1 : poFieldDefn->GetType() == OFTDateTime))
2551 : {
2552 1 : CPLString osExpr;
2553 : {
2554 1 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
2555 1 : nSecond = 0;
2556 1 : int nDateComponents = OGRWF3ParseDateTime(
2557 1 : leftExpr->papoSubExpr[1]->string_value, nYear, nMonth,
2558 : nDay, nHour, nMinute, nSecond);
2559 1 : if (nDateComponents >= 3)
2560 : {
2561 : osExpr =
2562 1 : "datetime=" +
2563 2 : SerializeDateTime(nDateComponents, nYear, nMonth,
2564 1 : nDay, nHour, nMinute, nSecond);
2565 : }
2566 : }
2567 1 : if (!osExpr.empty())
2568 : {
2569 1 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
2570 1 : nSecond = 0;
2571 1 : int nDateComponents = OGRWF3ParseDateTime(
2572 1 : rightExpr->papoSubExpr[1]->string_value, nYear, nMonth,
2573 : nDay, nHour, nMinute, nSecond);
2574 1 : if (nDateComponents >= 3)
2575 : {
2576 : osExpr +=
2577 : "%2F" // '/' URL encoded
2578 2 : + SerializeDateTime(nDateComponents, nYear, nMonth,
2579 1 : nDay, nHour, nMinute, nSecond);
2580 1 : return osExpr;
2581 : }
2582 : }
2583 : }
2584 : }
2585 :
2586 : // For AND, we can deal with a failure in one of the branch
2587 : // since client-side will do that extra filtering
2588 4 : CPLString osFilter1 = BuildFilter(leftExpr);
2589 4 : CPLString osFilter2 = BuildFilter(rightExpr);
2590 2 : if (!osFilter1.empty() && !osFilter2.empty())
2591 : {
2592 2 : return osFilter1 + "&" + osFilter2;
2593 : }
2594 1 : else if (!osFilter1.empty())
2595 1 : return osFilter1;
2596 : else
2597 0 : return osFilter2;
2598 : }
2599 8 : else if (poNode->eNodeType == SNT_OPERATION &&
2600 8 : poNode->nOperation == SWQ_EQ && poNode->nSubExprCount == 2 &&
2601 5 : poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2602 5 : poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT)
2603 : {
2604 5 : const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
2605 : const OGRFieldDefn *poFieldDefn =
2606 5 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2607 : int nDateComponents;
2608 5 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
2609 5 : nSecond = 0;
2610 15 : if (m_bHasStringIdMember &&
2611 6 : strcmp(poFieldDefn->GetNameRef(), "id") == 0 &&
2612 1 : poNode->papoSubExpr[1]->field_type == SWQ_STRING)
2613 : {
2614 1 : m_osGetID = poNode->papoSubExpr[1]->string_value;
2615 : }
2616 8 : else if (poFieldDefn &&
2617 8 : m_aoSetQueryableAttributes.find(poFieldDefn->GetNameRef()) !=
2618 8 : m_aoSetQueryableAttributes.end())
2619 : {
2620 : char *pszEscapedFieldName =
2621 2 : CPLEscapeString(poFieldDefn->GetNameRef(), -1, CPLES_URL);
2622 2 : CPLString osEscapedFieldName(pszEscapedFieldName);
2623 2 : CPLFree(pszEscapedFieldName);
2624 :
2625 2 : if (poNode->papoSubExpr[1]->field_type == SWQ_STRING)
2626 : {
2627 2 : char *pszEscapedValue = CPLEscapeString(
2628 1 : poNode->papoSubExpr[1]->string_value, -1, CPLES_URL);
2629 2 : CPLString osRet(std::move(osEscapedFieldName));
2630 1 : osRet += "=";
2631 1 : osRet += pszEscapedValue;
2632 1 : CPLFree(pszEscapedValue);
2633 1 : return osRet;
2634 : }
2635 1 : if (poNode->papoSubExpr[1]->field_type == SWQ_INTEGER)
2636 : {
2637 2 : CPLString osRet(std::move(osEscapedFieldName));
2638 1 : osRet += "=";
2639 : osRet +=
2640 1 : CPLSPrintf("%" PRId64, poNode->papoSubExpr[1]->int_value);
2641 1 : return osRet;
2642 : }
2643 : }
2644 2 : else if (poFieldDefn &&
2645 4 : (poFieldDefn->GetType() == OFTDate ||
2646 2 : poFieldDefn->GetType() == OFTDateTime) &&
2647 5 : poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP &&
2648 1 : (nDateComponents = OGRWF3ParseDateTime(
2649 1 : poNode->papoSubExpr[1]->string_value, nYear, nMonth, nDay,
2650 : nHour, nMinute, nSecond)) >= 3)
2651 : {
2652 2 : return "datetime=" + SerializeDateTime(nDateComponents, nYear,
2653 : nMonth, nDay, nHour, nMinute,
2654 1 : nSecond);
2655 2 : }
2656 : }
2657 3 : else if (poNode->eNodeType == SNT_OPERATION &&
2658 3 : (poNode->nOperation == SWQ_GT || poNode->nOperation == SWQ_GE ||
2659 2 : poNode->nOperation == SWQ_LT || poNode->nOperation == SWQ_LE) &&
2660 2 : poNode->nSubExprCount == 2 &&
2661 2 : poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2662 2 : poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
2663 2 : poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP)
2664 : {
2665 2 : const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
2666 : const OGRFieldDefn *poFieldDefn =
2667 2 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2668 : int nDateComponents;
2669 2 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
2670 2 : nSecond = 0;
2671 2 : if (poFieldDefn &&
2672 4 : (poFieldDefn->GetType() == OFTDate ||
2673 6 : poFieldDefn->GetType() == OFTDateTime) &&
2674 2 : (nDateComponents = OGRWF3ParseDateTime(
2675 2 : poNode->papoSubExpr[1]->string_value, nYear, nMonth, nDay,
2676 : nHour, nMinute, nSecond)) >= 3)
2677 : {
2678 : CPLString osDT(SerializeDateTime(nDateComponents, nYear, nMonth,
2679 4 : nDay, nHour, nMinute, nSecond));
2680 2 : if (poNode->nOperation == SWQ_GT || poNode->nOperation == SWQ_GE)
2681 : {
2682 2 : return "datetime=" + osDT + "%2F..";
2683 : }
2684 : else
2685 : {
2686 2 : return "datetime=..%2F" + osDT;
2687 : }
2688 : }
2689 : }
2690 3 : m_bFilterMustBeClientSideEvaluated = true;
2691 3 : return CPLString();
2692 : }
2693 :
2694 : /************************************************************************/
2695 : /* BuildFilterCQLText() */
2696 : /************************************************************************/
2697 :
2698 0 : CPLString OGROAPIFLayer::BuildFilterCQLText(const swq_expr_node *poNode)
2699 : {
2700 0 : if (poNode->eNodeType == SNT_OPERATION && poNode->nOperation == SWQ_AND &&
2701 0 : poNode->nSubExprCount == 2)
2702 : {
2703 0 : const auto leftExpr = poNode->papoSubExpr[0];
2704 0 : const auto rightExpr = poNode->papoSubExpr[1];
2705 :
2706 : // For AND, we can deal with a failure in one of the branch
2707 : // since client-side will do that extra filtering
2708 0 : CPLString osFilter1 = BuildFilterCQLText(leftExpr);
2709 0 : CPLString osFilter2 = BuildFilterCQLText(rightExpr);
2710 0 : if (!osFilter1.empty() && !osFilter2.empty())
2711 : {
2712 0 : return '(' + osFilter1 + ") AND (" + osFilter2 + ')';
2713 : }
2714 0 : else if (!osFilter1.empty())
2715 0 : return osFilter1;
2716 : else
2717 0 : return osFilter2;
2718 : }
2719 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2720 0 : poNode->nOperation == SWQ_OR && poNode->nSubExprCount == 2)
2721 : {
2722 0 : const auto leftExpr = poNode->papoSubExpr[0];
2723 0 : const auto rightExpr = poNode->papoSubExpr[1];
2724 :
2725 0 : CPLString osFilter1 = BuildFilterCQLText(leftExpr);
2726 0 : CPLString osFilter2 = BuildFilterCQLText(rightExpr);
2727 0 : if (!osFilter1.empty() && !osFilter2.empty())
2728 : {
2729 0 : return '(' + osFilter1 + ") OR (" + osFilter2 + ')';
2730 0 : }
2731 : }
2732 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2733 0 : poNode->nOperation == SWQ_NOT && poNode->nSubExprCount == 1)
2734 : {
2735 0 : const auto childExpr = poNode->papoSubExpr[0];
2736 0 : CPLString osFilterChild = BuildFilterCQLText(childExpr);
2737 0 : if (!osFilterChild.empty())
2738 : {
2739 0 : return "NOT (" + osFilterChild + ')';
2740 0 : }
2741 : }
2742 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2743 0 : poNode->nOperation == SWQ_ISNULL && poNode->nSubExprCount == 1 &&
2744 0 : poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN)
2745 : {
2746 0 : const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
2747 : const OGRFieldDefn *poFieldDefn =
2748 0 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2749 0 : if (poFieldDefn)
2750 : {
2751 0 : return CPLString("(") + poFieldDefn->GetNameRef() + " IS NULL)";
2752 0 : }
2753 : }
2754 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2755 0 : (poNode->nOperation == SWQ_EQ || poNode->nOperation == SWQ_NE ||
2756 0 : poNode->nOperation == SWQ_GT || poNode->nOperation == SWQ_GE ||
2757 0 : poNode->nOperation == SWQ_LT || poNode->nOperation == SWQ_LE ||
2758 0 : poNode->nOperation == SWQ_LIKE ||
2759 0 : poNode->nOperation == SWQ_ILIKE) &&
2760 0 : poNode->nSubExprCount == 2 &&
2761 0 : poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2762 0 : poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT)
2763 : {
2764 0 : const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
2765 : const OGRFieldDefn *poFieldDefn =
2766 0 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2767 0 : if (m_bHasStringIdMember && poNode->nOperation == SWQ_EQ &&
2768 0 : strcmp(poFieldDefn->GetNameRef(), "id") == 0 &&
2769 0 : poNode->papoSubExpr[1]->field_type == SWQ_STRING)
2770 : {
2771 0 : m_osGetID = poNode->papoSubExpr[1]->string_value;
2772 : }
2773 0 : else if (poFieldDefn &&
2774 0 : m_aoSetQueryableAttributes.find(poFieldDefn->GetNameRef()) !=
2775 0 : m_aoSetQueryableAttributes.end())
2776 : {
2777 0 : CPLString osRet(poFieldDefn->GetNameRef());
2778 0 : switch (poNode->nOperation)
2779 : {
2780 0 : case SWQ_EQ:
2781 0 : osRet += " = ";
2782 0 : break;
2783 0 : case SWQ_NE:
2784 0 : osRet += " <> ";
2785 0 : break;
2786 0 : case SWQ_GT:
2787 0 : osRet += " > ";
2788 0 : break;
2789 0 : case SWQ_GE:
2790 0 : osRet += " >= ";
2791 0 : break;
2792 0 : case SWQ_LT:
2793 0 : osRet += " < ";
2794 0 : break;
2795 0 : case SWQ_LE:
2796 0 : osRet += " <= ";
2797 0 : break;
2798 0 : case SWQ_LIKE:
2799 0 : osRet += " LIKE ";
2800 0 : break;
2801 0 : case SWQ_ILIKE:
2802 0 : osRet += " ILIKE ";
2803 0 : break;
2804 0 : default:
2805 0 : CPLAssert(false);
2806 : break;
2807 : }
2808 0 : if (poNode->papoSubExpr[1]->field_type == SWQ_STRING)
2809 : {
2810 0 : osRet += '\'';
2811 0 : osRet += CPLString(poNode->papoSubExpr[1]->string_value)
2812 0 : .replaceAll('\'', "''");
2813 0 : osRet += '\'';
2814 0 : return osRet;
2815 : }
2816 0 : if (poNode->papoSubExpr[1]->field_type == SWQ_INTEGER ||
2817 0 : poNode->papoSubExpr[1]->field_type == SWQ_INTEGER64)
2818 : {
2819 : osRet +=
2820 0 : CPLSPrintf("%" PRId64, poNode->papoSubExpr[1]->int_value);
2821 0 : return osRet;
2822 : }
2823 0 : if (poNode->papoSubExpr[1]->field_type == SWQ_FLOAT)
2824 : {
2825 : osRet +=
2826 0 : CPLSPrintf("%.16g", poNode->papoSubExpr[1]->float_value);
2827 0 : return osRet;
2828 : }
2829 0 : if (poNode->papoSubExpr[1]->field_type == SWQ_TIMESTAMP)
2830 : {
2831 : int nDateComponents;
2832 0 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
2833 0 : nSecond = 0;
2834 0 : if ((poFieldDefn->GetType() == OFTDate ||
2835 0 : poFieldDefn->GetType() == OFTDateTime) &&
2836 0 : (nDateComponents = OGRWF3ParseDateTime(
2837 0 : poNode->papoSubExpr[1]->string_value, nYear, nMonth,
2838 : nDay, nHour, nMinute, nSecond)) >= 3)
2839 : {
2840 : CPLString osDT(SerializeDateTime(nDateComponents, nYear,
2841 : nMonth, nDay, nHour,
2842 0 : nMinute, nSecond));
2843 0 : osRet += '\'';
2844 0 : osRet += osDT;
2845 0 : osRet += '\'';
2846 0 : return osRet;
2847 : }
2848 : }
2849 : }
2850 : }
2851 :
2852 0 : m_bFilterMustBeClientSideEvaluated = true;
2853 0 : return CPLString();
2854 : }
2855 :
2856 : /************************************************************************/
2857 : /* BuildFilterJSONFilterExpr() */
2858 : /************************************************************************/
2859 :
2860 0 : CPLString OGROAPIFLayer::BuildFilterJSONFilterExpr(const swq_expr_node *poNode)
2861 : {
2862 0 : if (poNode->eNodeType == SNT_OPERATION && poNode->nOperation == SWQ_AND &&
2863 0 : poNode->nSubExprCount == 2)
2864 : {
2865 0 : const auto leftExpr = poNode->papoSubExpr[0];
2866 0 : const auto rightExpr = poNode->papoSubExpr[1];
2867 :
2868 : // For AND, we can deal with a failure in one of the branch
2869 : // since client-side will do that extra filtering
2870 0 : CPLString osFilter1 = BuildFilterJSONFilterExpr(leftExpr);
2871 0 : CPLString osFilter2 = BuildFilterJSONFilterExpr(rightExpr);
2872 0 : if (!osFilter1.empty() && !osFilter2.empty())
2873 : {
2874 0 : return "[\"all\"," + osFilter1 + ',' + osFilter2 + ']';
2875 : }
2876 0 : else if (!osFilter1.empty())
2877 0 : return osFilter1;
2878 : else
2879 0 : return osFilter2;
2880 : }
2881 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2882 0 : poNode->nOperation == SWQ_OR && poNode->nSubExprCount == 2)
2883 : {
2884 0 : const auto leftExpr = poNode->papoSubExpr[0];
2885 0 : const auto rightExpr = poNode->papoSubExpr[1];
2886 :
2887 0 : CPLString osFilter1 = BuildFilterJSONFilterExpr(leftExpr);
2888 0 : CPLString osFilter2 = BuildFilterJSONFilterExpr(rightExpr);
2889 0 : if (!osFilter1.empty() && !osFilter2.empty())
2890 : {
2891 0 : return "[\"any\"," + osFilter1 + ',' + osFilter2 + ']';
2892 0 : }
2893 : }
2894 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2895 0 : poNode->nOperation == SWQ_NOT && poNode->nSubExprCount == 1)
2896 : {
2897 0 : const auto childExpr = poNode->papoSubExpr[0];
2898 0 : CPLString osFilterChild = BuildFilterJSONFilterExpr(childExpr);
2899 0 : if (!osFilterChild.empty())
2900 : {
2901 0 : return "[\"!\"," + osFilterChild + ']';
2902 0 : }
2903 : }
2904 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2905 0 : poNode->nOperation == SWQ_ISNULL && poNode->nSubExprCount == 1)
2906 : {
2907 0 : const auto childExpr = poNode->papoSubExpr[0];
2908 0 : CPLString osFilterChild = BuildFilterJSONFilterExpr(childExpr);
2909 0 : if (!osFilterChild.empty())
2910 : {
2911 0 : return "[\"==\"," + osFilterChild + ",null]";
2912 0 : }
2913 : }
2914 0 : else if (poNode->eNodeType == SNT_OPERATION &&
2915 0 : (poNode->nOperation == SWQ_EQ || poNode->nOperation == SWQ_NE ||
2916 0 : poNode->nOperation == SWQ_GT || poNode->nOperation == SWQ_GE ||
2917 0 : poNode->nOperation == SWQ_LT || poNode->nOperation == SWQ_LE ||
2918 0 : poNode->nOperation == SWQ_LIKE) &&
2919 0 : poNode->nSubExprCount == 2)
2920 : {
2921 0 : if (m_bHasStringIdMember && poNode->nOperation == SWQ_EQ &&
2922 0 : poNode->papoSubExpr[0]->eNodeType == SNT_COLUMN &&
2923 0 : poNode->papoSubExpr[1]->eNodeType == SNT_CONSTANT &&
2924 0 : poNode->papoSubExpr[1]->field_type == SWQ_STRING)
2925 : {
2926 0 : const int nFieldIdx = poNode->papoSubExpr[0]->field_index;
2927 : const OGRFieldDefn *poFieldDefn =
2928 0 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2929 0 : if (strcmp(poFieldDefn->GetNameRef(), "id") == 0)
2930 : {
2931 0 : m_osGetID = poNode->papoSubExpr[1]->string_value;
2932 0 : return CPLString();
2933 : }
2934 : }
2935 :
2936 0 : CPLString osRet("[\"");
2937 0 : switch (poNode->nOperation)
2938 : {
2939 0 : case SWQ_EQ:
2940 0 : osRet += "==";
2941 0 : break;
2942 0 : case SWQ_NE:
2943 0 : osRet += "!=";
2944 0 : break;
2945 0 : case SWQ_GT:
2946 0 : osRet += ">";
2947 0 : break;
2948 0 : case SWQ_GE:
2949 0 : osRet += ">=";
2950 0 : break;
2951 0 : case SWQ_LT:
2952 0 : osRet += "<";
2953 0 : break;
2954 0 : case SWQ_LE:
2955 0 : osRet += "<=";
2956 0 : break;
2957 0 : case SWQ_LIKE:
2958 0 : osRet += "like";
2959 0 : break;
2960 0 : default:
2961 0 : CPLAssert(false);
2962 : break;
2963 : }
2964 0 : osRet += "\",";
2965 0 : CPLString osFilter1 = BuildFilterJSONFilterExpr(poNode->papoSubExpr[0]);
2966 0 : CPLString osFilter2 = BuildFilterJSONFilterExpr(poNode->papoSubExpr[1]);
2967 0 : if (!osFilter1.empty() && !osFilter2.empty())
2968 : {
2969 0 : osRet += osFilter1;
2970 0 : osRet += ',';
2971 0 : osRet += osFilter2;
2972 0 : osRet += ']';
2973 0 : return osRet;
2974 0 : }
2975 : }
2976 0 : else if (poNode->eNodeType == SNT_COLUMN)
2977 : {
2978 0 : const int nFieldIdx = poNode->field_index;
2979 : const OGRFieldDefn *poFieldDefn =
2980 0 : GetLayerDefn()->GetFieldDefn(nFieldIdx);
2981 0 : if (poFieldDefn &&
2982 0 : m_aoSetQueryableAttributes.find(poFieldDefn->GetNameRef()) !=
2983 0 : m_aoSetQueryableAttributes.end())
2984 : {
2985 0 : CPLString osRet("[\"get\",\"");
2986 0 : osRet += CPLString(poFieldDefn->GetNameRef())
2987 0 : .replaceAll('\\', "\\\\")
2988 0 : .replaceAll('"', "\\\"");
2989 0 : osRet += "\"]";
2990 0 : return osRet;
2991 : }
2992 : }
2993 0 : else if (poNode->eNodeType == SNT_CONSTANT)
2994 : {
2995 0 : if (poNode->field_type == SWQ_STRING)
2996 : {
2997 0 : CPLString osRet("\"");
2998 0 : osRet += CPLString(poNode->string_value)
2999 0 : .replaceAll('\\', "\\\\")
3000 0 : .replaceAll('"', "\\\"");
3001 0 : osRet += '"';
3002 0 : return osRet;
3003 : }
3004 0 : if (poNode->field_type == SWQ_INTEGER ||
3005 0 : poNode->field_type == SWQ_INTEGER64)
3006 : {
3007 0 : return CPLSPrintf("%" PRId64, poNode->int_value);
3008 : }
3009 0 : if (poNode->field_type == SWQ_FLOAT)
3010 : {
3011 0 : return CPLSPrintf("%.16g", poNode->float_value);
3012 : }
3013 0 : if (poNode->field_type == SWQ_TIMESTAMP)
3014 : {
3015 0 : int nYear = 0, nMonth = 0, nDay = 0, nHour = 0, nMinute = 0,
3016 0 : nSecond = 0;
3017 : const int nDateComponents =
3018 0 : OGRWF3ParseDateTime(poNode->string_value, nYear, nMonth, nDay,
3019 : nHour, nMinute, nSecond);
3020 0 : if (nDateComponents >= 3)
3021 : {
3022 : CPLString osDT(SerializeDateTime(nDateComponents, nYear, nMonth,
3023 : nDay, nHour, nMinute,
3024 0 : nSecond));
3025 0 : CPLString osRet("\"");
3026 0 : osRet += osDT;
3027 0 : osRet += '"';
3028 0 : return osRet;
3029 : }
3030 : }
3031 : }
3032 :
3033 0 : m_bFilterMustBeClientSideEvaluated = true;
3034 0 : return CPLString();
3035 : }
3036 :
3037 : /************************************************************************/
3038 : /* GetQueryableAttributes() */
3039 : /************************************************************************/
3040 :
3041 7 : void OGROAPIFLayer::GetQueryableAttributes()
3042 : {
3043 7 : if (m_bGotQueryableAttributes)
3044 6 : return;
3045 1 : m_bGotQueryableAttributes = true;
3046 1 : std::string osAPIURL;
3047 1 : CPLJSONDocument oAPIDoc = m_poDS->GetAPIDoc(osAPIURL);
3048 1 : if (oAPIDoc.GetRoot().GetString("openapi").empty())
3049 0 : return;
3050 :
3051 3 : CPLJSONObject oPaths = oAPIDoc.GetRoot().GetObj("paths");
3052 : CPLJSONArray oParameters =
3053 3 : oPaths.GetObj(m_osPath).GetObj("get").GetArray("parameters");
3054 1 : if (!oParameters.IsValid())
3055 : {
3056 0 : oParameters = oPaths.GetObj("/collections/{collectionId}/items")
3057 0 : .GetObj("get")
3058 0 : .GetArray("parameters");
3059 : }
3060 3 : for (int i = 0; i < oParameters.Size(); i++)
3061 : {
3062 4 : CPLJSONObject oParam = oParameters[i];
3063 6 : CPLString osRef = oParam.GetString("$ref");
3064 2 : if (!osRef.empty() && osRef.find("#/") == 0)
3065 : {
3066 0 : oParam = oAPIDoc.GetRoot().GetObj(osRef.substr(2));
3067 : }
3068 2 : if (oParam.GetString("in") == "query")
3069 : {
3070 6 : const auto osName(oParam.GetString("name"));
3071 2 : if (osName == "filter-lang")
3072 : {
3073 0 : const auto oEnums = oParam.GetObj("schema").GetArray("enum");
3074 0 : for (int j = 0; j < oEnums.Size(); j++)
3075 : {
3076 0 : if (oEnums[j].ToString() == "cql-text")
3077 : {
3078 0 : m_bHasCQLText = true;
3079 0 : CPLDebug("OAPIF", "CQL text detected");
3080 : }
3081 0 : else if (oEnums[j].ToString() == "json-filter-expr")
3082 : {
3083 0 : m_bHasJSONFilterExpression = true;
3084 0 : CPLDebug("OAPIF", "JSON Filter expression detected");
3085 : }
3086 : }
3087 : }
3088 2 : else if (GetLayerDefn()->GetFieldIndex(osName.c_str()) >= 0)
3089 : {
3090 2 : m_aoSetQueryableAttributes.insert(osName);
3091 : }
3092 : }
3093 : }
3094 :
3095 : // HACK
3096 1 : if (CPLTestBool(CPLGetConfigOption("OGR_OAPIF_ALLOW_CQL_TEXT", "NO")))
3097 0 : m_bHasCQLText = true;
3098 :
3099 1 : if (m_bHasCQLText || m_bHasJSONFilterExpression)
3100 : {
3101 0 : if (!m_osQueryablesURL.empty())
3102 : {
3103 0 : CPLJSONDocument oDoc;
3104 0 : if (m_poDS->DownloadJSon(m_osQueryablesURL, oDoc))
3105 : {
3106 0 : auto oQueryables = oDoc.GetRoot().GetArray("queryables");
3107 0 : for (int i = 0; i < oQueryables.Size(); i++)
3108 : {
3109 0 : const auto osId = oQueryables[i].GetString("id");
3110 0 : if (!osId.empty())
3111 : {
3112 0 : m_aoSetQueryableAttributes.insert(osId);
3113 : }
3114 : }
3115 : }
3116 : }
3117 : }
3118 : }
3119 :
3120 : /************************************************************************/
3121 : /* SetAttributeFilter() */
3122 : /************************************************************************/
3123 :
3124 9 : OGRErr OGROAPIFLayer::SetAttributeFilter(const char *pszQuery)
3125 :
3126 : {
3127 9 : if (m_poAttrQuery == nullptr && pszQuery == nullptr)
3128 1 : return OGRERR_NONE;
3129 :
3130 8 : if (!m_bFeatureDefnEstablished)
3131 1 : EstablishFeatureDefn();
3132 :
3133 8 : OGRErr eErr = OGRLayer::SetAttributeFilter(pszQuery);
3134 :
3135 8 : m_osAttributeFilter.clear();
3136 8 : m_bFilterMustBeClientSideEvaluated = false;
3137 8 : m_osGetID.clear();
3138 8 : if (m_poAttrQuery != nullptr)
3139 : {
3140 7 : GetQueryableAttributes();
3141 :
3142 : swq_expr_node *poNode =
3143 7 : static_cast<swq_expr_node *>(m_poAttrQuery->GetSWQExpr());
3144 :
3145 7 : poNode->ReplaceBetweenByGEAndLERecurse();
3146 :
3147 7 : if (m_bHasCQLText)
3148 : {
3149 0 : m_osAttributeFilter = BuildFilterCQLText(poNode);
3150 0 : if (!m_osAttributeFilter.empty())
3151 : {
3152 : char *pszEscaped =
3153 0 : CPLEscapeString(m_osAttributeFilter, -1, CPLES_URL);
3154 0 : m_osAttributeFilter = "filter=";
3155 0 : m_osAttributeFilter += pszEscaped;
3156 0 : m_osAttributeFilter += "&filter-lang=cql-text";
3157 0 : CPLFree(pszEscaped);
3158 : }
3159 : }
3160 7 : else if (m_bHasJSONFilterExpression)
3161 : {
3162 0 : m_osAttributeFilter = BuildFilterJSONFilterExpr(poNode);
3163 0 : if (!m_osAttributeFilter.empty())
3164 : {
3165 : char *pszEscaped =
3166 0 : CPLEscapeString(m_osAttributeFilter, -1, CPLES_URL);
3167 0 : m_osAttributeFilter = "filter=";
3168 0 : m_osAttributeFilter += pszEscaped;
3169 0 : m_osAttributeFilter += "&filter-lang=json-filter-expr";
3170 0 : CPLFree(pszEscaped);
3171 : }
3172 : }
3173 : else
3174 : {
3175 7 : m_osAttributeFilter = BuildFilter(poNode);
3176 : }
3177 7 : if (m_osAttributeFilter.empty())
3178 : {
3179 2 : CPLDebug("OAPIF", "Full filter will be evaluated on client side.");
3180 : }
3181 5 : else if (m_bFilterMustBeClientSideEvaluated)
3182 : {
3183 1 : CPLDebug(
3184 : "OAPIF",
3185 : "Only part of the filter will be evaluated on server side.");
3186 : }
3187 : }
3188 :
3189 8 : ResetReading();
3190 :
3191 8 : return eErr;
3192 : }
3193 :
3194 : /************************************************************************/
3195 : /* TestCapability() */
3196 : /************************************************************************/
3197 :
3198 12 : int OGROAPIFLayer::TestCapability(const char *pszCap)
3199 : {
3200 12 : if (EQUAL(pszCap, OLCFastFeatureCount))
3201 : {
3202 5 : return m_nTotalFeatureCount >= 0 && m_poFilterGeom == nullptr &&
3203 5 : m_poAttrQuery == nullptr;
3204 : }
3205 9 : if (EQUAL(pszCap, OLCFastGetExtent))
3206 : {
3207 1 : return m_oOriginalExtent.IsInit();
3208 : }
3209 8 : if (EQUAL(pszCap, OLCStringsAsUTF8))
3210 : {
3211 7 : return TRUE;
3212 : }
3213 : // Don't advertise OLCRandomRead as it requires a GET per feature
3214 1 : return FALSE;
3215 : }
3216 :
3217 : /************************************************************************/
3218 : /* Open() */
3219 : /************************************************************************/
3220 :
3221 42 : static GDALDataset *OGROAPIFDriverOpen(GDALOpenInfo *poOpenInfo)
3222 :
3223 : {
3224 42 : if (!OGROAPIFDriverIdentify(poOpenInfo) || poOpenInfo->eAccess == GA_Update)
3225 0 : return nullptr;
3226 84 : auto poDataset = std::make_unique<OGROAPIFDataset>();
3227 42 : if (!poDataset->Open(poOpenInfo))
3228 9 : return nullptr;
3229 33 : return poDataset.release();
3230 : }
3231 :
3232 : /************************************************************************/
3233 : /* RegisterOGROAPIF() */
3234 : /************************************************************************/
3235 :
3236 1935 : void RegisterOGROAPIF()
3237 :
3238 : {
3239 1935 : if (GDALGetDriverByName("OAPIF") != nullptr)
3240 282 : return;
3241 :
3242 1653 : GDALDriver *poDriver = new GDALDriver();
3243 :
3244 1653 : poDriver->SetDescription("OAPIF");
3245 1653 : poDriver->SetMetadataItem(GDAL_DCAP_VECTOR, "YES");
3246 1653 : poDriver->SetMetadataItem(GDAL_DMD_LONGNAME, "OGC API - Features");
3247 1653 : poDriver->SetMetadataItem(GDAL_DMD_HELPTOPIC, "drivers/vector/oapif.html");
3248 :
3249 1653 : poDriver->SetMetadataItem(GDAL_DMD_CONNECTION_PREFIX, "OAPIF:");
3250 1653 : poDriver->SetMetadataItem(GDAL_DMD_SUPPORTED_SQL_DIALECTS, "OGRSQL SQLITE");
3251 :
3252 1653 : poDriver->SetMetadataItem(
3253 : GDAL_DMD_OPENOPTIONLIST,
3254 : "<OpenOptionList>"
3255 : " <Option name='URL' type='string' "
3256 : "description='URL to the landing page or a /collections/{id}' "
3257 : "required='true'/>"
3258 : " <Option name='PAGE_SIZE' type='int' "
3259 : "description='Maximum number of features to retrieve in a single "
3260 : "request'/>"
3261 : " <Option name='INITIAL_REQUEST_PAGE_SIZE' type='int' "
3262 : "description='Maximum number of features to retrieve in the initial "
3263 : "request issued to determine the schema from a feature sample'/>"
3264 : " <Option name='USERPWD' type='string' "
3265 : "description='Basic authentication as username:password'/>"
3266 : " <Option name='IGNORE_SCHEMA' type='boolean' "
3267 : "description='Whether the XML Schema or JSON Schema should be ignored' "
3268 : "default='NO'/>"
3269 : " <Option name='CRS' type='string' "
3270 : "description='CRS identifier to use for layers'/>"
3271 : " <Option name='PREFERRED_CRS' type='string' "
3272 : "description='Preferred CRS identifier to use for layers'/>"
3273 : " <Option name='SERVER_FEATURE_AXIS_ORDER' type='string-select' "
3274 : "description='Coordinate axis order of GeoJSON features returned by "
3275 : "the server' "
3276 : "default='AUTHORITY_COMPLIANT'>"
3277 : " <Value>AUTHORITY_COMPLIANT</Value>"
3278 : " <Value>GIS_FRIENDLY</Value>"
3279 : " </Option>"
3280 : " <Option name='DATETIME' type='string' "
3281 : "description=\"Date-time filter to pass to items requests with the "
3282 : "'datetime' parameter\"/>"
3283 1653 : "</OpenOptionList>");
3284 :
3285 1653 : poDriver->pfnIdentify = OGROAPIFDriverIdentify;
3286 1653 : poDriver->pfnOpen = OGROAPIFDriverOpen;
3287 :
3288 1653 : GetGDALDriverManager()->RegisterDriver(poDriver);
3289 : }
|