Line data Source code
1 : /******************************************************************************
2 : *
3 : * Project: OGR
4 : * Purpose: Implements OGRGMLDataSource class.
5 : * Author: Frank Warmerdam, warmerdam@pobox.com
6 : *
7 : ******************************************************************************
8 : * Copyright (c) 2002, Frank Warmerdam <warmerdam@pobox.com>
9 : * Copyright (c) 2007-2013, Even Rouault <even dot rouault at spatialys.com>
10 : *
11 : * SPDX-License-Identifier: MIT
12 : *
13 : ******************************************************************************
14 : * Contributor: Alessandro Furieri, a.furieri@lqt.it
15 : * Portions of this module implementing GML_SKIP_RESOLVE_ELEMS HUGE
16 : * Developed for Faunalia ( http://www.faunalia.it) with funding from
17 : * Regione Toscana - Settore SISTEMA INFORMATIVO TERRITORIALE ED AMBIENTALE
18 : *
19 : ****************************************************************************/
20 :
21 : #include "cpl_port.h"
22 : #include "ogr_gml.h"
23 :
24 : #include <algorithm>
25 : #include <vector>
26 :
27 : #include "cpl_conv.h"
28 : #include "cpl_http.h"
29 : #include "cpl_string.h"
30 : #include "cpl_vsi_error.h"
31 : #include "gmlreaderp.h"
32 : #include "gmlregistry.h"
33 : #include "gmlutils.h"
34 : #include "ogr_p.h"
35 : #include "ogr_schema_override.h"
36 : #include "parsexsd.h"
37 : #include "memdataset.h"
38 :
39 : /************************************************************************/
40 : /* ReplaceSpaceByPct20IfNeeded() */
41 : /************************************************************************/
42 :
43 142 : static CPLString ReplaceSpaceByPct20IfNeeded(const char *pszURL)
44 : {
45 : // Replace ' ' by '%20'.
46 142 : CPLString osRet = pszURL;
47 142 : const char *pszNeedle = strstr(pszURL, "; ");
48 142 : if (pszNeedle)
49 : {
50 2 : char *pszTmp = static_cast<char *>(CPLMalloc(strlen(pszURL) + 2 + 1));
51 2 : const int nBeforeNeedle = static_cast<int>(pszNeedle - pszURL);
52 2 : memcpy(pszTmp, pszURL, nBeforeNeedle);
53 2 : strcpy(pszTmp + nBeforeNeedle, ";%20");
54 2 : strcpy(pszTmp + nBeforeNeedle + strlen(";%20"),
55 : pszNeedle + strlen("; "));
56 2 : osRet = pszTmp;
57 2 : CPLFree(pszTmp);
58 : }
59 :
60 142 : return osRet;
61 : }
62 :
63 : /************************************************************************/
64 : /* OGRGMLDataSource() */
65 : /************************************************************************/
66 :
67 550 : OGRGMLDataSource::OGRGMLDataSource()
68 : : papoLayers(nullptr), nLayers(0), papszCreateOptions(nullptr),
69 : fpOutput(nullptr), bFpOutputIsNonSeekable(false),
70 : bFpOutputSingleFile(false), bBBOX3D(false), nBoundedByLocation(-1),
71 : nSchemaInsertLocation(-1), bIsOutputGML3(false),
72 : bIsOutputGML3Deegree(false), bIsOutputGML32(false),
73 : eSRSNameFormat(SRSNAME_SHORT), bWriteSpaceIndentation(true),
74 : poReader(nullptr), bOutIsTempFile(false), bExposeGMLId(false),
75 : bExposeFid(false), bIsWFS(false), bUseGlobalSRSName(false),
76 : m_bInvertAxisOrderIfLatLong(false), m_bConsiderEPSGAsURN(false),
77 : m_eSwapCoordinates(GML_SWAP_AUTO), m_bGetSecondaryGeometryOption(false),
78 : eReadMode(STANDARD), poStoredGMLFeature(nullptr),
79 550 : poLastReadLayer(nullptr), bEmptyAsNull(true)
80 : {
81 550 : }
82 :
83 : /************************************************************************/
84 : /* ~OGRGMLDataSource() */
85 : /************************************************************************/
86 :
87 1100 : OGRGMLDataSource::~OGRGMLDataSource()
88 : {
89 550 : OGRGMLDataSource::Close();
90 1100 : }
91 :
92 : /************************************************************************/
93 : /* Close() */
94 : /************************************************************************/
95 :
96 1086 : CPLErr OGRGMLDataSource::Close()
97 : {
98 1086 : CPLErr eErr = CE_None;
99 1086 : if (nOpenFlags != OPEN_FLAGS_CLOSED)
100 : {
101 1086 : if (fpOutput && !m_bWriteError)
102 : {
103 99 : if (nLayers == 0)
104 3 : WriteTopElements();
105 :
106 99 : const char *pszPrefix = GetAppPrefix();
107 99 : if (GMLFeatureCollection())
108 1 : PrintLine(fpOutput, "</gml:FeatureCollection>");
109 98 : else if (RemoveAppPrefix())
110 2 : PrintLine(fpOutput, "</FeatureCollection>");
111 : else
112 96 : PrintLine(fpOutput, "</%s:FeatureCollection>", pszPrefix);
113 :
114 99 : if (bFpOutputIsNonSeekable)
115 : {
116 0 : VSIFCloseL(fpOutput);
117 0 : fpOutput = nullptr;
118 : }
119 :
120 99 : InsertHeader();
121 :
122 198 : if (!bFpOutputIsNonSeekable && nBoundedByLocation != -1 &&
123 99 : VSIFSeekL(fpOutput, nBoundedByLocation, SEEK_SET) == 0)
124 : {
125 166 : if (m_bWriteGlobalSRS && sBoundingRect.IsInit() &&
126 67 : IsGML3Output())
127 : {
128 57 : bool bCoordSwap = false;
129 : char *pszSRSName =
130 : m_poWriteGlobalSRS
131 57 : ? GML_GetSRSName(m_poWriteGlobalSRS.get(),
132 : eSRSNameFormat, &bCoordSwap)
133 95 : : CPLStrdup("");
134 57 : char szLowerCorner[75] = {};
135 57 : char szUpperCorner[75] = {};
136 :
137 57 : OGRWktOptions coordOpts;
138 :
139 57 : if (OGRGMLDataSource::GetLayerCount() == 1)
140 : {
141 41 : OGRLayer *poLayer = OGRGMLDataSource::GetLayer(0);
142 41 : if (poLayer->GetLayerDefn()->GetGeomFieldCount() == 1)
143 : {
144 : const auto &oCoordPrec =
145 37 : poLayer->GetLayerDefn()
146 37 : ->GetGeomFieldDefn(0)
147 37 : ->GetCoordinatePrecision();
148 37 : if (oCoordPrec.dfXYResolution !=
149 : OGRGeomCoordinatePrecision::UNKNOWN)
150 : {
151 1 : coordOpts.format = OGRWktFormat::F;
152 1 : coordOpts.xyPrecision =
153 : OGRGeomCoordinatePrecision::
154 1 : ResolutionToPrecision(
155 1 : oCoordPrec.dfXYResolution);
156 : }
157 37 : if (oCoordPrec.dfZResolution !=
158 : OGRGeomCoordinatePrecision::UNKNOWN)
159 : {
160 1 : coordOpts.format = OGRWktFormat::F;
161 1 : coordOpts.zPrecision =
162 : OGRGeomCoordinatePrecision::
163 1 : ResolutionToPrecision(
164 1 : oCoordPrec.dfZResolution);
165 : }
166 : }
167 : }
168 :
169 114 : std::string wkt;
170 57 : if (bCoordSwap)
171 : {
172 22 : wkt = OGRMakeWktCoordinate(
173 : sBoundingRect.MinY, sBoundingRect.MinX,
174 22 : sBoundingRect.MinZ, bBBOX3D ? 3 : 2, coordOpts);
175 11 : memcpy(szLowerCorner, wkt.data(), wkt.size() + 1);
176 :
177 22 : wkt = OGRMakeWktCoordinate(
178 : sBoundingRect.MaxY, sBoundingRect.MaxX,
179 22 : sBoundingRect.MaxZ, bBBOX3D ? 3 : 2, coordOpts);
180 11 : memcpy(szUpperCorner, wkt.data(), wkt.size() + 1);
181 : }
182 : else
183 : {
184 92 : wkt = OGRMakeWktCoordinate(
185 : sBoundingRect.MinX, sBoundingRect.MinY,
186 92 : sBoundingRect.MinZ, bBBOX3D ? 3 : 2, coordOpts);
187 46 : memcpy(szLowerCorner, wkt.data(), wkt.size() + 1);
188 :
189 92 : wkt = OGRMakeWktCoordinate(
190 : sBoundingRect.MaxX, sBoundingRect.MaxY,
191 92 : sBoundingRect.MaxZ, (bBBOX3D) ? 3 : 2, coordOpts);
192 46 : memcpy(szUpperCorner, wkt.data(), wkt.size() + 1);
193 : }
194 57 : if (bWriteSpaceIndentation)
195 57 : VSIFPrintfL(fpOutput, " ");
196 57 : PrintLine(
197 : fpOutput,
198 : "<gml:boundedBy><gml:Envelope%s%s><gml:lowerCorner>%s"
199 : "</gml:lowerCorner><gml:upperCorner>%s</"
200 : "gml:upperCorner>"
201 : "</gml:Envelope></gml:boundedBy>",
202 57 : bBBOX3D ? " srsDimension=\"3\"" : "", pszSRSName,
203 : szLowerCorner, szUpperCorner);
204 57 : CPLFree(pszSRSName);
205 : }
206 42 : else if (m_bWriteGlobalSRS && sBoundingRect.IsInit())
207 : {
208 10 : if (bWriteSpaceIndentation)
209 10 : VSIFPrintfL(fpOutput, " ");
210 10 : PrintLine(fpOutput, "<gml:boundedBy>");
211 10 : if (bWriteSpaceIndentation)
212 10 : VSIFPrintfL(fpOutput, " ");
213 10 : PrintLine(fpOutput, "<gml:Box>");
214 10 : if (bWriteSpaceIndentation)
215 10 : VSIFPrintfL(fpOutput, " ");
216 10 : VSIFPrintfL(fpOutput,
217 : "<gml:coord><gml:X>%.16g</gml:X>"
218 : "<gml:Y>%.16g</gml:Y>",
219 : sBoundingRect.MinX, sBoundingRect.MinY);
220 10 : if (bBBOX3D)
221 1 : VSIFPrintfL(fpOutput, "<gml:Z>%.16g</gml:Z>",
222 : sBoundingRect.MinZ);
223 10 : PrintLine(fpOutput, "</gml:coord>");
224 10 : if (bWriteSpaceIndentation)
225 10 : VSIFPrintfL(fpOutput, " ");
226 10 : VSIFPrintfL(fpOutput,
227 : "<gml:coord><gml:X>%.16g</gml:X>"
228 : "<gml:Y>%.16g</gml:Y>",
229 : sBoundingRect.MaxX, sBoundingRect.MaxY);
230 10 : if (bBBOX3D)
231 1 : VSIFPrintfL(fpOutput, "<gml:Z>%.16g</gml:Z>",
232 : sBoundingRect.MaxZ);
233 10 : PrintLine(fpOutput, "</gml:coord>");
234 10 : if (bWriteSpaceIndentation)
235 10 : VSIFPrintfL(fpOutput, " ");
236 10 : PrintLine(fpOutput, "</gml:Box>");
237 10 : if (bWriteSpaceIndentation)
238 10 : VSIFPrintfL(fpOutput, " ");
239 10 : PrintLine(fpOutput, "</gml:boundedBy>");
240 : }
241 : else
242 : {
243 32 : if (bWriteSpaceIndentation)
244 32 : VSIFPrintfL(fpOutput, " ");
245 32 : if (IsGML3Output())
246 32 : PrintLine(
247 : fpOutput,
248 : "<gml:boundedBy><gml:Null /></gml:boundedBy>");
249 : else
250 0 : PrintLine(fpOutput, "<gml:boundedBy><gml:null>missing"
251 : "</gml:null></gml:boundedBy>");
252 : }
253 : }
254 : }
255 :
256 1086 : if (fpOutput)
257 100 : VSIFCloseL(fpOutput);
258 1086 : fpOutput = nullptr;
259 :
260 1086 : CSLDestroy(papszCreateOptions);
261 1086 : papszCreateOptions = nullptr;
262 :
263 1791 : for (int i = 0; i < nLayers; i++)
264 705 : delete papoLayers[i];
265 1086 : CPLFree(papoLayers);
266 1086 : papoLayers = nullptr;
267 1086 : nLayers = 0;
268 :
269 1086 : if (poReader)
270 : {
271 446 : if (bOutIsTempFile)
272 0 : VSIUnlink(poReader->GetSourceFileName());
273 446 : delete poReader;
274 446 : poReader = nullptr;
275 : }
276 :
277 1086 : delete poStoredGMLFeature;
278 1086 : poStoredGMLFeature = nullptr;
279 :
280 1086 : if (m_bUnlinkXSDFilename)
281 : {
282 7 : VSIUnlink(osXSDFilename);
283 7 : m_bUnlinkXSDFilename = false;
284 : }
285 :
286 1086 : if (m_bWriteError)
287 4 : eErr = CE_Failure;
288 : }
289 1086 : return eErr;
290 : }
291 :
292 : /************************************************************************/
293 : /* CheckHeader() */
294 : /************************************************************************/
295 :
296 1641 : bool OGRGMLDataSource::CheckHeader(const char *pszStr)
297 : {
298 1641 : if (strstr(pszStr, "<wfs:FeatureCollection ") != nullptr)
299 378 : return true;
300 :
301 1263 : if (strstr(pszStr, "opengis.net/gml") == nullptr &&
302 420 : strstr(pszStr, "<csw:GetRecordsResponse") == nullptr)
303 : {
304 363 : return false;
305 : }
306 :
307 : // Ignore kml files
308 900 : if (strstr(pszStr, "<kml") != nullptr)
309 : {
310 0 : return false;
311 : }
312 :
313 : // Ignore .xsd schemas.
314 900 : if (strstr(pszStr, "<schema") != nullptr ||
315 899 : strstr(pszStr, "<xs:schema") != nullptr ||
316 899 : strstr(pszStr, "<xsd:schema") != nullptr)
317 : {
318 3 : return false;
319 : }
320 :
321 : // Ignore GeoRSS documents. They will be recognized by the GeoRSS driver.
322 897 : if (strstr(pszStr, "<rss") != nullptr &&
323 4 : strstr(pszStr, "xmlns:georss") != nullptr)
324 : {
325 4 : return false;
326 : }
327 :
328 : // Ignore OpenJUMP .jml documents.
329 : // They will be recognized by the OpenJUMP driver.
330 893 : if (strstr(pszStr, "<JCSDataFile") != nullptr)
331 : {
332 42 : return false;
333 : }
334 :
335 : // Ignore OGR WFS xml description files, or WFS Capabilities results.
336 851 : if (strstr(pszStr, "<OGRWFSDataSource>") != nullptr ||
337 849 : strstr(pszStr, "<wfs:WFS_Capabilities") != nullptr)
338 : {
339 2 : return false;
340 : }
341 :
342 : // Ignore WMTS capabilities results.
343 849 : if (strstr(pszStr, "http://www.opengis.net/wmts/1.0") != nullptr)
344 : {
345 1 : return false;
346 : }
347 :
348 848 : return true;
349 : }
350 :
351 : /************************************************************************/
352 : /* ExtractSRSName() */
353 : /************************************************************************/
354 :
355 27 : static bool ExtractSRSName(const char *pszXML, char *szSRSName,
356 : size_t sizeof_szSRSName)
357 : {
358 27 : szSRSName[0] = '\0';
359 :
360 27 : const char *pszSRSName = strstr(pszXML, "srsName=\"");
361 27 : if (pszSRSName != nullptr)
362 : {
363 23 : pszSRSName += 9;
364 23 : const char *pszEndQuote = strchr(pszSRSName, '"');
365 23 : if (pszEndQuote != nullptr &&
366 23 : static_cast<size_t>(pszEndQuote - pszSRSName) < sizeof_szSRSName)
367 : {
368 23 : memcpy(szSRSName, pszSRSName, pszEndQuote - pszSRSName);
369 23 : szSRSName[pszEndQuote - pszSRSName] = '\0';
370 23 : return true;
371 : }
372 : }
373 4 : return false;
374 : }
375 :
376 : /************************************************************************/
377 : /* Open() */
378 : /************************************************************************/
379 :
380 449 : bool OGRGMLDataSource::Open(GDALOpenInfo *poOpenInfo)
381 :
382 : {
383 : // Extract XSD filename from connection string if present.
384 449 : osFilename = poOpenInfo->pszFilename;
385 449 : const char *pszXSDFilenameTmp = strstr(poOpenInfo->pszFilename, ",xsd=");
386 449 : if (pszXSDFilenameTmp != nullptr)
387 : {
388 2 : osFilename.resize(pszXSDFilenameTmp - poOpenInfo->pszFilename);
389 2 : osXSDFilename = pszXSDFilenameTmp + strlen(",xsd=");
390 : }
391 : else
392 : {
393 : osXSDFilename =
394 447 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "XSD", "");
395 : }
396 :
397 449 : const char *pszFilename = osFilename.c_str();
398 :
399 : // Open the source file.
400 449 : VSILFILE *fpToClose = nullptr;
401 449 : VSILFILE *fp = nullptr;
402 449 : if (poOpenInfo->fpL != nullptr)
403 : {
404 447 : fp = poOpenInfo->fpL;
405 447 : VSIFSeekL(fp, 0, SEEK_SET);
406 : }
407 : else
408 : {
409 2 : fp = VSIFOpenL(pszFilename, "r");
410 2 : if (fp == nullptr)
411 0 : return false;
412 2 : fpToClose = fp;
413 : }
414 :
415 : // Load a header chunk and check for signs it is GML.
416 449 : char szHeader[4096] = {};
417 449 : size_t nRead = VSIFReadL(szHeader, 1, sizeof(szHeader) - 1, fp);
418 449 : if (nRead == 0)
419 : {
420 0 : if (fpToClose)
421 0 : VSIFCloseL(fpToClose);
422 0 : return false;
423 : }
424 449 : szHeader[nRead] = '\0';
425 :
426 898 : CPLString osWithVsiGzip;
427 :
428 : // Might be a OS-Mastermap gzipped GML, so let be nice and try to open
429 : // it transparently with /vsigzip/.
430 900 : if (static_cast<GByte>(szHeader[0]) == 0x1f &&
431 2 : static_cast<GByte>(szHeader[1]) == 0x8b &&
432 453 : EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "gz") &&
433 2 : !STARTS_WITH(pszFilename, "/vsigzip/"))
434 : {
435 2 : if (fpToClose)
436 0 : VSIFCloseL(fpToClose);
437 2 : fpToClose = nullptr;
438 2 : osWithVsiGzip = "/vsigzip/";
439 2 : osWithVsiGzip += pszFilename;
440 :
441 2 : pszFilename = osWithVsiGzip;
442 :
443 2 : fp = fpToClose = VSIFOpenL(pszFilename, "r");
444 2 : if (fp == nullptr)
445 0 : return false;
446 :
447 2 : nRead = VSIFReadL(szHeader, 1, sizeof(szHeader) - 1, fp);
448 2 : if (nRead == 0)
449 : {
450 0 : VSIFCloseL(fpToClose);
451 0 : return false;
452 : }
453 2 : szHeader[nRead] = '\0';
454 : }
455 :
456 : // Check for a UTF-8 BOM and skip if found.
457 :
458 : // TODO: BOM is variable-length parameter and depends on encoding. */
459 : // Add BOM detection for other encodings.
460 :
461 : // Used to skip to actual beginning of XML data
462 449 : char *szPtr = szHeader;
463 :
464 449 : if ((static_cast<unsigned char>(szHeader[0]) == 0xEF) &&
465 4 : (static_cast<unsigned char>(szHeader[1]) == 0xBB) &&
466 4 : (static_cast<unsigned char>(szHeader[2]) == 0xBF))
467 : {
468 4 : szPtr += 3;
469 : }
470 :
471 449 : bool bExpatCompatibleEncoding = false;
472 :
473 449 : const char *pszEncoding = strstr(szPtr, "encoding=");
474 449 : if (pszEncoding)
475 362 : bExpatCompatibleEncoding =
476 724 : (pszEncoding[9] == '\'' || pszEncoding[9] == '"') &&
477 362 : (STARTS_WITH_CI(pszEncoding + 10, "UTF-8") ||
478 2 : STARTS_WITH_CI(pszEncoding + 10, "ISO-8859-15") ||
479 2 : (STARTS_WITH_CI(pszEncoding + 10, "ISO-8859-1") &&
480 2 : pszEncoding[20] == pszEncoding[9]));
481 : else
482 87 : bExpatCompatibleEncoding = true; // utf-8 is the default.
483 :
484 867 : const bool bHas3D = strstr(szPtr, "srsDimension=\"3\"") != nullptr ||
485 418 : strstr(szPtr, "<gml:Z>") != nullptr;
486 :
487 : // Here, we expect the opening chevrons of GML tree root element.
488 449 : if (szPtr[0] != '<' || !CheckHeader(szPtr))
489 : {
490 3 : if (fpToClose)
491 0 : VSIFCloseL(fpToClose);
492 3 : return false;
493 : }
494 :
495 : // Now we definitely own the file descriptor.
496 446 : if (fp == poOpenInfo->fpL)
497 442 : poOpenInfo->fpL = nullptr;
498 :
499 : // Small optimization: if we parse a <wfs:FeatureCollection> and
500 : // that numberOfFeatures is set, we can use it to set the FeatureCount
501 : // but *ONLY* if there's just one class.
502 446 : const char *pszFeatureCollection = strstr(szPtr, "wfs:FeatureCollection");
503 446 : if (pszFeatureCollection == nullptr)
504 : // GML 3.2.1 output.
505 300 : pszFeatureCollection = strstr(szPtr, "gml:FeatureCollection");
506 446 : if (pszFeatureCollection == nullptr)
507 : {
508 : // Deegree WFS 1.0.0 output.
509 284 : pszFeatureCollection = strstr(szPtr, "<FeatureCollection");
510 284 : if (pszFeatureCollection &&
511 7 : strstr(szPtr, "xmlns:wfs=\"http://www.opengis.net/wfs\"") ==
512 : nullptr)
513 6 : pszFeatureCollection = nullptr;
514 : }
515 :
516 446 : GIntBig nNumberOfFeatures = 0;
517 446 : if (pszFeatureCollection)
518 : {
519 163 : bExposeGMLId = true;
520 163 : bIsWFS = true;
521 163 : const char *pszNumberOfFeatures = strstr(szPtr, "numberOfFeatures=");
522 163 : if (pszNumberOfFeatures)
523 : {
524 46 : pszNumberOfFeatures += 17;
525 46 : char ch = pszNumberOfFeatures[0];
526 46 : if ((ch == '\'' || ch == '"') &&
527 46 : strchr(pszNumberOfFeatures + 1, ch) != nullptr)
528 : {
529 46 : nNumberOfFeatures = CPLAtoGIntBig(pszNumberOfFeatures + 1);
530 : }
531 : }
532 117 : else if ((pszNumberOfFeatures = strstr(szPtr, "numberReturned=")) !=
533 : nullptr)
534 : {
535 : // WFS 2.0.0
536 94 : pszNumberOfFeatures += 15;
537 94 : char ch = pszNumberOfFeatures[0];
538 94 : if ((ch == '\'' || ch == '"') &&
539 94 : strchr(pszNumberOfFeatures + 1, ch) != nullptr)
540 : {
541 : // 'unknown' might be a valid value in a corrected version of
542 : // WFS 2.0 but it will also evaluate to 0, that is considered as
543 : // unknown, so nothing particular to do.
544 94 : nNumberOfFeatures = CPLAtoGIntBig(pszNumberOfFeatures + 1);
545 : }
546 : }
547 : }
548 283 : else if (STARTS_WITH(pszFilename, "/vsimem/") &&
549 132 : strstr(pszFilename, "_ogr_wfs_"))
550 : {
551 : // http://regis.intergraph.com/wfs/dcmetro/request.asp? returns a
552 : // <G:FeatureCollection> Who knows what servers can return? When
553 : // in the context of the WFS driver always expose the gml:id to avoid
554 : // later crashes.
555 0 : bExposeGMLId = true;
556 0 : bIsWFS = true;
557 : }
558 : else
559 : {
560 388 : bExposeGMLId = strstr(szPtr, " gml:id=\"") != nullptr ||
561 105 : strstr(szPtr, " gml:id='") != nullptr;
562 494 : bExposeFid = strstr(szPtr, " fid=\"") != nullptr ||
563 211 : strstr(szPtr, " fid='") != nullptr;
564 : }
565 :
566 : const char *pszExposeGMLId =
567 446 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "EXPOSE_GML_ID",
568 : CPLGetConfigOption("GML_EXPOSE_GML_ID", nullptr));
569 446 : if (pszExposeGMLId)
570 64 : bExposeGMLId = CPLTestBool(pszExposeGMLId);
571 :
572 : const char *pszExposeFid =
573 446 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "EXPOSE_FID",
574 : CPLGetConfigOption("GML_EXPOSE_FID", nullptr));
575 :
576 446 : if (pszExposeFid)
577 1 : bExposeFid = CPLTestBool(pszExposeFid);
578 :
579 446 : const bool bHintConsiderEPSGAsURN =
580 446 : strstr(szPtr, "xmlns:fme=\"http://www.safe.com/gml/fme\"") != nullptr;
581 :
582 446 : char szSRSName[128] = {};
583 :
584 : // MTKGML.
585 446 : if (strstr(szPtr, "<Maastotiedot") != nullptr)
586 : {
587 3 : if (strstr(szPtr,
588 : "http://xml.nls.fi/XML/Namespace/"
589 : "Maastotietojarjestelma/SiirtotiedostonMalli/2011-02") ==
590 : nullptr)
591 1 : CPLDebug("GML", "Warning: a MTKGML file was detected, "
592 : "but its namespace is unknown");
593 3 : bUseGlobalSRSName = true;
594 3 : if (!ExtractSRSName(szPtr, szSRSName, sizeof(szSRSName)))
595 1 : strcpy(szSRSName, "EPSG:3067");
596 : }
597 :
598 446 : const char *pszSchemaLocation = strstr(szPtr, "schemaLocation=");
599 446 : if (pszSchemaLocation)
600 390 : pszSchemaLocation += strlen("schemaLocation=");
601 :
602 446 : bool bCheckAuxFile = true;
603 446 : if (STARTS_WITH(pszFilename, "/vsicurl_streaming/"))
604 2 : bCheckAuxFile = false;
605 444 : else if (STARTS_WITH(pszFilename, "/vsicurl/") &&
606 1 : (strstr(pszFilename, "?SERVICE=") ||
607 1 : strstr(pszFilename, "&SERVICE=")))
608 0 : bCheckAuxFile = false;
609 :
610 446 : bool bIsWFSJointLayer = bIsWFS && strstr(szPtr, "<wfs:Tuple>");
611 446 : if (bIsWFSJointLayer)
612 50 : bExposeGMLId = false;
613 :
614 : // We assume now that it is GML. Instantiate a GMLReader on it.
615 : const char *pszReadMode =
616 446 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "READ_MODE",
617 : CPLGetConfigOption("GML_READ_MODE", "AUTO"));
618 446 : if (EQUAL(pszReadMode, "AUTO"))
619 443 : pszReadMode = nullptr;
620 446 : if (pszReadMode == nullptr || EQUAL(pszReadMode, "STANDARD"))
621 443 : eReadMode = STANDARD;
622 3 : else if (EQUAL(pszReadMode, "SEQUENTIAL_LAYERS"))
623 2 : eReadMode = SEQUENTIAL_LAYERS;
624 1 : else if (EQUAL(pszReadMode, "INTERLEAVED_LAYERS"))
625 1 : eReadMode = INTERLEAVED_LAYERS;
626 : else
627 : {
628 0 : CPLDebug("GML",
629 : "Unrecognized value for GML_READ_MODE configuration option.");
630 : }
631 :
632 892 : m_bInvertAxisOrderIfLatLong = CPLTestBool(CSLFetchNameValueDef(
633 446 : poOpenInfo->papszOpenOptions, "INVERT_AXIS_ORDER_IF_LAT_LONG",
634 : CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG", "YES")));
635 :
636 446 : const char *pszConsiderEPSGAsURN = CSLFetchNameValueDef(
637 446 : poOpenInfo->papszOpenOptions, "CONSIDER_EPSG_AS_URN",
638 : CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", "AUTO"));
639 446 : if (!EQUAL(pszConsiderEPSGAsURN, "AUTO"))
640 0 : m_bConsiderEPSGAsURN = CPLTestBool(pszConsiderEPSGAsURN);
641 446 : else if (bHintConsiderEPSGAsURN)
642 : {
643 : // GML produced by FME (at least CanVec GML) seem to honour EPSG axis
644 : // ordering.
645 5 : CPLDebug("GML", "FME-produced GML --> "
646 : "consider that GML_CONSIDER_EPSG_AS_URN is set to YES");
647 5 : m_bConsiderEPSGAsURN = true;
648 : }
649 : else
650 : {
651 441 : m_bConsiderEPSGAsURN = false;
652 : }
653 :
654 446 : const char *pszSwapCoordinates = CSLFetchNameValueDef(
655 446 : poOpenInfo->papszOpenOptions, "SWAP_COORDINATES",
656 : CPLGetConfigOption("GML_SWAP_COORDINATES", "AUTO"));
657 452 : m_eSwapCoordinates = EQUAL(pszSwapCoordinates, "AUTO") ? GML_SWAP_AUTO
658 6 : : CPLTestBool(pszSwapCoordinates) ? GML_SWAP_YES
659 : : GML_SWAP_NO;
660 :
661 446 : m_bGetSecondaryGeometryOption =
662 446 : CPLTestBool(CPLGetConfigOption("GML_GET_SECONDARY_GEOM", "NO"));
663 :
664 : // EXPAT is faster than Xerces, so when it is safe to use it, use it!
665 : // The only interest of Xerces is for rare encodings that Expat doesn't
666 : // handle, but UTF-8 is well handled by Expat.
667 446 : bool bUseExpatParserPreferably = bExpatCompatibleEncoding;
668 :
669 : // Override default choice.
670 446 : const char *pszGMLParser = CPLGetConfigOption("GML_PARSER", nullptr);
671 446 : if (pszGMLParser)
672 : {
673 4 : if (EQUAL(pszGMLParser, "EXPAT"))
674 2 : bUseExpatParserPreferably = true;
675 2 : else if (EQUAL(pszGMLParser, "XERCES"))
676 2 : bUseExpatParserPreferably = false;
677 : }
678 :
679 446 : poReader =
680 892 : CreateGMLReader(bUseExpatParserPreferably, m_bInvertAxisOrderIfLatLong,
681 446 : m_bConsiderEPSGAsURN, m_eSwapCoordinates,
682 446 : m_bGetSecondaryGeometryOption);
683 446 : if (poReader == nullptr)
684 : {
685 0 : CPLError(CE_Failure, CPLE_AppDefined,
686 : "File %s appears to be GML but the GML reader can't\n"
687 : "be instantiated, likely because Xerces or Expat support was\n"
688 : "not configured in.",
689 : pszFilename);
690 0 : VSIFCloseL(fp);
691 0 : return false;
692 : }
693 :
694 446 : poReader->SetSourceFile(pszFilename);
695 446 : auto poGMLReader = cpl::down_cast<GMLReader *>(poReader);
696 446 : poGMLReader->SetIsWFSJointLayer(bIsWFSJointLayer);
697 446 : bEmptyAsNull =
698 446 : CPLFetchBool(poOpenInfo->papszOpenOptions, "EMPTY_AS_NULL", true);
699 446 : poGMLReader->SetEmptyAsNull(bEmptyAsNull);
700 446 : poGMLReader->SetReportAllAttributes(CPLFetchBool(
701 446 : poOpenInfo->papszOpenOptions, "GML_ATTRIBUTES_TO_OGR_FIELDS",
702 446 : CPLTestBool(CPLGetConfigOption("GML_ATTRIBUTES_TO_OGR_FIELDS", "NO"))));
703 446 : poGMLReader->SetUseBBOX(
704 446 : CPLFetchBool(poOpenInfo->papszOpenOptions, "USE_BBOX", false));
705 :
706 : // Find <gml:description>, <gml:name> and <gml:boundedBy> and if it is
707 : // a standalone geometry
708 : // Also look for <gml:description>, <gml:identifier> and <gml:name> inside
709 : // a feature
710 446 : FindAndParseTopElements(fp);
711 :
712 446 : if (m_poStandaloneGeom)
713 : {
714 1 : papoLayers = static_cast<OGRLayer **>(CPLMalloc(sizeof(OGRLayer *)));
715 1 : nLayers = 1;
716 : auto poLayer = new OGRMemLayer(
717 : "geometry",
718 1 : m_oStandaloneGeomSRS.IsEmpty() ? nullptr : &m_oStandaloneGeomSRS,
719 1 : m_poStandaloneGeom->getGeometryType());
720 1 : papoLayers[0] = poLayer;
721 1 : OGRFeature *poFeature = new OGRFeature(poLayer->GetLayerDefn());
722 1 : poFeature->SetGeometryDirectly(m_poStandaloneGeom.release());
723 1 : CPL_IGNORE_RET_VAL(poLayer->CreateFeature(poFeature));
724 1 : delete poFeature;
725 1 : poLayer->SetUpdatable(false);
726 1 : VSIFCloseL(fp);
727 1 : return true;
728 : }
729 :
730 445 : if (szSRSName[0] != '\0')
731 3 : poReader->SetGlobalSRSName(szSRSName);
732 :
733 : const bool bIsWFSFromServer =
734 445 : CPLString(pszFilename).ifind("SERVICE=WFS") != std::string::npos;
735 :
736 : // Resolve the xlinks in the source file and save it with the
737 : // extension ".resolved.gml". The source file will to set to that.
738 445 : char *pszXlinkResolvedFilename = nullptr;
739 445 : const char *pszOption = CPLGetConfigOption("GML_SAVE_RESOLVED_TO", nullptr);
740 445 : bool bResolve = true;
741 445 : bool bHugeFile = false;
742 445 : if (bIsWFSFromServer ||
743 0 : (pszOption != nullptr && STARTS_WITH_CI(pszOption, "SAME")))
744 : {
745 : // "SAME" will overwrite the existing gml file.
746 59 : pszXlinkResolvedFilename = CPLStrdup(pszFilename);
747 : }
748 386 : else if (pszOption != nullptr && CPLStrnlen(pszOption, 5) >= 5 &&
749 0 : STARTS_WITH_CI(pszOption - 4 + strlen(pszOption), ".gml"))
750 : {
751 : // Any string ending with ".gml" will try and write to it.
752 0 : pszXlinkResolvedFilename = CPLStrdup(pszOption);
753 : }
754 : else
755 : {
756 : // When no option is given or is not recognised,
757 : // use the same file name with the extension changed to .resolved.gml
758 386 : pszXlinkResolvedFilename = CPLStrdup(
759 772 : CPLResetExtensionSafe(pszFilename, "resolved.gml").c_str());
760 :
761 : // Check if the file already exists.
762 : VSIStatBufL sResStatBuf, sGMLStatBuf;
763 772 : if (bCheckAuxFile &&
764 386 : VSIStatL(pszXlinkResolvedFilename, &sResStatBuf) == 0)
765 : {
766 10 : if (VSIStatL(pszFilename, &sGMLStatBuf) == 0 &&
767 5 : sGMLStatBuf.st_mtime > sResStatBuf.st_mtime)
768 : {
769 0 : CPLDebug("GML",
770 : "Found %s but ignoring because it appears\n"
771 : "be older than the associated GML file.",
772 : pszXlinkResolvedFilename);
773 : }
774 : else
775 : {
776 5 : poReader->SetSourceFile(pszXlinkResolvedFilename);
777 5 : bResolve = false;
778 : }
779 : }
780 : }
781 :
782 445 : const char *pszSkipOption = CSLFetchNameValueDef(
783 445 : poOpenInfo->papszOpenOptions, "SKIP_RESOLVE_ELEMS",
784 : CPLGetConfigOption("GML_SKIP_RESOLVE_ELEMS", "ALL"));
785 :
786 445 : char **papszSkip = nullptr;
787 445 : if (EQUAL(pszSkipOption, "ALL"))
788 432 : bResolve = false;
789 13 : else if (EQUAL(pszSkipOption, "HUGE"))
790 : // Exactly as NONE, but intended for HUGE files
791 5 : bHugeFile = true;
792 8 : else if (!EQUAL(pszSkipOption, "NONE")) // Use this to resolve everything.
793 0 : papszSkip = CSLTokenizeString2(
794 : pszSkipOption, ",", CSLT_STRIPLEADSPACES | CSLT_STRIPENDSPACES);
795 445 : bool bHaveSchema = false;
796 445 : bool bSchemaDone = false;
797 :
798 : // Is some GML Feature Schema (.gfs) TEMPLATE required?
799 : const char *pszGFSTemplateName =
800 445 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "GFS_TEMPLATE",
801 : CPLGetConfigOption("GML_GFS_TEMPLATE", nullptr));
802 445 : if (pszGFSTemplateName != nullptr)
803 : {
804 : // Attempt to load the GFS TEMPLATE.
805 2 : bHaveSchema = poReader->LoadClasses(pszGFSTemplateName);
806 : }
807 :
808 445 : if (bResolve)
809 : {
810 13 : if (bHugeFile)
811 : {
812 5 : bSchemaDone = true;
813 : bool bSqliteIsTempFile =
814 5 : CPLTestBool(CPLGetConfigOption("GML_HUGE_TEMPFILE", "YES"));
815 : int iSqliteCacheMB =
816 5 : atoi(CPLGetConfigOption("OGR_SQLITE_CACHE", "0"));
817 10 : if (poReader->HugeFileResolver(pszXlinkResolvedFilename,
818 : bSqliteIsTempFile,
819 5 : iSqliteCacheMB) == false)
820 : {
821 : // Assume an error has been reported.
822 0 : VSIFCloseL(fp);
823 0 : CPLFree(pszXlinkResolvedFilename);
824 0 : return false;
825 : }
826 : }
827 : else
828 : {
829 8 : poReader->ResolveXlinks(pszXlinkResolvedFilename, &bOutIsTempFile,
830 8 : papszSkip);
831 : }
832 : }
833 :
834 445 : CPLFree(pszXlinkResolvedFilename);
835 445 : pszXlinkResolvedFilename = nullptr;
836 445 : CSLDestroy(papszSkip);
837 445 : papszSkip = nullptr;
838 :
839 : // If the source filename for the reader is still the GML filename, then
840 : // we can directly provide the file pointer. Otherwise close it.
841 445 : if (strcmp(poReader->GetSourceFileName(), pszFilename) == 0)
842 427 : poReader->SetFP(fp);
843 : else
844 18 : VSIFCloseL(fp);
845 445 : fp = nullptr;
846 :
847 : // Is a prescan required?
848 445 : if (bHaveSchema && !bSchemaDone)
849 : {
850 : // We must detect which layers are actually present in the .gml
851 : // and how many features they have.
852 2 : if (!poReader->PrescanForTemplate())
853 : {
854 : // Assume an error has been reported.
855 0 : return false;
856 : }
857 : }
858 :
859 890 : CPLString osGFSFilename;
860 445 : if (!bIsWFSFromServer)
861 : {
862 386 : osGFSFilename = CPLResetExtensionSafe(pszFilename, "gfs");
863 386 : if (STARTS_WITH(osGFSFilename, "/vsigzip/"))
864 2 : osGFSFilename = osGFSFilename.substr(strlen("/vsigzip/"));
865 : }
866 :
867 : // Can we find a GML Feature Schema (.gfs) for the input file?
868 824 : if (!osGFSFilename.empty() && !bHaveSchema && !bSchemaDone &&
869 379 : osXSDFilename.empty())
870 : {
871 : VSIStatBufL sGFSStatBuf;
872 376 : if (bCheckAuxFile && VSIStatL(osGFSFilename, &sGFSStatBuf) == 0)
873 : {
874 : VSIStatBufL sGMLStatBuf;
875 102 : if (VSIStatL(pszFilename, &sGMLStatBuf) == 0 &&
876 51 : sGMLStatBuf.st_mtime > sGFSStatBuf.st_mtime)
877 : {
878 1 : CPLDebug("GML",
879 : "Found %s but ignoring because it appears\n"
880 : "be older than the associated GML file.",
881 : osGFSFilename.c_str());
882 : }
883 : else
884 : {
885 50 : bHaveSchema = poReader->LoadClasses(osGFSFilename);
886 50 : if (bHaveSchema)
887 : {
888 : const std::string osXSDFilenameTmp =
889 96 : CPLResetExtensionSafe(pszFilename, "xsd");
890 48 : if (VSIStatExL(osXSDFilenameTmp.c_str(), &sGMLStatBuf,
891 48 : VSI_STAT_EXISTS_FLAG) == 0)
892 : {
893 0 : CPLDebug("GML", "Using %s file, ignoring %s",
894 : osGFSFilename.c_str(),
895 : osXSDFilenameTmp.c_str());
896 : }
897 : }
898 : }
899 : }
900 : }
901 :
902 : // Can we find an xsd which might conform to the GML3 Level 0
903 : // profile? We really ought to look for it based on the rules
904 : // schemaLocation in the GML feature collection but for now we
905 : // just hopes it is in the same director with the same name.
906 :
907 445 : bool bHasFoundXSD = false;
908 :
909 445 : if (!bHaveSchema)
910 : {
911 395 : char **papszTypeNames = nullptr;
912 :
913 : VSIStatBufL sXSDStatBuf;
914 395 : if (osXSDFilename.empty())
915 : {
916 333 : osXSDFilename = CPLResetExtensionSafe(pszFilename, "xsd");
917 333 : if (bCheckAuxFile && VSIStatExL(osXSDFilename, &sXSDStatBuf,
918 : VSI_STAT_EXISTS_FLAG) == 0)
919 : {
920 213 : bHasFoundXSD = true;
921 : }
922 : }
923 : else
924 : {
925 62 : if (STARTS_WITH(osXSDFilename, "http://") ||
926 124 : STARTS_WITH(osXSDFilename, "https://") ||
927 62 : VSIStatExL(osXSDFilename, &sXSDStatBuf, VSI_STAT_EXISTS_FLAG) ==
928 : 0)
929 : {
930 62 : bHasFoundXSD = true;
931 : }
932 : }
933 :
934 : // If not found, try if there is a schema in the gml_registry.xml
935 : // that might match a declared namespace and featuretype.
936 395 : if (!bHasFoundXSD)
937 : {
938 : GMLRegistry oRegistry(
939 120 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "REGISTRY",
940 240 : CPLGetConfigOption("GML_REGISTRY", "")));
941 120 : if (oRegistry.Parse())
942 : {
943 240 : CPLString osHeader(szHeader);
944 805 : for (size_t iNS = 0; iNS < oRegistry.aoNamespaces.size(); iNS++)
945 : {
946 : GMLRegistryNamespace &oNamespace =
947 695 : oRegistry.aoNamespaces[iNS];
948 : // When namespace is omitted or fit with case sensitive
949 : // match for name space prefix, then go next to find feature
950 : // match.
951 : //
952 : // Case sensitive comparison since below test that also
953 : // uses the namespace prefix is case sensitive.
954 1277 : if (!oNamespace.osPrefix.empty() &&
955 582 : osHeader.find(CPLSPrintf(
956 : "xmlns:%s", oNamespace.osPrefix.c_str())) ==
957 : std::string::npos)
958 : {
959 : // namespace does not match with one of registry
960 : // definition. go to next entry.
961 575 : continue;
962 : }
963 :
964 : const char *pszURIToFind =
965 120 : CPLSPrintf("\"%s\"", oNamespace.osURI.c_str());
966 120 : if (strstr(szHeader, pszURIToFind) != nullptr)
967 : {
968 10 : if (oNamespace.bUseGlobalSRSName)
969 7 : bUseGlobalSRSName = true;
970 :
971 38 : for (size_t iTypename = 0;
972 38 : iTypename < oNamespace.aoFeatureTypes.size();
973 : iTypename++)
974 : {
975 38 : const char *pszElementToFind = nullptr;
976 :
977 : GMLRegistryFeatureType &oFeatureType =
978 38 : oNamespace.aoFeatureTypes[iTypename];
979 :
980 38 : if (!oNamespace.osPrefix.empty())
981 : {
982 15 : if (!oFeatureType.osElementValue.empty())
983 4 : pszElementToFind = CPLSPrintf(
984 : "%s:%s>%s", oNamespace.osPrefix.c_str(),
985 : oFeatureType.osElementName.c_str(),
986 : oFeatureType.osElementValue.c_str());
987 : else
988 11 : pszElementToFind = CPLSPrintf(
989 : "%s:%s", oNamespace.osPrefix.c_str(),
990 : oFeatureType.osElementName.c_str());
991 : }
992 : else
993 : {
994 23 : if (!oFeatureType.osElementValue.empty())
995 0 : pszElementToFind = CPLSPrintf(
996 : "%s>%s",
997 : oFeatureType.osElementName.c_str(),
998 : oFeatureType.osElementValue.c_str());
999 : else
1000 23 : pszElementToFind = CPLSPrintf(
1001 : "<%s",
1002 : oFeatureType.osElementName.c_str());
1003 : }
1004 :
1005 : // Case sensitive test since in a CadastralParcel
1006 : // feature there is a property basicPropertyUnit
1007 : // xlink, not to be confused with a top-level
1008 : // BasicPropertyUnit feature.
1009 38 : if (osHeader.find(pszElementToFind) !=
1010 : std::string::npos)
1011 : {
1012 10 : if (!oFeatureType.osSchemaLocation.empty())
1013 : {
1014 : osXSDFilename =
1015 1 : oFeatureType.osSchemaLocation;
1016 1 : if (STARTS_WITH(osXSDFilename, "http://") ||
1017 1 : STARTS_WITH(osXSDFilename,
1018 2 : "https://") ||
1019 1 : VSIStatExL(osXSDFilename, &sXSDStatBuf,
1020 : VSI_STAT_EXISTS_FLAG) == 0)
1021 : {
1022 1 : bHasFoundXSD = true;
1023 1 : bHaveSchema = true;
1024 1 : CPLDebug(
1025 : "GML",
1026 : "Found %s for %s:%s in registry",
1027 : osXSDFilename.c_str(),
1028 : oNamespace.osPrefix.c_str(),
1029 : oFeatureType.osElementName.c_str());
1030 : }
1031 : else
1032 : {
1033 0 : CPLDebug("GML", "Cannot open %s",
1034 : osXSDFilename.c_str());
1035 : }
1036 : }
1037 : else
1038 : {
1039 9 : bHaveSchema = poReader->LoadClasses(
1040 9 : oFeatureType.osGFSSchemaLocation);
1041 9 : if (bHaveSchema)
1042 : {
1043 9 : CPLDebug(
1044 : "GML",
1045 : "Found %s for %s:%s in registry",
1046 : oFeatureType.osGFSSchemaLocation
1047 : .c_str(),
1048 : oNamespace.osPrefix.c_str(),
1049 : oFeatureType.osElementName.c_str());
1050 : }
1051 : }
1052 10 : break;
1053 : }
1054 : }
1055 10 : break;
1056 : }
1057 : }
1058 : }
1059 : }
1060 :
1061 : /* For WFS, try to fetch the application schema */
1062 395 : if (bIsWFS && !bHaveSchema && pszSchemaLocation != nullptr &&
1063 142 : (pszSchemaLocation[0] == '\'' || pszSchemaLocation[0] == '"') &&
1064 142 : strchr(pszSchemaLocation + 1, pszSchemaLocation[0]) != nullptr)
1065 : {
1066 142 : char *pszSchemaLocationTmp1 = CPLStrdup(pszSchemaLocation + 1);
1067 142 : int nTruncLen = static_cast<int>(
1068 142 : strchr(pszSchemaLocation + 1, pszSchemaLocation[0]) -
1069 142 : (pszSchemaLocation + 1));
1070 142 : pszSchemaLocationTmp1[nTruncLen] = '\0';
1071 : char *pszSchemaLocationTmp2 =
1072 142 : CPLUnescapeString(pszSchemaLocationTmp1, nullptr, CPLES_XML);
1073 : CPLString osEscaped =
1074 284 : ReplaceSpaceByPct20IfNeeded(pszSchemaLocationTmp2);
1075 142 : CPLFree(pszSchemaLocationTmp2);
1076 142 : pszSchemaLocationTmp2 = CPLStrdup(osEscaped);
1077 142 : if (pszSchemaLocationTmp2)
1078 : {
1079 : // pszSchemaLocationTmp2 is of the form:
1080 : // http://namespace1 http://namespace1_schema_location
1081 : // http://namespace2 http://namespace1_schema_location2 So we
1082 : // try to find http://namespace1_schema_location that contains
1083 : // hints that it is the WFS application */ schema, i.e. if it
1084 : // contains typename= and request=DescribeFeatureType.
1085 : char **papszTokens =
1086 142 : CSLTokenizeString2(pszSchemaLocationTmp2, " \r\n", 0);
1087 142 : int nTokens = CSLCount(papszTokens);
1088 142 : if ((nTokens % 2) == 0)
1089 : {
1090 302 : for (int i = 0; i < nTokens; i += 2)
1091 : {
1092 286 : const char *pszEscapedURL = papszTokens[i + 1];
1093 286 : char *pszLocation = CPLUnescapeString(
1094 : pszEscapedURL, nullptr, CPLES_URL);
1095 286 : CPLString osLocation = pszLocation;
1096 286 : CPLFree(pszLocation);
1097 286 : if (osLocation.ifind("typename=") !=
1098 412 : std::string::npos &&
1099 126 : osLocation.ifind("request=DescribeFeatureType") !=
1100 : std::string::npos)
1101 : {
1102 : CPLString osTypeName =
1103 252 : CPLURLGetValue(osLocation, "typename");
1104 : papszTypeNames =
1105 126 : CSLTokenizeString2(osTypeName, ",", 0);
1106 :
1107 : // Old non-documented way
1108 : const char *pszGML_DOWNLOAD_WFS_SCHEMA =
1109 126 : CPLGetConfigOption("GML_DOWNLOAD_WFS_SCHEMA",
1110 : nullptr);
1111 126 : if (pszGML_DOWNLOAD_WFS_SCHEMA)
1112 : {
1113 0 : CPLError(
1114 : CE_Warning, CPLE_AppDefined,
1115 : "Configuration option "
1116 : "GML_DOWNLOAD_WFS_SCHEMA is deprecated. "
1117 : "Please use GML_DOWNLOAD_SCHEMA instead of "
1118 : "the DOWNLOAD_SCHEMA open option");
1119 : }
1120 : else
1121 : {
1122 126 : pszGML_DOWNLOAD_WFS_SCHEMA = "YES";
1123 : }
1124 134 : if (!bHasFoundXSD && CPLHTTPEnabled() &&
1125 8 : CPLFetchBool(poOpenInfo->papszOpenOptions,
1126 : "DOWNLOAD_SCHEMA",
1127 8 : CPLTestBool(CPLGetConfigOption(
1128 : "GML_DOWNLOAD_SCHEMA",
1129 : pszGML_DOWNLOAD_WFS_SCHEMA))))
1130 : {
1131 : CPLHTTPResult *psResult =
1132 8 : CPLHTTPFetch(pszEscapedURL, nullptr);
1133 8 : if (psResult)
1134 : {
1135 8 : if (psResult->nStatus == 0 &&
1136 7 : psResult->pabyData != nullptr)
1137 : {
1138 7 : bHasFoundXSD = true;
1139 7 : m_bUnlinkXSDFilename = true;
1140 : osXSDFilename =
1141 : VSIMemGenerateHiddenFilename(
1142 7 : "tmp_ogr_gml.xsd");
1143 7 : VSILFILE *fpMem = VSIFileFromMemBuffer(
1144 : osXSDFilename, psResult->pabyData,
1145 7 : psResult->nDataLen, TRUE);
1146 7 : VSIFCloseL(fpMem);
1147 7 : psResult->pabyData = nullptr;
1148 : }
1149 8 : CPLHTTPDestroyResult(psResult);
1150 : }
1151 : }
1152 126 : break;
1153 : }
1154 : }
1155 : }
1156 142 : CSLDestroy(papszTokens);
1157 : }
1158 142 : CPLFree(pszSchemaLocationTmp2);
1159 142 : CPLFree(pszSchemaLocationTmp1);
1160 : }
1161 :
1162 395 : bool bHasFeatureProperties = false;
1163 395 : if (bHasFoundXSD)
1164 : {
1165 566 : std::vector<GMLFeatureClass *> aosClasses;
1166 566 : bool bUseSchemaImports = CPLFetchBool(
1167 283 : poOpenInfo->papszOpenOptions, "USE_SCHEMA_IMPORT",
1168 283 : CPLTestBool(CPLGetConfigOption("GML_USE_SCHEMA_IMPORT", "NO")));
1169 283 : bool bFullyUnderstood = false;
1170 283 : bHaveSchema = GMLParseXSD(osXSDFilename, bUseSchemaImports,
1171 : aosClasses, bFullyUnderstood);
1172 :
1173 283 : if (bHaveSchema && !bFullyUnderstood && bIsWFSJointLayer)
1174 : {
1175 1 : CPLDebug("GML", "Schema found, but only partially understood. "
1176 : "Cannot be used in a WFS join context");
1177 :
1178 : std::vector<GMLFeatureClass *>::const_iterator oIter =
1179 1 : aosClasses.begin();
1180 : std::vector<GMLFeatureClass *>::const_iterator oEndIter =
1181 1 : aosClasses.end();
1182 2 : while (oIter != oEndIter)
1183 : {
1184 1 : GMLFeatureClass *poClass = *oIter;
1185 :
1186 1 : delete poClass;
1187 1 : ++oIter;
1188 : }
1189 1 : aosClasses.resize(0);
1190 1 : bHaveSchema = false;
1191 : }
1192 :
1193 283 : if (bHaveSchema)
1194 : {
1195 273 : CPLDebug("GML", "Using %s", osXSDFilename.c_str());
1196 : std::vector<GMLFeatureClass *>::const_iterator oIter =
1197 273 : aosClasses.begin();
1198 : std::vector<GMLFeatureClass *>::const_iterator oEndIter =
1199 273 : aosClasses.end();
1200 658 : while (oIter != oEndIter)
1201 : {
1202 386 : GMLFeatureClass *poClass = *oIter;
1203 :
1204 386 : if (poClass->HasFeatureProperties())
1205 : {
1206 1 : bHasFeatureProperties = true;
1207 1 : break;
1208 : }
1209 385 : ++oIter;
1210 : }
1211 :
1212 273 : oIter = aosClasses.begin();
1213 661 : while (oIter != oEndIter)
1214 : {
1215 388 : GMLFeatureClass *poClass = *oIter;
1216 388 : ++oIter;
1217 :
1218 : // We have no way of knowing if the geometry type is 25D
1219 : // when examining the xsd only, so if there was a hint
1220 : // it is, we force to 25D.
1221 388 : if (bHas3D && poClass->GetGeometryPropertyCount() == 1)
1222 : {
1223 35 : poClass->GetGeometryProperty(0)->SetType(
1224 : wkbSetZ(static_cast<OGRwkbGeometryType>(
1225 : poClass->GetGeometryProperty(0)->GetType())));
1226 : }
1227 :
1228 388 : bool bAddClass = true;
1229 : // If typenames are declared, only register the matching
1230 : // classes, in case the XSD contains more layers, but not if
1231 : // feature classes contain feature properties, in which case
1232 : // we will have embedded features that will be reported as
1233 : // top-level features.
1234 388 : if (papszTypeNames != nullptr && !bHasFeatureProperties)
1235 : {
1236 178 : bAddClass = false;
1237 178 : char **papszIter = papszTypeNames;
1238 416 : while (*papszIter && !bAddClass)
1239 : {
1240 238 : const char *pszTypeName = *papszIter;
1241 238 : if (strcmp(pszTypeName, poClass->GetName()) == 0)
1242 177 : bAddClass = true;
1243 238 : papszIter++;
1244 : }
1245 :
1246 : // Retry by removing prefixes.
1247 178 : if (!bAddClass)
1248 : {
1249 1 : papszIter = papszTypeNames;
1250 2 : while (*papszIter && !bAddClass)
1251 : {
1252 1 : const char *pszTypeName = *papszIter;
1253 1 : const char *pszColon = strchr(pszTypeName, ':');
1254 1 : if (pszColon)
1255 : {
1256 1 : pszTypeName = pszColon + 1;
1257 1 : if (strcmp(pszTypeName,
1258 1 : poClass->GetName()) == 0)
1259 : {
1260 1 : poClass->SetName(pszTypeName);
1261 1 : bAddClass = true;
1262 : }
1263 : }
1264 1 : papszIter++;
1265 : }
1266 : }
1267 : }
1268 :
1269 776 : if (bAddClass &&
1270 388 : poReader->GetClass(poClass->GetName()) == nullptr)
1271 : {
1272 388 : poReader->AddClass(poClass);
1273 : }
1274 : else
1275 0 : delete poClass;
1276 : }
1277 :
1278 273 : poReader->SetClassListLocked(true);
1279 : }
1280 : }
1281 :
1282 395 : if (bHaveSchema && bIsWFS)
1283 : {
1284 136 : if (bIsWFSJointLayer)
1285 : {
1286 47 : BuildJointClassFromXSD();
1287 : }
1288 :
1289 : // For WFS, we can assume sequential layers.
1290 155 : if (poReader->GetClassCount() > 1 && pszReadMode == nullptr &&
1291 19 : !bHasFeatureProperties)
1292 : {
1293 19 : CPLDebug("GML",
1294 : "WFS output. Using SEQUENTIAL_LAYERS read mode");
1295 19 : eReadMode = SEQUENTIAL_LAYERS;
1296 : }
1297 : // Sometimes the returned schema contains only <xs:include> that we
1298 : // don't resolve so ignore it.
1299 117 : else if (poReader->GetClassCount() == 0)
1300 0 : bHaveSchema = false;
1301 : }
1302 :
1303 395 : CSLDestroy(papszTypeNames);
1304 : }
1305 :
1306 : // Force a first pass to establish the schema. Eventually we will have
1307 : // mechanisms for remembering the schema and related information.
1308 : const char *pszForceSRSDetection =
1309 445 : CSLFetchNameValue(poOpenInfo->papszOpenOptions, "FORCE_SRS_DETECTION");
1310 454 : if (!bHaveSchema ||
1311 9 : (pszForceSRSDetection && CPLTestBool(pszForceSRSDetection)))
1312 : {
1313 122 : bool bOnlyDetectSRS = bHaveSchema;
1314 122 : if (!poReader->PrescanForSchema(true, bOnlyDetectSRS))
1315 : {
1316 : // Assume an error was reported.
1317 0 : return false;
1318 : }
1319 122 : if (!bHaveSchema)
1320 : {
1321 113 : if (bIsWFSJointLayer && poReader->GetClassCount() == 1)
1322 : {
1323 2 : BuildJointClassFromScannedSchema();
1324 : }
1325 :
1326 113 : if (bHasFoundXSD)
1327 : {
1328 10 : CPLDebug("GML", "Generating %s file, ignoring %s",
1329 : osGFSFilename.c_str(), osXSDFilename.c_str());
1330 : }
1331 : }
1332 : }
1333 :
1334 445 : if (poReader->GetClassCount() > 1 && poReader->IsSequentialLayers() &&
1335 : pszReadMode == nullptr)
1336 : {
1337 27 : CPLDebug("GML",
1338 : "Layers are monoblock. Using SEQUENTIAL_LAYERS read mode");
1339 27 : eReadMode = SEQUENTIAL_LAYERS;
1340 : }
1341 :
1342 445 : if (!DealWithOgrSchemaOpenOption(poOpenInfo))
1343 : {
1344 10 : return false;
1345 : }
1346 :
1347 : // Save the schema file if possible. Don't make a fuss if we
1348 : // can't. It could be read-only directory or something.
1349 : const char *pszWriteGFS =
1350 435 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "WRITE_GFS", "AUTO");
1351 435 : bool bWriteGFS = false;
1352 435 : if (EQUAL(pszWriteGFS, "AUTO"))
1353 : {
1354 111 : if (!bHaveSchema && !poReader->HasStoppedParsing() &&
1355 650 : VSIIsLocal(pszFilename) &&
1356 107 : VSISupportsSequentialWrite(pszFilename, false))
1357 : {
1358 : VSIStatBufL sGFSStatBuf;
1359 107 : if (VSIStatExL(osGFSFilename, &sGFSStatBuf, VSI_STAT_EXISTS_FLAG) !=
1360 : 0)
1361 : {
1362 102 : bWriteGFS = true;
1363 : }
1364 : else
1365 : {
1366 5 : CPLDebug("GML", "Not saving %s file: already exists.",
1367 : osGFSFilename.c_str());
1368 : }
1369 : }
1370 : }
1371 3 : else if (CPLTestBool(pszWriteGFS))
1372 : {
1373 1 : if (bHaveSchema || !poReader->HasStoppedParsing())
1374 : {
1375 1 : bWriteGFS = true;
1376 : }
1377 : else
1378 : {
1379 0 : CPLError(CE_Warning, CPLE_AppDefined,
1380 : "GFS file saving asked, but cannot be done");
1381 : }
1382 : }
1383 :
1384 435 : if (bWriteGFS)
1385 : {
1386 103 : if (!poReader->SaveClasses(osGFSFilename))
1387 : {
1388 0 : if (CPLTestBool(pszWriteGFS))
1389 : {
1390 0 : CPLError(CE_Warning, CPLE_AppDefined,
1391 : "GFS file saving asked, but failed");
1392 : }
1393 : else
1394 : {
1395 0 : CPLDebug("GML", "Not saving %s file: can't be created.",
1396 : osGFSFilename.c_str());
1397 : }
1398 : }
1399 : }
1400 :
1401 : // Translate the GMLFeatureClasses into layers.
1402 435 : papoLayers = static_cast<OGRLayer **>(
1403 435 : CPLCalloc(sizeof(OGRLayer *), poReader->GetClassCount()));
1404 435 : nLayers = 0;
1405 :
1406 435 : if (poReader->GetClassCount() == 1 && nNumberOfFeatures != 0)
1407 : {
1408 118 : GMLFeatureClass *poClass = poReader->GetClass(0);
1409 118 : GIntBig nFeatureCount = poClass->GetFeatureCount();
1410 118 : if (nFeatureCount < 0)
1411 : {
1412 106 : poClass->SetFeatureCount(nNumberOfFeatures);
1413 : }
1414 12 : else if (nFeatureCount != nNumberOfFeatures)
1415 : {
1416 0 : CPLDebug("GML", "Feature count in header, "
1417 : "and actual feature count don't match");
1418 : }
1419 : }
1420 :
1421 435 : if (bIsWFS && poReader->GetClassCount() == 1)
1422 138 : bUseGlobalSRSName = true;
1423 :
1424 1013 : while (nLayers < poReader->GetClassCount())
1425 : {
1426 578 : papoLayers[nLayers] = TranslateGMLSchema(poReader->GetClass(nLayers));
1427 578 : nLayers++;
1428 : }
1429 :
1430 : // Warn if we have geometry columns without known CRS due to only using
1431 : // the .xsd
1432 435 : if (bHaveSchema && pszForceSRSDetection == nullptr)
1433 : {
1434 313 : bool bExitLoop = false;
1435 671 : for (int i = 0; !bExitLoop && i < nLayers; ++i)
1436 : {
1437 358 : const auto poLayer = papoLayers[i];
1438 358 : const auto poLayerDefn = poLayer->GetLayerDefn();
1439 358 : const auto nGeomFieldCount = poLayerDefn->GetGeomFieldCount();
1440 492 : for (int j = 0; j < nGeomFieldCount; ++j)
1441 : {
1442 373 : if (poLayerDefn->GetGeomFieldDefn(j)->GetSpatialRef() ==
1443 : nullptr)
1444 : {
1445 239 : bExitLoop = true;
1446 239 : break;
1447 : }
1448 : }
1449 : }
1450 313 : if (bExitLoop)
1451 : {
1452 239 : CPLDebug("GML",
1453 : "Geometry fields without known CRS have been detected. "
1454 : "You may want to specify the FORCE_SRS_DETECTION open "
1455 : "option to YES.");
1456 : }
1457 : }
1458 :
1459 435 : return true;
1460 : }
1461 :
1462 : /************************************************************************/
1463 : /* BuildJointClassFromXSD() */
1464 : /************************************************************************/
1465 :
1466 47 : void OGRGMLDataSource::BuildJointClassFromXSD()
1467 : {
1468 94 : CPLString osJointClassName = "join";
1469 141 : for (int i = 0; i < poReader->GetClassCount(); i++)
1470 : {
1471 94 : osJointClassName += "_";
1472 94 : osJointClassName += poReader->GetClass(i)->GetName();
1473 : }
1474 47 : GMLFeatureClass *poJointClass = new GMLFeatureClass(osJointClassName);
1475 47 : poJointClass->SetElementName("Tuple");
1476 141 : for (int i = 0; i < poReader->GetClassCount(); i++)
1477 : {
1478 94 : GMLFeatureClass *poClass = poReader->GetClass(i);
1479 :
1480 : {
1481 188 : CPLString osPropertyName;
1482 94 : osPropertyName.Printf("%s.%s", poClass->GetName(), "gml_id");
1483 : GMLPropertyDefn *poNewProperty =
1484 94 : new GMLPropertyDefn(osPropertyName);
1485 188 : CPLString osSrcElement;
1486 94 : osSrcElement.Printf("member|%s@id", poClass->GetName());
1487 94 : poNewProperty->SetSrcElement(osSrcElement);
1488 94 : poNewProperty->SetType(GMLPT_String);
1489 94 : poJointClass->AddProperty(poNewProperty);
1490 : }
1491 :
1492 200 : for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
1493 : {
1494 106 : GMLPropertyDefn *poProperty = poClass->GetProperty(iField);
1495 212 : CPLString osPropertyName;
1496 : osPropertyName.Printf("%s.%s", poClass->GetName(),
1497 106 : poProperty->GetName());
1498 : GMLPropertyDefn *poNewProperty =
1499 106 : new GMLPropertyDefn(osPropertyName);
1500 :
1501 106 : poNewProperty->SetType(poProperty->GetType());
1502 212 : CPLString osSrcElement;
1503 : osSrcElement.Printf("member|%s|%s", poClass->GetName(),
1504 106 : poProperty->GetSrcElement());
1505 106 : poNewProperty->SetSrcElement(osSrcElement);
1506 106 : poNewProperty->SetWidth(poProperty->GetWidth());
1507 106 : poNewProperty->SetPrecision(poProperty->GetPrecision());
1508 106 : poNewProperty->SetNullable(poProperty->IsNullable());
1509 :
1510 106 : poJointClass->AddProperty(poNewProperty);
1511 : }
1512 188 : for (int iField = 0; iField < poClass->GetGeometryPropertyCount();
1513 : iField++)
1514 : {
1515 : GMLGeometryPropertyDefn *poProperty =
1516 94 : poClass->GetGeometryProperty(iField);
1517 188 : CPLString osPropertyName;
1518 : osPropertyName.Printf("%s.%s", poClass->GetName(),
1519 94 : poProperty->GetName());
1520 188 : CPLString osSrcElement;
1521 : osSrcElement.Printf("member|%s|%s", poClass->GetName(),
1522 94 : poProperty->GetSrcElement());
1523 : GMLGeometryPropertyDefn *poNewProperty =
1524 : new GMLGeometryPropertyDefn(osPropertyName, osSrcElement,
1525 94 : poProperty->GetType(), -1,
1526 188 : poProperty->IsNullable());
1527 94 : poJointClass->AddGeometryProperty(poNewProperty);
1528 : }
1529 : }
1530 47 : poJointClass->SetSchemaLocked(true);
1531 :
1532 47 : poReader->ClearClasses();
1533 47 : poReader->AddClass(poJointClass);
1534 47 : }
1535 :
1536 : /************************************************************************/
1537 : /* BuildJointClassFromScannedSchema() */
1538 : /************************************************************************/
1539 :
1540 2 : void OGRGMLDataSource::BuildJointClassFromScannedSchema()
1541 : {
1542 : // Make sure that all properties of a same base feature type are
1543 : // consecutive. If not, reorder.
1544 4 : std::vector<std::vector<GMLPropertyDefn *>> aapoProps;
1545 2 : GMLFeatureClass *poClass = poReader->GetClass(0);
1546 4 : CPLString osJointClassName = "join";
1547 :
1548 14 : for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
1549 : {
1550 12 : GMLPropertyDefn *poProp = poClass->GetProperty(iField);
1551 24 : CPLString osPrefix(poProp->GetName());
1552 12 : size_t iPos = osPrefix.find('.');
1553 12 : if (iPos != std::string::npos)
1554 12 : osPrefix.resize(iPos);
1555 12 : int iSubClass = 0; // Used after for.
1556 18 : for (; iSubClass < static_cast<int>(aapoProps.size()); iSubClass++)
1557 : {
1558 14 : CPLString osPrefixClass(aapoProps[iSubClass][0]->GetName());
1559 14 : iPos = osPrefixClass.find('.');
1560 14 : if (iPos != std::string::npos)
1561 14 : osPrefixClass.resize(iPos);
1562 14 : if (osPrefix == osPrefixClass)
1563 8 : break;
1564 : }
1565 12 : if (iSubClass == static_cast<int>(aapoProps.size()))
1566 : {
1567 4 : osJointClassName += "_";
1568 4 : osJointClassName += osPrefix;
1569 4 : aapoProps.push_back(std::vector<GMLPropertyDefn *>());
1570 : }
1571 12 : aapoProps[iSubClass].push_back(poProp);
1572 : }
1573 2 : poClass->SetElementName(poClass->GetName());
1574 2 : poClass->SetName(osJointClassName);
1575 :
1576 2 : poClass->StealProperties();
1577 : std::vector<std::pair<CPLString, std::vector<GMLGeometryPropertyDefn *>>>
1578 4 : aapoGeomProps;
1579 6 : for (int iSubClass = 0; iSubClass < static_cast<int>(aapoProps.size());
1580 : iSubClass++)
1581 : {
1582 8 : CPLString osPrefixClass(aapoProps[iSubClass][0]->GetName());
1583 4 : size_t iPos = osPrefixClass.find('.');
1584 4 : if (iPos != std::string::npos)
1585 4 : osPrefixClass.resize(iPos);
1586 : aapoGeomProps.emplace_back(
1587 4 : std::pair(osPrefixClass, std::vector<GMLGeometryPropertyDefn *>()));
1588 16 : for (int iField = 0;
1589 16 : iField < static_cast<int>(aapoProps[iSubClass].size()); iField++)
1590 : {
1591 12 : poClass->AddProperty(aapoProps[iSubClass][iField]);
1592 : }
1593 : }
1594 2 : aapoProps.resize(0);
1595 :
1596 : // Reorder geometry fields too
1597 6 : for (int iField = 0; iField < poClass->GetGeometryPropertyCount(); iField++)
1598 : {
1599 4 : GMLGeometryPropertyDefn *poProp = poClass->GetGeometryProperty(iField);
1600 8 : CPLString osPrefix(poProp->GetName());
1601 4 : size_t iPos = osPrefix.find('.');
1602 4 : if (iPos != std::string::npos)
1603 4 : osPrefix.resize(iPos);
1604 4 : int iSubClass = 0; // Used after for.
1605 6 : for (; iSubClass < static_cast<int>(aapoGeomProps.size()); iSubClass++)
1606 : {
1607 6 : if (osPrefix == aapoGeomProps[iSubClass].first)
1608 4 : break;
1609 : }
1610 4 : if (iSubClass == static_cast<int>(aapoGeomProps.size()))
1611 : aapoGeomProps.emplace_back(
1612 0 : std::pair(osPrefix, std::vector<GMLGeometryPropertyDefn *>()));
1613 4 : aapoGeomProps[iSubClass].second.push_back(poProp);
1614 : }
1615 2 : poClass->StealGeometryProperties();
1616 6 : for (int iSubClass = 0; iSubClass < static_cast<int>(aapoGeomProps.size());
1617 : iSubClass++)
1618 : {
1619 8 : for (int iField = 0;
1620 8 : iField < static_cast<int>(aapoGeomProps[iSubClass].second.size());
1621 : iField++)
1622 : {
1623 4 : poClass->AddGeometryProperty(
1624 4 : aapoGeomProps[iSubClass].second[iField]);
1625 : }
1626 : }
1627 2 : }
1628 :
1629 : /************************************************************************/
1630 : /* TranslateGMLSchema() */
1631 : /************************************************************************/
1632 :
1633 578 : OGRGMLLayer *OGRGMLDataSource::TranslateGMLSchema(GMLFeatureClass *poClass)
1634 :
1635 : {
1636 : // Create an empty layer.
1637 578 : const char *pszSRSName = poClass->GetSRSName();
1638 578 : OGRSpatialReference *poSRS = nullptr;
1639 578 : if (pszSRSName)
1640 : {
1641 132 : poSRS = new OGRSpatialReference();
1642 132 : poSRS->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
1643 : ? OAMS_TRADITIONAL_GIS_ORDER
1644 : : OAMS_AUTHORITY_COMPLIANT);
1645 132 : if (poSRS->SetFromUserInput(
1646 : pszSRSName,
1647 132 : OGRSpatialReference::SET_FROM_USER_INPUT_LIMITATIONS_get()) !=
1648 : OGRERR_NONE)
1649 : {
1650 0 : delete poSRS;
1651 0 : poSRS = nullptr;
1652 : }
1653 : }
1654 : else
1655 : {
1656 446 : pszSRSName = GetGlobalSRSName();
1657 :
1658 446 : if (pszSRSName && GML_IsLegitSRSName(pszSRSName))
1659 : {
1660 35 : poSRS = new OGRSpatialReference();
1661 35 : poSRS->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
1662 : ? OAMS_TRADITIONAL_GIS_ORDER
1663 : : OAMS_AUTHORITY_COMPLIANT);
1664 35 : if (poSRS->SetFromUserInput(
1665 : pszSRSName,
1666 : OGRSpatialReference::
1667 35 : SET_FROM_USER_INPUT_LIMITATIONS_get()) != OGRERR_NONE)
1668 : {
1669 0 : delete poSRS;
1670 0 : poSRS = nullptr;
1671 : }
1672 :
1673 70 : if (poSRS != nullptr && m_bInvertAxisOrderIfLatLong &&
1674 35 : GML_IsSRSLatLongOrder(pszSRSName))
1675 : {
1676 23 : if (!poClass->HasExtents() && sBoundingRect.IsInit())
1677 : {
1678 23 : poClass->SetExtents(sBoundingRect.MinY, sBoundingRect.MaxY,
1679 : sBoundingRect.MinX, sBoundingRect.MaxX);
1680 : }
1681 : }
1682 : }
1683 :
1684 446 : if (!poClass->HasExtents() && sBoundingRect.IsInit())
1685 : {
1686 12 : poClass->SetExtents(sBoundingRect.MinX, sBoundingRect.MaxX,
1687 : sBoundingRect.MinY, sBoundingRect.MaxY);
1688 : }
1689 : }
1690 :
1691 : // Report a COMPD_CS only if GML_REPORT_COMPD_CS is explicitly set to TRUE.
1692 578 : if (poSRS != nullptr && poSRS->IsCompound())
1693 : {
1694 : const char *pszReportCompdCS =
1695 8 : CPLGetConfigOption("GML_REPORT_COMPD_CS", nullptr);
1696 8 : if (pszReportCompdCS == nullptr)
1697 : {
1698 8 : CPLDebug("GML", "Compound CRS detected but only horizontal part "
1699 : "will be reported. Set the GML_REPORT_COMPD_CS=YES "
1700 : "configuration option to get the Compound CRS");
1701 8 : pszReportCompdCS = "FALSE";
1702 : }
1703 8 : if (!CPLTestBool(pszReportCompdCS))
1704 : {
1705 8 : OGR_SRSNode *poCOMPD_CS = poSRS->GetAttrNode("COMPD_CS");
1706 8 : if (poCOMPD_CS != nullptr)
1707 : {
1708 8 : OGR_SRSNode *poCandidateRoot = poCOMPD_CS->GetNode("PROJCS");
1709 8 : if (poCandidateRoot == nullptr)
1710 1 : poCandidateRoot = poCOMPD_CS->GetNode("GEOGCS");
1711 8 : if (poCandidateRoot != nullptr)
1712 : {
1713 8 : poSRS->SetRoot(poCandidateRoot->Clone());
1714 : }
1715 : }
1716 : }
1717 : }
1718 :
1719 578 : OGRGMLLayer *poLayer = new OGRGMLLayer(poClass->GetName(), false, this);
1720 :
1721 : // Added attributes (properties).
1722 578 : if (bExposeGMLId)
1723 : {
1724 866 : OGRFieldDefn oField("gml_id", OFTString);
1725 433 : oField.SetNullable(FALSE);
1726 433 : poLayer->GetLayerDefn()->AddFieldDefn(&oField);
1727 : }
1728 145 : else if (bExposeFid)
1729 : {
1730 110 : OGRFieldDefn oField("fid", OFTString);
1731 55 : oField.SetNullable(FALSE);
1732 55 : poLayer->GetLayerDefn()->AddFieldDefn(&oField);
1733 : }
1734 :
1735 1215 : for (int iField = 0; iField < poClass->GetGeometryPropertyCount(); iField++)
1736 : {
1737 : GMLGeometryPropertyDefn *poProperty =
1738 637 : poClass->GetGeometryProperty(iField);
1739 :
1740 : // Patch wrong .gfs file produced by earlier versions
1741 637 : if (poProperty->GetType() == wkbPolyhedralSurface &&
1742 0 : strcmp(poProperty->GetName(), "lod2Solid") == 0)
1743 : {
1744 0 : poProperty->SetType(wkbPolyhedralSurfaceZ);
1745 : }
1746 :
1747 1274 : OGRGeomFieldDefn oField(poProperty->GetName(), poProperty->GetType());
1748 1080 : if (poClass->GetGeometryPropertyCount() == 1 &&
1749 443 : poClass->GetFeatureCount() == 0)
1750 : {
1751 0 : oField.SetType(wkbUnknown);
1752 : }
1753 :
1754 637 : const auto &osSRSName = poProperty->GetSRSName();
1755 637 : if (!osSRSName.empty())
1756 : {
1757 30 : OGRSpatialReference *poSRS2 = new OGRSpatialReference();
1758 30 : poSRS2->SetAxisMappingStrategy(m_bInvertAxisOrderIfLatLong
1759 : ? OAMS_TRADITIONAL_GIS_ORDER
1760 : : OAMS_AUTHORITY_COMPLIANT);
1761 30 : if (poSRS2->SetFromUserInput(
1762 : osSRSName.c_str(),
1763 : OGRSpatialReference::
1764 30 : SET_FROM_USER_INPUT_LIMITATIONS_get()) == OGRERR_NONE)
1765 : {
1766 30 : oField.SetSpatialRef(poSRS2);
1767 : }
1768 30 : poSRS2->Release();
1769 : }
1770 : else
1771 : {
1772 607 : oField.SetSpatialRef(poSRS);
1773 : }
1774 637 : oField.SetNullable(poProperty->IsNullable());
1775 637 : oField.SetCoordinatePrecision(poProperty->GetCoordinatePrecision());
1776 637 : poLayer->GetLayerDefn()->AddGeomFieldDefn(&oField);
1777 : }
1778 :
1779 578 : if (poReader->GetClassCount() == 1)
1780 : {
1781 335 : int iInsertPos = 0;
1782 340 : for (const auto &osElt : m_aosGMLExtraElements)
1783 : {
1784 : GMLPropertyDefn *poProperty =
1785 5 : new GMLPropertyDefn(osElt.c_str(), osElt.c_str());
1786 5 : poProperty->SetType(GMLPT_String);
1787 5 : if (poClass->AddProperty(poProperty, iInsertPos) == iInsertPos)
1788 3 : ++iInsertPos;
1789 : else
1790 2 : delete poProperty;
1791 : }
1792 : }
1793 :
1794 2765 : for (int iField = 0; iField < poClass->GetPropertyCount(); iField++)
1795 : {
1796 2187 : GMLPropertyDefn *poProperty = poClass->GetProperty(iField);
1797 2187 : OGRFieldSubType eSubType = poProperty->GetSubType();
1798 : const OGRFieldType eFType =
1799 2187 : GML_GetOGRFieldType(poProperty->GetType(), eSubType);
1800 4374 : OGRFieldDefn oField(poProperty->GetName(), eFType);
1801 2187 : oField.SetSubType(eSubType);
1802 2187 : if (STARTS_WITH_CI(oField.GetNameRef(), "ogr:"))
1803 0 : oField.SetName(poProperty->GetName() + 4);
1804 2187 : if (poProperty->GetWidth() > 0)
1805 662 : oField.SetWidth(poProperty->GetWidth());
1806 2187 : if (poProperty->GetPrecision() > 0)
1807 45 : oField.SetPrecision(poProperty->GetPrecision());
1808 2187 : if (!bEmptyAsNull)
1809 2 : oField.SetNullable(poProperty->IsNullable());
1810 2187 : oField.SetUnique(poProperty->IsUnique());
1811 2187 : oField.SetComment(poProperty->GetDocumentation());
1812 2187 : poLayer->GetLayerDefn()->AddFieldDefn(&oField);
1813 : }
1814 :
1815 578 : if (poSRS != nullptr)
1816 167 : poSRS->Release();
1817 :
1818 578 : return poLayer;
1819 : }
1820 :
1821 : /************************************************************************/
1822 : /* GetGlobalSRSName() */
1823 : /************************************************************************/
1824 :
1825 1083 : const char *OGRGMLDataSource::GetGlobalSRSName()
1826 : {
1827 1083 : if (poReader->CanUseGlobalSRSName() || bUseGlobalSRSName)
1828 504 : return poReader->GetGlobalSRSName();
1829 : else
1830 579 : return nullptr;
1831 : }
1832 :
1833 : /************************************************************************/
1834 : /* Create() */
1835 : /************************************************************************/
1836 :
1837 101 : bool OGRGMLDataSource::Create(const char *pszFilename, char **papszOptions)
1838 :
1839 : {
1840 101 : if (fpOutput != nullptr || poReader != nullptr)
1841 : {
1842 0 : CPLAssert(false);
1843 : return false;
1844 : }
1845 :
1846 101 : if (strcmp(pszFilename, "/dev/stdout") == 0)
1847 0 : pszFilename = "/vsistdout/";
1848 :
1849 : // Read options.
1850 101 : CSLDestroy(papszCreateOptions);
1851 101 : papszCreateOptions = CSLDuplicate(papszOptions);
1852 :
1853 : const char *pszFormat =
1854 101 : CSLFetchNameValueDef(papszCreateOptions, "FORMAT", "GML3.2");
1855 101 : bIsOutputGML3 = EQUAL(pszFormat, "GML3");
1856 101 : bIsOutputGML3Deegree = EQUAL(pszFormat, "GML3Deegree");
1857 101 : bIsOutputGML32 = EQUAL(pszFormat, "GML3.2");
1858 101 : if (bIsOutputGML3Deegree || bIsOutputGML32)
1859 79 : bIsOutputGML3 = true;
1860 :
1861 101 : eSRSNameFormat = (bIsOutputGML3) ? SRSNAME_OGC_URN : SRSNAME_SHORT;
1862 101 : if (bIsOutputGML3)
1863 : {
1864 : const char *pszLongSRS =
1865 91 : CSLFetchNameValue(papszCreateOptions, "GML3_LONGSRS");
1866 : const char *pszSRSNameFormat =
1867 91 : CSLFetchNameValue(papszCreateOptions, "SRSNAME_FORMAT");
1868 91 : if (pszSRSNameFormat)
1869 : {
1870 6 : if (pszLongSRS)
1871 : {
1872 0 : CPLError(CE_Warning, CPLE_NotSupported,
1873 : "Both GML3_LONGSRS and SRSNAME_FORMAT specified. "
1874 : "Ignoring GML3_LONGSRS");
1875 : }
1876 6 : if (EQUAL(pszSRSNameFormat, "SHORT"))
1877 1 : eSRSNameFormat = SRSNAME_SHORT;
1878 5 : else if (EQUAL(pszSRSNameFormat, "OGC_URN"))
1879 1 : eSRSNameFormat = SRSNAME_OGC_URN;
1880 4 : else if (EQUAL(pszSRSNameFormat, "OGC_URL"))
1881 4 : eSRSNameFormat = SRSNAME_OGC_URL;
1882 : else
1883 : {
1884 0 : CPLError(CE_Warning, CPLE_NotSupported,
1885 : "Invalid value for SRSNAME_FORMAT. "
1886 : "Using SRSNAME_OGC_URN");
1887 : }
1888 : }
1889 85 : else if (pszLongSRS && !CPLTestBool(pszLongSRS))
1890 0 : eSRSNameFormat = SRSNAME_SHORT;
1891 : }
1892 :
1893 101 : bWriteSpaceIndentation = CPLTestBool(
1894 101 : CSLFetchNameValueDef(papszCreateOptions, "SPACE_INDENTATION", "YES"));
1895 :
1896 : // Create the output file.
1897 101 : osFilename = pszFilename;
1898 101 : SetDescription(pszFilename);
1899 :
1900 101 : if (strcmp(pszFilename, "/vsistdout/") == 0 ||
1901 101 : STARTS_WITH(pszFilename, "/vsigzip/"))
1902 : {
1903 0 : fpOutput = VSIFOpenExL(pszFilename, "wb", true);
1904 0 : bFpOutputIsNonSeekable = true;
1905 0 : bFpOutputSingleFile = true;
1906 : }
1907 101 : else if (STARTS_WITH(pszFilename, "/vsizip/"))
1908 : {
1909 0 : if (EQUAL(CPLGetExtensionSafe(pszFilename).c_str(), "zip"))
1910 : {
1911 0 : SetDescription(
1912 0 : CPLFormFilenameSafe(pszFilename, "out.gml", nullptr).c_str());
1913 : }
1914 :
1915 0 : fpOutput = VSIFOpenExL(GetDescription(), "wb", true);
1916 0 : bFpOutputIsNonSeekable = true;
1917 : }
1918 : else
1919 101 : fpOutput = VSIFOpenExL(pszFilename, "wb+", true);
1920 101 : if (fpOutput == nullptr)
1921 : {
1922 1 : CPLError(CE_Failure, CPLE_OpenFailed,
1923 : "Failed to create GML file %s: %s", pszFilename,
1924 : VSIGetLastErrorMsg());
1925 1 : return false;
1926 : }
1927 :
1928 : // Write out "standard" header.
1929 100 : PrintLine(fpOutput, "%s", "<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
1930 :
1931 100 : if (!bFpOutputIsNonSeekable)
1932 100 : nSchemaInsertLocation = static_cast<int>(VSIFTellL(fpOutput));
1933 :
1934 100 : const char *pszPrefix = GetAppPrefix();
1935 100 : const char *pszTargetNameSpace = CSLFetchNameValueDef(
1936 : papszOptions, "TARGET_NAMESPACE", "http://ogr.maptools.org/");
1937 :
1938 100 : if (GMLFeatureCollection())
1939 1 : PrintLine(fpOutput, "<gml:FeatureCollection");
1940 99 : else if (RemoveAppPrefix())
1941 2 : PrintLine(fpOutput, "<FeatureCollection");
1942 : else
1943 97 : PrintLine(fpOutput, "<%s:FeatureCollection", pszPrefix);
1944 :
1945 100 : if (IsGML32Output())
1946 : {
1947 77 : char *pszGMLId = CPLEscapeString(
1948 : CSLFetchNameValueDef(papszOptions, "GML_ID", "aFeatureCollection"),
1949 : -1, CPLES_XML);
1950 77 : PrintLine(fpOutput, " gml:id=\"%s\"", pszGMLId);
1951 77 : CPLFree(pszGMLId);
1952 : }
1953 :
1954 : // Write out schema info if provided in creation options.
1955 100 : const char *pszSchemaURI = CSLFetchNameValue(papszOptions, "XSISCHEMAURI");
1956 100 : const char *pszSchemaOpt = CSLFetchNameValue(papszOptions, "XSISCHEMA");
1957 :
1958 100 : if (pszSchemaURI != nullptr)
1959 : {
1960 0 : PrintLine(
1961 : fpOutput,
1962 : " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
1963 0 : PrintLine(fpOutput, " xsi:schemaLocation=\"%s\"", pszSchemaURI);
1964 : }
1965 100 : else if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL"))
1966 : {
1967 : char *pszBasename =
1968 98 : CPLStrdup(CPLGetBasenameSafe(GetDescription()).c_str());
1969 :
1970 98 : PrintLine(
1971 : fpOutput,
1972 : " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
1973 98 : PrintLine(fpOutput, " xsi:schemaLocation=\"%s %s\"",
1974 : pszTargetNameSpace,
1975 196 : CPLResetExtensionSafe(pszBasename, "xsd").c_str());
1976 98 : CPLFree(pszBasename);
1977 : }
1978 :
1979 100 : if (RemoveAppPrefix())
1980 2 : PrintLine(fpOutput, " xmlns=\"%s\"", pszTargetNameSpace);
1981 : else
1982 98 : PrintLine(fpOutput, " xmlns:%s=\"%s\"", pszPrefix,
1983 : pszTargetNameSpace);
1984 :
1985 100 : if (IsGML32Output())
1986 77 : PrintLine(fpOutput, "%s",
1987 : " xmlns:gml=\"http://www.opengis.net/gml/3.2\">");
1988 : else
1989 23 : PrintLine(fpOutput, "%s",
1990 : " xmlns:gml=\"http://www.opengis.net/gml\">");
1991 :
1992 100 : return true;
1993 : }
1994 :
1995 : /************************************************************************/
1996 : /* WriteTopElements() */
1997 : /************************************************************************/
1998 :
1999 100 : void OGRGMLDataSource::WriteTopElements()
2000 : {
2001 300 : const char *pszDescription = CSLFetchNameValueDef(
2002 100 : papszCreateOptions, "DESCRIPTION", GetMetadataItem("DESCRIPTION"));
2003 100 : if (pszDescription != nullptr)
2004 : {
2005 2 : if (bWriteSpaceIndentation)
2006 2 : VSIFPrintfL(fpOutput, " ");
2007 2 : char *pszTmp = CPLEscapeString(pszDescription, -1, CPLES_XML);
2008 2 : PrintLine(fpOutput, "<gml:description>%s</gml:description>", pszTmp);
2009 2 : CPLFree(pszTmp);
2010 : }
2011 :
2012 100 : const char *l_pszName = CSLFetchNameValueDef(papszCreateOptions, "NAME",
2013 100 : GetMetadataItem("NAME"));
2014 100 : if (l_pszName != nullptr)
2015 : {
2016 2 : if (bWriteSpaceIndentation)
2017 2 : VSIFPrintfL(fpOutput, " ");
2018 2 : char *pszTmp = CPLEscapeString(l_pszName, -1, CPLES_XML);
2019 2 : PrintLine(fpOutput, "<gml:name>%s</gml:name>", pszTmp);
2020 2 : CPLFree(pszTmp);
2021 : }
2022 :
2023 : // Should we initialize an area to place the boundedBy element?
2024 : // We will need to seek back to fill it in.
2025 100 : nBoundedByLocation = -1;
2026 100 : if (CPLFetchBool(papszCreateOptions, "BOUNDEDBY", true))
2027 : {
2028 100 : if (!bFpOutputIsNonSeekable)
2029 : {
2030 100 : nBoundedByLocation = static_cast<int>(VSIFTellL(fpOutput));
2031 :
2032 100 : if (nBoundedByLocation != -1)
2033 100 : PrintLine(fpOutput, "%350s", "");
2034 : }
2035 : else
2036 : {
2037 0 : if (bWriteSpaceIndentation)
2038 0 : VSIFPrintfL(fpOutput, " ");
2039 0 : if (IsGML3Output())
2040 0 : PrintLine(fpOutput,
2041 : "<gml:boundedBy><gml:Null /></gml:boundedBy>");
2042 : else
2043 0 : PrintLine(fpOutput, "<gml:boundedBy><gml:null>missing</"
2044 : "gml:null></gml:boundedBy>");
2045 : }
2046 : }
2047 100 : }
2048 :
2049 : /************************************************************************/
2050 : /* DealWithOgrSchemaOpenOption() */
2051 : /************************************************************************/
2052 :
2053 445 : bool OGRGMLDataSource::DealWithOgrSchemaOpenOption(
2054 : const GDALOpenInfo *poOpenInfo)
2055 : {
2056 :
2057 : std::string osFieldsSchemaOverrideParam =
2058 890 : CSLFetchNameValueDef(poOpenInfo->papszOpenOptions, "OGR_SCHEMA", "");
2059 :
2060 445 : if (!osFieldsSchemaOverrideParam.empty())
2061 : {
2062 :
2063 : // GML driver does not support update at the moment so this will never happen
2064 26 : if (poOpenInfo->eAccess == GA_Update)
2065 : {
2066 0 : CPLError(CE_Failure, CPLE_NotSupported,
2067 : "OGR_SCHEMA open option is not supported in update mode.");
2068 10 : return false;
2069 : }
2070 :
2071 26 : OGRSchemaOverride osSchemaOverride;
2072 50 : if (!osSchemaOverride.LoadFromJSON(osFieldsSchemaOverrideParam) ||
2073 24 : !osSchemaOverride.IsValid())
2074 : {
2075 2 : return false;
2076 : }
2077 :
2078 24 : const auto &oLayerOverrides = osSchemaOverride.GetLayerOverrides();
2079 42 : for (const auto &oLayer : oLayerOverrides)
2080 : {
2081 26 : const auto &oLayerName = oLayer.first;
2082 26 : const auto &oLayerFieldOverride = oLayer.second;
2083 26 : const bool bIsFullOverride{oLayerFieldOverride.IsFullOverride()};
2084 26 : std::vector<GMLPropertyDefn *> aoProperties;
2085 :
2086 26 : CPLDebug("GML", "Applying schema override for layer %s",
2087 : oLayerName.c_str());
2088 :
2089 : // Fail if the layer name does not exist
2090 26 : const auto oClass = poReader->GetClass(oLayerName.c_str());
2091 26 : if (oClass == nullptr)
2092 : {
2093 6 : CPLError(CE_Failure, CPLE_AppDefined, "Layer %s not found",
2094 : oLayerName.c_str());
2095 6 : return false;
2096 : }
2097 :
2098 20 : const auto &oLayerFields = oLayerFieldOverride.GetFieldOverrides();
2099 42 : for (const auto &oFieldOverrideIt : oLayerFields)
2100 : {
2101 : const auto oProperty =
2102 24 : oClass->GetProperty(oFieldOverrideIt.first.c_str());
2103 24 : if (oProperty == nullptr)
2104 : {
2105 2 : CPLError(CE_Failure, CPLE_AppDefined,
2106 : "Field %s not found in layer %s",
2107 : oFieldOverrideIt.first.c_str(),
2108 : oLayerName.c_str());
2109 2 : return false;
2110 : }
2111 :
2112 22 : const auto &oFieldOverride = oFieldOverrideIt.second;
2113 :
2114 : const OGRFieldSubType eSubType =
2115 22 : oFieldOverride.GetFieldSubType().value_or(OFSTNone);
2116 :
2117 22 : if (oFieldOverride.GetFieldSubType().has_value())
2118 : {
2119 8 : oProperty->SetSubType(eSubType);
2120 : }
2121 :
2122 22 : if (oFieldOverride.GetFieldType().has_value())
2123 : {
2124 12 : oProperty->SetType(GML_FromOGRFieldType(
2125 24 : oFieldOverride.GetFieldType().value(), eSubType));
2126 : }
2127 :
2128 22 : if (oFieldOverride.GetFieldName().has_value())
2129 : {
2130 4 : oProperty->SetName(
2131 8 : oFieldOverride.GetFieldName().value().c_str());
2132 : }
2133 :
2134 22 : if (oFieldOverride.GetFieldWidth().has_value())
2135 : {
2136 2 : oProperty->SetWidth(oFieldOverride.GetFieldWidth().value());
2137 : }
2138 :
2139 22 : if (oFieldOverride.GetFieldPrecision().has_value())
2140 : {
2141 4 : oProperty->SetPrecision(
2142 2 : oFieldOverride.GetFieldPrecision().value());
2143 : }
2144 :
2145 22 : if (bIsFullOverride)
2146 : {
2147 4 : aoProperties.push_back(oProperty);
2148 : }
2149 : }
2150 :
2151 : // Remove fields not in the override
2152 20 : if (bIsFullOverride &&
2153 2 : aoProperties.size() !=
2154 2 : static_cast<size_t>(oClass->GetPropertyCount()))
2155 : {
2156 8 : for (int j = 0; j < oClass->GetPropertyCount(); ++j)
2157 : {
2158 6 : const auto oProperty = oClass->GetProperty(j);
2159 6 : if (std::find(aoProperties.begin(), aoProperties.end(),
2160 6 : oProperty) == aoProperties.end())
2161 : {
2162 2 : delete (oProperty);
2163 : }
2164 : }
2165 :
2166 2 : oClass->StealProperties();
2167 :
2168 6 : for (const auto &oProperty : aoProperties)
2169 : {
2170 4 : oClass->AddProperty(oProperty);
2171 : }
2172 : }
2173 : }
2174 : }
2175 435 : return true;
2176 : }
2177 :
2178 : /************************************************************************/
2179 : /* DeclareNewWriteSRS() */
2180 : /************************************************************************/
2181 :
2182 : // Check that all SRS passed to ICreateLayer() and CreateGeomField()
2183 : // are the same (or all null)
2184 :
2185 124 : void OGRGMLDataSource::DeclareNewWriteSRS(const OGRSpatialReference *poSRS)
2186 : {
2187 124 : if (m_bWriteGlobalSRS)
2188 : {
2189 124 : if (!m_bWriteGlobalSRSInit)
2190 : {
2191 91 : m_bWriteGlobalSRSInit = true;
2192 91 : if (poSRS)
2193 : {
2194 27 : m_poWriteGlobalSRS.reset(poSRS->Clone());
2195 27 : m_poWriteGlobalSRS->SetAxisMappingStrategy(
2196 : OAMS_TRADITIONAL_GIS_ORDER);
2197 : }
2198 : }
2199 : else
2200 : {
2201 33 : if (m_poWriteGlobalSRS)
2202 : {
2203 3 : const char *const apszOptions[] = {
2204 : "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
2205 5 : if (!poSRS ||
2206 2 : !poSRS->IsSame(m_poWriteGlobalSRS.get(), apszOptions))
2207 : {
2208 2 : m_bWriteGlobalSRS = false;
2209 : }
2210 : }
2211 : else
2212 : {
2213 30 : if (poSRS)
2214 1 : m_bWriteGlobalSRS = false;
2215 : }
2216 : }
2217 : }
2218 124 : }
2219 :
2220 : /************************************************************************/
2221 : /* ICreateLayer() */
2222 : /************************************************************************/
2223 :
2224 : OGRLayer *
2225 126 : OGRGMLDataSource::ICreateLayer(const char *pszLayerName,
2226 : const OGRGeomFieldDefn *poSrcGeomFieldDefn,
2227 : CSLConstList /*papszOptions*/)
2228 : {
2229 : // Verify we are in update mode.
2230 126 : if (fpOutput == nullptr)
2231 : {
2232 0 : CPLError(CE_Failure, CPLE_NoWriteAccess,
2233 : "Data source %s opened for read access.\n"
2234 : "New layer %s cannot be created.\n",
2235 0 : GetDescription(), pszLayerName);
2236 :
2237 0 : return nullptr;
2238 : }
2239 :
2240 : const auto eType =
2241 126 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetType() : wkbNone;
2242 : const auto poSRS =
2243 126 : poSrcGeomFieldDefn ? poSrcGeomFieldDefn->GetSpatialRef() : nullptr;
2244 :
2245 : // Ensure name is safe as an element name.
2246 126 : char *pszCleanLayerName = CPLStrdup(pszLayerName);
2247 :
2248 126 : CPLCleanXMLElementName(pszCleanLayerName);
2249 126 : if (strcmp(pszCleanLayerName, pszLayerName) != 0)
2250 : {
2251 0 : CPLError(CE_Warning, CPLE_AppDefined,
2252 : "Layer name '%s' adjusted to '%s' for XML validity.",
2253 : pszLayerName, pszCleanLayerName);
2254 : }
2255 :
2256 126 : if (nLayers == 0)
2257 : {
2258 97 : WriteTopElements();
2259 : }
2260 :
2261 : // Create the layer object.
2262 126 : OGRGMLLayer *poLayer = new OGRGMLLayer(pszCleanLayerName, true, this);
2263 126 : poLayer->GetLayerDefn()->SetGeomType(eType);
2264 126 : if (eType != wkbNone)
2265 : {
2266 105 : auto poGeomFieldDefn = poLayer->GetLayerDefn()->GetGeomFieldDefn(0);
2267 105 : const char *pszGeomFieldName = poSrcGeomFieldDefn->GetNameRef();
2268 105 : if (!pszGeomFieldName || pszGeomFieldName[0] == 0)
2269 104 : pszGeomFieldName = "geometryProperty";
2270 105 : poGeomFieldDefn->SetName(pszGeomFieldName);
2271 105 : poGeomFieldDefn->SetNullable(poSrcGeomFieldDefn->IsNullable());
2272 105 : DeclareNewWriteSRS(poSRS);
2273 105 : if (poSRS != nullptr)
2274 : {
2275 24 : auto poSRSClone = poSRS->Clone();
2276 24 : poSRSClone->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
2277 24 : poGeomFieldDefn->SetSpatialRef(poSRSClone);
2278 24 : poSRSClone->Dereference();
2279 : }
2280 105 : poGeomFieldDefn->SetCoordinatePrecision(
2281 : poSrcGeomFieldDefn->GetCoordinatePrecision());
2282 : }
2283 :
2284 126 : CPLFree(pszCleanLayerName);
2285 :
2286 : // Add layer to data source layer list.
2287 126 : papoLayers = static_cast<OGRLayer **>(
2288 126 : CPLRealloc(papoLayers, sizeof(OGRLayer *) * (nLayers + 1)));
2289 :
2290 126 : papoLayers[nLayers++] = poLayer;
2291 :
2292 126 : return poLayer;
2293 : }
2294 :
2295 : /************************************************************************/
2296 : /* TestCapability() */
2297 : /************************************************************************/
2298 :
2299 172 : int OGRGMLDataSource::TestCapability(const char *pszCap)
2300 :
2301 : {
2302 172 : if (EQUAL(pszCap, ODsCCreateLayer))
2303 68 : return TRUE;
2304 104 : else if (EQUAL(pszCap, ODsCCreateGeomFieldAfterCreateLayer))
2305 42 : return TRUE;
2306 62 : else if (EQUAL(pszCap, ODsCCurveGeometries))
2307 5 : return bIsOutputGML3;
2308 57 : else if (EQUAL(pszCap, ODsCZGeometries))
2309 2 : return TRUE;
2310 55 : else if (EQUAL(pszCap, ODsCRandomLayerWrite))
2311 0 : return TRUE;
2312 : else
2313 55 : return FALSE;
2314 : }
2315 :
2316 : /************************************************************************/
2317 : /* GetLayer() */
2318 : /************************************************************************/
2319 :
2320 888 : OGRLayer *OGRGMLDataSource::GetLayer(int iLayer)
2321 :
2322 : {
2323 888 : if (iLayer < 0 || iLayer >= nLayers)
2324 7 : return nullptr;
2325 : else
2326 881 : return papoLayers[iLayer];
2327 : }
2328 :
2329 : /************************************************************************/
2330 : /* GrowExtents() */
2331 : /************************************************************************/
2332 :
2333 211 : void OGRGMLDataSource::GrowExtents(OGREnvelope3D *psGeomBounds,
2334 : int nCoordDimension)
2335 :
2336 : {
2337 211 : sBoundingRect.Merge(*psGeomBounds);
2338 211 : if (nCoordDimension == 3)
2339 46 : bBBOX3D = true;
2340 211 : }
2341 :
2342 : /************************************************************************/
2343 : /* InsertHeader() */
2344 : /* */
2345 : /* This method is used to update boundedby info for a */
2346 : /* dataset, and insert schema descriptions depending on */
2347 : /* selection options in effect. */
2348 : /************************************************************************/
2349 :
2350 99 : void OGRGMLDataSource::InsertHeader()
2351 :
2352 : {
2353 99 : int nSchemaStart = 0;
2354 :
2355 99 : if (bFpOutputSingleFile)
2356 0 : return;
2357 :
2358 : // Do we want to write the schema within the GML instance doc
2359 : // or to a separate file? For now we only support external.
2360 : const char *pszSchemaURI =
2361 99 : CSLFetchNameValue(papszCreateOptions, "XSISCHEMAURI");
2362 : const char *pszSchemaOpt =
2363 99 : CSLFetchNameValue(papszCreateOptions, "XSISCHEMA");
2364 :
2365 99 : const bool bGMLFeatureCollection = GMLFeatureCollection();
2366 :
2367 99 : if (pszSchemaURI != nullptr)
2368 0 : return;
2369 :
2370 99 : VSILFILE *fpSchema = nullptr;
2371 99 : if (pszSchemaOpt == nullptr || EQUAL(pszSchemaOpt, "EXTERNAL"))
2372 : {
2373 : const std::string l_osXSDFilename =
2374 98 : CPLResetExtensionSafe(GetDescription(), "xsd");
2375 :
2376 98 : fpSchema = VSIFOpenL(l_osXSDFilename.c_str(), "wt");
2377 98 : if (fpSchema == nullptr)
2378 : {
2379 0 : CPLError(CE_Failure, CPLE_OpenFailed,
2380 : "Failed to open file %.500s for schema output.",
2381 : l_osXSDFilename.c_str());
2382 0 : return;
2383 : }
2384 196 : PrintLine(fpSchema, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
2385 : }
2386 1 : else if (EQUAL(pszSchemaOpt, "INTERNAL"))
2387 : {
2388 0 : if (fpOutput == nullptr)
2389 0 : return;
2390 0 : nSchemaStart = static_cast<int>(VSIFTellL(fpOutput));
2391 0 : fpSchema = fpOutput;
2392 : }
2393 : else
2394 : {
2395 1 : return;
2396 : }
2397 :
2398 : // Write the schema section at the end of the file. Once
2399 : // complete, we will read it back in, and then move the whole
2400 : // file "down" enough to insert the schema at the beginning.
2401 :
2402 : // Detect if there are fields of List types.
2403 98 : bool bHasListFields = false;
2404 :
2405 98 : const int nLayerCount = OGRGMLDataSource::GetLayerCount();
2406 223 : for (int iLayer = 0; !bHasListFields && iLayer < nLayerCount; iLayer++)
2407 : {
2408 125 : OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
2409 294 : for (int iField = 0;
2410 294 : !bHasListFields && iField < poFDefn->GetFieldCount(); iField++)
2411 : {
2412 169 : OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
2413 :
2414 336 : if (poFieldDefn->GetType() == OFTIntegerList ||
2415 334 : poFieldDefn->GetType() == OFTInteger64List ||
2416 503 : poFieldDefn->GetType() == OFTRealList ||
2417 167 : poFieldDefn->GetType() == OFTStringList)
2418 : {
2419 3 : bHasListFields = true;
2420 : }
2421 : }
2422 : }
2423 :
2424 : // Emit the start of the schema section.
2425 98 : const char *pszPrefix = GetAppPrefix();
2426 98 : if (pszPrefix[0] == '\0')
2427 0 : pszPrefix = "ogr";
2428 196 : const char *pszTargetNameSpace = CSLFetchNameValueDef(
2429 98 : papszCreateOptions, "TARGET_NAMESPACE", "http://ogr.maptools.org/");
2430 :
2431 98 : if (IsGML3Output())
2432 : {
2433 88 : PrintLine(fpSchema, "<xs:schema ");
2434 88 : PrintLine(fpSchema, " targetNamespace=\"%s\"", pszTargetNameSpace);
2435 88 : PrintLine(fpSchema, " xmlns:%s=\"%s\"", pszPrefix,
2436 : pszTargetNameSpace);
2437 88 : PrintLine(fpSchema,
2438 : " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"");
2439 88 : if (IsGML32Output())
2440 : {
2441 75 : PrintLine(fpSchema,
2442 : " xmlns:gml=\"http://www.opengis.net/gml/3.2\"");
2443 75 : if (!bGMLFeatureCollection)
2444 : {
2445 75 : PrintLine(
2446 : fpSchema,
2447 : " xmlns:gmlsf=\"http://www.opengis.net/gmlsf/2.0\"");
2448 : }
2449 : }
2450 : else
2451 : {
2452 13 : PrintLine(fpSchema, " xmlns:gml=\"http://www.opengis.net/gml\"");
2453 13 : if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
2454 : {
2455 11 : PrintLine(fpSchema,
2456 : " xmlns:gmlsf=\"http://www.opengis.net/gmlsf\"");
2457 : }
2458 : }
2459 88 : PrintLine(fpSchema, " elementFormDefault=\"qualified\"");
2460 88 : PrintLine(fpSchema, " version=\"1.0\">");
2461 :
2462 88 : if (IsGML32Output())
2463 : {
2464 75 : if (!bGMLFeatureCollection)
2465 : {
2466 75 : PrintLine(fpSchema, "<xs:annotation>");
2467 75 : PrintLine(fpSchema, " <xs:appinfo "
2468 : "source=\"http://schemas.opengis.net/"
2469 : "gmlsfProfile/2.0/gmlsfLevels.xsd\">");
2470 75 : PrintLine(
2471 : fpSchema,
2472 : " <gmlsf:ComplianceLevel>%d</gmlsf:ComplianceLevel>",
2473 : (bHasListFields) ? 1 : 0);
2474 75 : PrintLine(fpSchema, " </xs:appinfo>");
2475 75 : PrintLine(fpSchema, "</xs:annotation>");
2476 : }
2477 :
2478 75 : PrintLine(fpSchema,
2479 : "<xs:import namespace=\"http://www.opengis.net/gml/3.2\" "
2480 : "schemaLocation=\"http://schemas.opengis.net/gml/3.2.1/"
2481 : "gml.xsd\"/>");
2482 75 : if (!bGMLFeatureCollection)
2483 : {
2484 75 : PrintLine(
2485 : fpSchema,
2486 : "<xs:import namespace=\"http://www.opengis.net/gmlsf/2.0\" "
2487 : "schemaLocation=\"http://schemas.opengis.net/gmlsfProfile/"
2488 : "2.0/gmlsfLevels.xsd\"/>");
2489 : }
2490 : }
2491 : else
2492 : {
2493 13 : if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
2494 : {
2495 11 : PrintLine(fpSchema, "<xs:annotation>");
2496 11 : PrintLine(fpSchema,
2497 : " <xs:appinfo "
2498 : "source=\"http://schemas.opengis.net/gml/3.1.1/"
2499 : "profiles/gmlsfProfile/1.0.0/gmlsfLevels.xsd\">");
2500 11 : PrintLine(
2501 : fpSchema,
2502 : " <gmlsf:ComplianceLevel>%d</gmlsf:ComplianceLevel>",
2503 : (bHasListFields) ? 1 : 0);
2504 11 : PrintLine(fpSchema,
2505 : " "
2506 : "<gmlsf:GMLProfileSchema>http://schemas.opengis.net/"
2507 : "gml/3.1.1/profiles/gmlsfProfile/1.0.0/gmlsf.xsd</"
2508 : "gmlsf:GMLProfileSchema>");
2509 11 : PrintLine(fpSchema, " </xs:appinfo>");
2510 11 : PrintLine(fpSchema, "</xs:annotation>");
2511 : }
2512 :
2513 13 : PrintLine(fpSchema,
2514 : "<xs:import namespace=\"http://www.opengis.net/gml\" "
2515 : "schemaLocation=\"http://schemas.opengis.net/gml/3.1.1/"
2516 : "base/gml.xsd\"/>");
2517 13 : if (!IsGML3DeegreeOutput() && !bGMLFeatureCollection)
2518 : {
2519 11 : PrintLine(
2520 : fpSchema,
2521 : "<xs:import namespace=\"http://www.opengis.net/gmlsf\" "
2522 : "schemaLocation=\"http://schemas.opengis.net/gml/3.1.1/"
2523 : "profiles/gmlsfProfile/1.0.0/gmlsfLevels.xsd\"/>");
2524 : }
2525 : }
2526 : }
2527 : else
2528 : {
2529 10 : PrintLine(fpSchema,
2530 : "<xs:schema targetNamespace=\"%s\" xmlns:%s=\"%s\" "
2531 : "xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" "
2532 : "xmlns:gml=\"http://www.opengis.net/gml\" "
2533 : "elementFormDefault=\"qualified\" version=\"1.0\">",
2534 : pszTargetNameSpace, pszPrefix, pszTargetNameSpace);
2535 :
2536 10 : PrintLine(fpSchema,
2537 : "<xs:import namespace=\"http://www.opengis.net/gml\" "
2538 : "schemaLocation=\"http://schemas.opengis.net/gml/2.1.2/"
2539 : "feature.xsd\"/>");
2540 : }
2541 :
2542 : // Define the FeatureCollection element
2543 98 : if (!bGMLFeatureCollection)
2544 : {
2545 97 : bool bHasUniqueConstraints = false;
2546 221 : for (int iLayer = 0; (iLayer < nLayerCount) && !bHasUniqueConstraints;
2547 : iLayer++)
2548 : {
2549 124 : OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
2550 124 : const int nFieldCount = poFDefn->GetFieldCount();
2551 302 : for (int iField = 0;
2552 302 : (iField < nFieldCount) && !bHasUniqueConstraints; iField++)
2553 : {
2554 178 : const OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
2555 178 : if (poFieldDefn->IsUnique())
2556 0 : bHasUniqueConstraints = true;
2557 : }
2558 : }
2559 :
2560 97 : const char *pszFeatureMemberPrefix = pszPrefix;
2561 97 : if (IsGML3Output())
2562 : {
2563 87 : if (IsGML32Output())
2564 : {
2565 : // GML Simple Features profile v2.0 mentions gml:AbstractGML as
2566 : // substitutionGroup but using gml:AbstractFeature makes it
2567 : // usablable by GMLJP2 v2.
2568 75 : PrintLine(fpSchema,
2569 : "<xs:element name=\"FeatureCollection\" "
2570 : "type=\"%s:FeatureCollectionType\" "
2571 : "substitutionGroup=\"gml:AbstractFeature\"%s>",
2572 : pszPrefix, bHasUniqueConstraints ? "" : "/");
2573 : }
2574 12 : else if (IsGML3DeegreeOutput())
2575 : {
2576 1 : PrintLine(fpSchema,
2577 : "<xs:element name=\"FeatureCollection\" "
2578 : "type=\"%s:FeatureCollectionType\" "
2579 : "substitutionGroup=\"gml:_FeatureCollection\"%s>",
2580 : pszPrefix, bHasUniqueConstraints ? "" : "/");
2581 : }
2582 : else
2583 : {
2584 11 : PrintLine(fpSchema,
2585 : "<xs:element name=\"FeatureCollection\" "
2586 : "type=\"%s:FeatureCollectionType\" "
2587 : "substitutionGroup=\"gml:_GML\"%s>",
2588 : pszPrefix, bHasUniqueConstraints ? "" : "/");
2589 : }
2590 : }
2591 : else
2592 : {
2593 10 : pszFeatureMemberPrefix = "gml";
2594 10 : PrintLine(fpSchema,
2595 : "<xs:element name=\"FeatureCollection\" "
2596 : "type=\"%s:FeatureCollectionType\" "
2597 : "substitutionGroup=\"gml:_FeatureCollection\"%s>",
2598 : pszPrefix, bHasUniqueConstraints ? "" : "/");
2599 : }
2600 :
2601 97 : if (bHasUniqueConstraints)
2602 : {
2603 0 : for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
2604 : {
2605 0 : OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
2606 0 : const int nFieldCount = poFDefn->GetFieldCount();
2607 0 : for (int iField = 0; iField < nFieldCount; iField++)
2608 : {
2609 : const OGRFieldDefn *poFieldDefn =
2610 0 : poFDefn->GetFieldDefn(iField);
2611 0 : if (poFieldDefn->IsUnique())
2612 : {
2613 0 : PrintLine(
2614 : fpSchema,
2615 : " <xs:unique name=\"uniqueConstraint_%s_%s\">",
2616 0 : poFDefn->GetName(), poFieldDefn->GetNameRef());
2617 0 : PrintLine(fpSchema,
2618 : " <xs:selector "
2619 : "xpath=\"%s:featureMember/%s:%s\"/>",
2620 : pszFeatureMemberPrefix, pszPrefix,
2621 0 : poFDefn->GetName());
2622 0 : PrintLine(fpSchema, " <xs:field xpath=\"%s:%s\"/>",
2623 : pszPrefix, poFieldDefn->GetNameRef());
2624 0 : PrintLine(fpSchema, " </xs:unique>");
2625 : }
2626 : }
2627 : }
2628 0 : PrintLine(fpSchema, "</xs:element>");
2629 : }
2630 : }
2631 :
2632 : // Define the FeatureCollectionType
2633 98 : if (IsGML3Output() && !bGMLFeatureCollection)
2634 : {
2635 87 : PrintLine(fpSchema, "<xs:complexType name=\"FeatureCollectionType\">");
2636 87 : PrintLine(fpSchema, " <xs:complexContent>");
2637 87 : if (IsGML3DeegreeOutput())
2638 : {
2639 1 : PrintLine(fpSchema, " <xs:extension "
2640 : "base=\"gml:AbstractFeatureCollectionType\">");
2641 1 : PrintLine(fpSchema, " <xs:sequence>");
2642 1 : PrintLine(fpSchema, " <xs:element name=\"featureMember\" "
2643 : "minOccurs=\"0\" maxOccurs=\"unbounded\">");
2644 : }
2645 : else
2646 : {
2647 86 : PrintLine(fpSchema,
2648 : " <xs:extension base=\"gml:AbstractFeatureType\">");
2649 86 : PrintLine(
2650 : fpSchema,
2651 : " <xs:sequence minOccurs=\"0\" maxOccurs=\"unbounded\">");
2652 86 : PrintLine(fpSchema, " <xs:element name=\"featureMember\">");
2653 : }
2654 87 : PrintLine(fpSchema, " <xs:complexType>");
2655 87 : if (IsGML32Output())
2656 : {
2657 75 : PrintLine(fpSchema, " <xs:complexContent>");
2658 75 : PrintLine(fpSchema, " <xs:extension "
2659 : "base=\"gml:AbstractFeatureMemberType\">");
2660 75 : PrintLine(fpSchema, " <xs:sequence>");
2661 75 : PrintLine(
2662 : fpSchema,
2663 : " <xs:element ref=\"gml:AbstractFeature\"/>");
2664 75 : PrintLine(fpSchema, " </xs:sequence>");
2665 75 : PrintLine(fpSchema, " </xs:extension>");
2666 75 : PrintLine(fpSchema, " </xs:complexContent>");
2667 : }
2668 : else
2669 : {
2670 12 : PrintLine(fpSchema, " <xs:sequence>");
2671 12 : PrintLine(fpSchema,
2672 : " <xs:element ref=\"gml:_Feature\"/>");
2673 12 : PrintLine(fpSchema, " </xs:sequence>");
2674 : }
2675 87 : PrintLine(fpSchema, " </xs:complexType>");
2676 87 : PrintLine(fpSchema, " </xs:element>");
2677 87 : PrintLine(fpSchema, " </xs:sequence>");
2678 87 : PrintLine(fpSchema, " </xs:extension>");
2679 87 : PrintLine(fpSchema, " </xs:complexContent>");
2680 87 : PrintLine(fpSchema, "</xs:complexType>");
2681 : }
2682 11 : else if (!bGMLFeatureCollection)
2683 : {
2684 10 : PrintLine(fpSchema, "<xs:complexType name=\"FeatureCollectionType\">");
2685 10 : PrintLine(fpSchema, " <xs:complexContent>");
2686 10 : PrintLine(
2687 : fpSchema,
2688 : " <xs:extension base=\"gml:AbstractFeatureCollectionType\">");
2689 10 : PrintLine(fpSchema, " <xs:attribute name=\"lockId\" "
2690 : "type=\"xs:string\" use=\"optional\"/>");
2691 10 : PrintLine(fpSchema, " <xs:attribute name=\"scope\" "
2692 : "type=\"xs:string\" use=\"optional\"/>");
2693 10 : PrintLine(fpSchema, " </xs:extension>");
2694 10 : PrintLine(fpSchema, " </xs:complexContent>");
2695 10 : PrintLine(fpSchema, "</xs:complexType>");
2696 : }
2697 :
2698 : // Define the schema for each layer.
2699 223 : for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
2700 : {
2701 125 : OGRFeatureDefn *poFDefn = papoLayers[iLayer]->GetLayerDefn();
2702 :
2703 : // Emit initial stuff for a feature type.
2704 125 : if (IsGML32Output())
2705 : {
2706 91 : PrintLine(fpSchema,
2707 : "<xs:element name=\"%s\" type=\"%s:%s_Type\" "
2708 : "substitutionGroup=\"gml:AbstractFeature\"/>",
2709 91 : poFDefn->GetName(), pszPrefix, poFDefn->GetName());
2710 : }
2711 : else
2712 : {
2713 34 : PrintLine(fpSchema,
2714 : "<xs:element name=\"%s\" type=\"%s:%s_Type\" "
2715 : "substitutionGroup=\"gml:_Feature\"/>",
2716 34 : poFDefn->GetName(), pszPrefix, poFDefn->GetName());
2717 : }
2718 :
2719 125 : PrintLine(fpSchema, "<xs:complexType name=\"%s_Type\">",
2720 125 : poFDefn->GetName());
2721 125 : PrintLine(fpSchema, " <xs:complexContent>");
2722 125 : PrintLine(fpSchema,
2723 : " <xs:extension base=\"gml:AbstractFeatureType\">");
2724 125 : PrintLine(fpSchema, " <xs:sequence>");
2725 :
2726 248 : for (int iGeomField = 0; iGeomField < poFDefn->GetGeomFieldCount();
2727 : iGeomField++)
2728 : {
2729 : OGRGeomFieldDefn *poFieldDefn =
2730 123 : poFDefn->GetGeomFieldDefn(iGeomField);
2731 :
2732 : // Define the geometry attribute.
2733 123 : const char *pszGeometryTypeName = "GeometryPropertyType";
2734 123 : const char *pszGeomTypeComment = "";
2735 123 : OGRwkbGeometryType eGType = wkbFlatten(poFieldDefn->GetType());
2736 123 : switch (eGType)
2737 : {
2738 25 : case wkbPoint:
2739 25 : pszGeometryTypeName = "PointPropertyType";
2740 25 : break;
2741 12 : case wkbLineString:
2742 : case wkbCircularString:
2743 : case wkbCompoundCurve:
2744 12 : if (IsGML3Output())
2745 : {
2746 12 : if (eGType == wkbLineString)
2747 11 : pszGeomTypeComment =
2748 : " <!-- restricted to LineString -->";
2749 1 : else if (eGType == wkbCircularString)
2750 0 : pszGeomTypeComment =
2751 : " <!-- contains CircularString -->";
2752 1 : else if (eGType == wkbCompoundCurve)
2753 1 : pszGeomTypeComment =
2754 : " <!-- contains CompoundCurve -->";
2755 12 : pszGeometryTypeName = "CurvePropertyType";
2756 : }
2757 : else
2758 0 : pszGeometryTypeName = "LineStringPropertyType";
2759 12 : break;
2760 16 : case wkbPolygon:
2761 : case wkbCurvePolygon:
2762 16 : if (IsGML3Output())
2763 : {
2764 14 : if (eGType == wkbPolygon)
2765 13 : pszGeomTypeComment =
2766 : " <!-- restricted to Polygon -->";
2767 1 : else if (eGType == wkbCurvePolygon)
2768 1 : pszGeomTypeComment =
2769 : " <!-- contains CurvePolygon -->";
2770 14 : pszGeometryTypeName = "SurfacePropertyType";
2771 : }
2772 : else
2773 2 : pszGeometryTypeName = "PolygonPropertyType";
2774 16 : break;
2775 6 : case wkbMultiPoint:
2776 6 : pszGeometryTypeName = "MultiPointPropertyType";
2777 6 : break;
2778 9 : case wkbMultiLineString:
2779 : case wkbMultiCurve:
2780 9 : if (IsGML3Output())
2781 : {
2782 9 : if (eGType == wkbMultiLineString)
2783 8 : pszGeomTypeComment =
2784 : " <!-- restricted to MultiLineString -->";
2785 1 : else if (eGType == wkbMultiCurve)
2786 1 : pszGeomTypeComment =
2787 : " <!-- contains non-linear MultiCurve -->";
2788 9 : pszGeometryTypeName = "MultiCurvePropertyType";
2789 : }
2790 : else
2791 0 : pszGeometryTypeName = "MultiLineStringPropertyType";
2792 9 : break;
2793 12 : case wkbMultiPolygon:
2794 : case wkbMultiSurface:
2795 12 : if (IsGML3Output())
2796 : {
2797 11 : if (eGType == wkbMultiPolygon)
2798 10 : pszGeomTypeComment =
2799 : " <!-- restricted to MultiPolygon -->";
2800 1 : else if (eGType == wkbMultiSurface)
2801 1 : pszGeomTypeComment =
2802 : " <!-- contains non-linear MultiSurface -->";
2803 11 : pszGeometryTypeName = "MultiSurfacePropertyType";
2804 : }
2805 : else
2806 1 : pszGeometryTypeName = "MultiPolygonPropertyType";
2807 12 : break;
2808 6 : case wkbGeometryCollection:
2809 6 : pszGeometryTypeName = "MultiGeometryPropertyType";
2810 6 : break;
2811 37 : default:
2812 37 : break;
2813 : }
2814 :
2815 123 : const auto poSRS = poFieldDefn->GetSpatialRef();
2816 246 : std::string osSRSNameComment;
2817 123 : if (poSRS)
2818 : {
2819 30 : bool bCoordSwap = false;
2820 : char *pszSRSName =
2821 30 : GML_GetSRSName(poSRS, GetSRSNameFormat(), &bCoordSwap);
2822 30 : if (pszSRSName[0])
2823 : {
2824 30 : osSRSNameComment = "<!--";
2825 30 : osSRSNameComment += pszSRSName;
2826 30 : osSRSNameComment += " -->";
2827 : }
2828 30 : CPLFree(pszSRSName);
2829 : }
2830 :
2831 123 : int nMinOccurs = poFieldDefn->IsNullable() ? 0 : 1;
2832 123 : const auto &oCoordPrec = poFieldDefn->GetCoordinatePrecision();
2833 123 : if (oCoordPrec.dfXYResolution ==
2834 122 : OGRGeomCoordinatePrecision::UNKNOWN &&
2835 122 : oCoordPrec.dfZResolution == OGRGeomCoordinatePrecision::UNKNOWN)
2836 : {
2837 122 : PrintLine(
2838 : fpSchema,
2839 : " <xs:element name=\"%s\" type=\"gml:%s\" "
2840 : "nillable=\"true\" minOccurs=\"%d\" maxOccurs=\"1\"/>%s%s",
2841 : poFieldDefn->GetNameRef(), pszGeometryTypeName, nMinOccurs,
2842 : pszGeomTypeComment, osSRSNameComment.c_str());
2843 : }
2844 : else
2845 : {
2846 1 : PrintLine(fpSchema,
2847 : " <xs:element name=\"%s\" type=\"gml:%s\" "
2848 : "nillable=\"true\" minOccurs=\"%d\" maxOccurs=\"1\">",
2849 : poFieldDefn->GetNameRef(), pszGeometryTypeName,
2850 : nMinOccurs);
2851 1 : PrintLine(fpSchema, " <xs:annotation>");
2852 1 : PrintLine(fpSchema, " <xs:appinfo "
2853 : "source=\"http://ogr.maptools.org/\">");
2854 1 : if (oCoordPrec.dfXYResolution !=
2855 : OGRGeomCoordinatePrecision::UNKNOWN)
2856 : {
2857 1 : PrintLine(fpSchema,
2858 : " "
2859 : "<ogr:xy_coordinate_resolution>%g</"
2860 : "ogr:xy_coordinate_resolution>",
2861 1 : oCoordPrec.dfXYResolution);
2862 : }
2863 1 : if (oCoordPrec.dfZResolution !=
2864 : OGRGeomCoordinatePrecision::UNKNOWN)
2865 : {
2866 1 : PrintLine(fpSchema,
2867 : " "
2868 : "<ogr:z_coordinate_resolution>%g</"
2869 : "ogr:z_coordinate_resolution>",
2870 1 : oCoordPrec.dfZResolution);
2871 : }
2872 1 : PrintLine(fpSchema, " </xs:appinfo>");
2873 1 : PrintLine(fpSchema, " </xs:annotation>");
2874 1 : PrintLine(fpSchema, " </xs:element>%s%s",
2875 : pszGeomTypeComment, osSRSNameComment.c_str());
2876 : }
2877 : }
2878 :
2879 : // Emit each of the attributes.
2880 306 : for (int iField = 0; iField < poFDefn->GetFieldCount(); iField++)
2881 : {
2882 181 : OGRFieldDefn *poFieldDefn = poFDefn->GetFieldDefn(iField);
2883 :
2884 351 : if (IsGML3Output() &&
2885 170 : strcmp(poFieldDefn->GetNameRef(), "gml_id") == 0)
2886 1 : continue;
2887 191 : else if (!IsGML3Output() &&
2888 11 : strcmp(poFieldDefn->GetNameRef(), "fid") == 0)
2889 0 : continue;
2890 :
2891 202 : const auto AddComment = [this, fpSchema, poFieldDefn]()
2892 : {
2893 180 : if (!poFieldDefn->GetComment().empty())
2894 : {
2895 11 : char *pszComment = CPLEscapeString(
2896 11 : poFieldDefn->GetComment().c_str(), -1, CPLES_XML);
2897 11 : PrintLine(fpSchema,
2898 : " "
2899 : "<xs:annotation><xs:documentation>%s</"
2900 : "xs:documentation></xs:annotation>",
2901 : pszComment);
2902 11 : CPLFree(pszComment);
2903 : }
2904 360 : };
2905 :
2906 180 : int nMinOccurs = poFieldDefn->IsNullable() ? 0 : 1;
2907 180 : const OGRFieldType eType = poFieldDefn->GetType();
2908 180 : if (eType == OFTInteger || eType == OFTIntegerList)
2909 : {
2910 : int nWidth =
2911 32 : poFieldDefn->GetWidth() > 0 ? poFieldDefn->GetWidth() : 16;
2912 :
2913 32 : PrintLine(fpSchema,
2914 : " <xs:element name=\"%s\" nillable=\"true\" "
2915 : "minOccurs=\"%d\" maxOccurs=\"%s\">",
2916 : poFieldDefn->GetNameRef(), nMinOccurs,
2917 : eType == OFTIntegerList ? "unbounded" : "1");
2918 32 : AddComment();
2919 32 : PrintLine(fpSchema, " <xs:simpleType>");
2920 32 : if (poFieldDefn->GetSubType() == OFSTBoolean)
2921 : {
2922 3 : PrintLine(
2923 : fpSchema,
2924 : " <xs:restriction base=\"xs:boolean\">");
2925 : }
2926 29 : else if (poFieldDefn->GetSubType() == OFSTInt16)
2927 : {
2928 1 : PrintLine(fpSchema,
2929 : " <xs:restriction base=\"xs:short\">");
2930 : }
2931 : else
2932 : {
2933 28 : PrintLine(
2934 : fpSchema,
2935 : " <xs:restriction base=\"xs:integer\">");
2936 28 : PrintLine(fpSchema,
2937 : " <xs:totalDigits value=\"%d\"/>",
2938 : nWidth);
2939 : }
2940 32 : PrintLine(fpSchema, " </xs:restriction>");
2941 32 : PrintLine(fpSchema, " </xs:simpleType>");
2942 32 : PrintLine(fpSchema, " </xs:element>");
2943 : }
2944 148 : else if (eType == OFTInteger64 || eType == OFTInteger64List)
2945 : {
2946 : int nWidth =
2947 17 : poFieldDefn->GetWidth() > 0 ? poFieldDefn->GetWidth() : 16;
2948 :
2949 17 : PrintLine(fpSchema,
2950 : " <xs:element name=\"%s\" nillable=\"true\" "
2951 : "minOccurs=\"%d\" maxOccurs=\"%s\">",
2952 : poFieldDefn->GetNameRef(), nMinOccurs,
2953 : eType == OFTInteger64List ? "unbounded" : "1");
2954 17 : AddComment();
2955 17 : PrintLine(fpSchema, " <xs:simpleType>");
2956 17 : if (poFieldDefn->GetSubType() == OFSTBoolean)
2957 : {
2958 0 : PrintLine(
2959 : fpSchema,
2960 : " <xs:restriction base=\"xs:boolean\">");
2961 : }
2962 17 : else if (poFieldDefn->GetSubType() == OFSTInt16)
2963 : {
2964 0 : PrintLine(fpSchema,
2965 : " <xs:restriction base=\"xs:short\">");
2966 : }
2967 : else
2968 : {
2969 17 : PrintLine(fpSchema,
2970 : " <xs:restriction base=\"xs:long\">");
2971 17 : PrintLine(fpSchema,
2972 : " <xs:totalDigits value=\"%d\"/>",
2973 : nWidth);
2974 : }
2975 17 : PrintLine(fpSchema, " </xs:restriction>");
2976 17 : PrintLine(fpSchema, " </xs:simpleType>");
2977 17 : PrintLine(fpSchema, " </xs:element>");
2978 : }
2979 131 : else if (eType == OFTReal || eType == OFTRealList)
2980 : {
2981 : int nWidth, nDecimals;
2982 :
2983 35 : nWidth = poFieldDefn->GetWidth();
2984 35 : nDecimals = poFieldDefn->GetPrecision();
2985 :
2986 35 : PrintLine(fpSchema,
2987 : " <xs:element name=\"%s\" nillable=\"true\" "
2988 : "minOccurs=\"%d\" maxOccurs=\"%s\">",
2989 : poFieldDefn->GetNameRef(), nMinOccurs,
2990 : eType == OFTRealList ? "unbounded" : "1");
2991 35 : AddComment();
2992 35 : PrintLine(fpSchema, " <xs:simpleType>");
2993 35 : if (poFieldDefn->GetSubType() == OFSTFloat32)
2994 1 : PrintLine(fpSchema,
2995 : " <xs:restriction base=\"xs:float\">");
2996 : else
2997 34 : PrintLine(
2998 : fpSchema,
2999 : " <xs:restriction base=\"xs:decimal\">");
3000 35 : if (nWidth > 0)
3001 : {
3002 14 : PrintLine(fpSchema,
3003 : " <xs:totalDigits value=\"%d\"/>",
3004 : nWidth);
3005 14 : PrintLine(fpSchema,
3006 : " <xs:fractionDigits value=\"%d\"/>",
3007 : nDecimals);
3008 : }
3009 35 : PrintLine(fpSchema, " </xs:restriction>");
3010 35 : PrintLine(fpSchema, " </xs:simpleType>");
3011 35 : PrintLine(fpSchema, " </xs:element>");
3012 : }
3013 96 : else if (eType == OFTString || eType == OFTStringList)
3014 : {
3015 58 : PrintLine(fpSchema,
3016 : " <xs:element name=\"%s\" nillable=\"true\" "
3017 : "minOccurs=\"%d\" maxOccurs=\"%s\">",
3018 : poFieldDefn->GetNameRef(), nMinOccurs,
3019 : eType == OFTStringList ? "unbounded" : "1");
3020 58 : AddComment();
3021 58 : PrintLine(fpSchema, " <xs:simpleType>");
3022 58 : PrintLine(fpSchema,
3023 : " <xs:restriction base=\"xs:string\">");
3024 58 : if (poFieldDefn->GetWidth() != 0)
3025 : {
3026 10 : PrintLine(fpSchema,
3027 : " <xs:maxLength value=\"%d\"/>",
3028 : poFieldDefn->GetWidth());
3029 : }
3030 58 : PrintLine(fpSchema, " </xs:restriction>");
3031 58 : PrintLine(fpSchema, " </xs:simpleType>");
3032 58 : PrintLine(fpSchema, " </xs:element>");
3033 : }
3034 38 : else if (eType == OFTDate)
3035 : {
3036 18 : PrintLine(fpSchema,
3037 : " <xs:element name=\"%s\" nillable=\"true\" "
3038 : "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:date\">",
3039 : poFieldDefn->GetNameRef(), nMinOccurs);
3040 18 : AddComment();
3041 18 : PrintLine(fpSchema, " </xs:element>");
3042 : }
3043 20 : else if (eType == OFTTime)
3044 : {
3045 2 : PrintLine(fpSchema,
3046 : " <xs:element name=\"%s\" nillable=\"true\" "
3047 : "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:time\">",
3048 : poFieldDefn->GetNameRef(), nMinOccurs);
3049 2 : AddComment();
3050 2 : PrintLine(fpSchema, " </xs:element>");
3051 : }
3052 18 : else if (eType == OFTDateTime)
3053 : {
3054 18 : PrintLine(
3055 : fpSchema,
3056 : " <xs:element name=\"%s\" nillable=\"true\" "
3057 : "minOccurs=\"%d\" maxOccurs=\"1\" type=\"xs:dateTime\">",
3058 : poFieldDefn->GetNameRef(), nMinOccurs);
3059 18 : AddComment();
3060 18 : PrintLine(fpSchema, " </xs:element>");
3061 : }
3062 : else
3063 : {
3064 : // TODO.
3065 : }
3066 : } // Next field.
3067 :
3068 : // Finish off feature type.
3069 125 : PrintLine(fpSchema, " </xs:sequence>");
3070 125 : PrintLine(fpSchema, " </xs:extension>");
3071 125 : PrintLine(fpSchema, " </xs:complexContent>");
3072 125 : PrintLine(fpSchema, "</xs:complexType>");
3073 : } // Next layer.
3074 :
3075 98 : PrintLine(fpSchema, "</xs:schema>");
3076 :
3077 : // Move schema to the start of the file.
3078 98 : if (fpSchema == fpOutput)
3079 : {
3080 : // Read the schema into memory.
3081 0 : int nSchemaSize = static_cast<int>(VSIFTellL(fpSchema) - nSchemaStart);
3082 0 : char *pszSchema = static_cast<char *>(CPLMalloc(nSchemaSize + 1));
3083 :
3084 0 : VSIFSeekL(fpSchema, nSchemaStart, SEEK_SET);
3085 :
3086 0 : VSIFReadL(pszSchema, 1, nSchemaSize, fpSchema);
3087 0 : pszSchema[nSchemaSize] = '\0';
3088 :
3089 : // Move file data down by "schema size" bytes from after <?xml> header
3090 : // so we have room insert the schema. Move in pretty big chunks.
3091 0 : int nChunkSize = std::min(nSchemaStart - nSchemaInsertLocation, 250000);
3092 0 : char *pszChunk = static_cast<char *>(CPLMalloc(nChunkSize));
3093 :
3094 0 : for (int nEndOfUnmovedData = nSchemaStart;
3095 0 : nEndOfUnmovedData > nSchemaInsertLocation;)
3096 : {
3097 : const int nBytesToMove =
3098 0 : std::min(nChunkSize, nEndOfUnmovedData - nSchemaInsertLocation);
3099 :
3100 0 : VSIFSeekL(fpSchema, nEndOfUnmovedData - nBytesToMove, SEEK_SET);
3101 0 : VSIFReadL(pszChunk, 1, nBytesToMove, fpSchema);
3102 0 : VSIFSeekL(fpSchema, nEndOfUnmovedData - nBytesToMove + nSchemaSize,
3103 : SEEK_SET);
3104 0 : VSIFWriteL(pszChunk, 1, nBytesToMove, fpSchema);
3105 :
3106 0 : nEndOfUnmovedData -= nBytesToMove;
3107 : }
3108 :
3109 0 : CPLFree(pszChunk);
3110 :
3111 : // Write the schema in the opened slot.
3112 0 : VSIFSeekL(fpSchema, nSchemaInsertLocation, SEEK_SET);
3113 0 : VSIFWriteL(pszSchema, 1, nSchemaSize, fpSchema);
3114 :
3115 0 : VSIFSeekL(fpSchema, 0, SEEK_END);
3116 :
3117 0 : nBoundedByLocation += nSchemaSize;
3118 :
3119 0 : CPLFree(pszSchema);
3120 : }
3121 : else
3122 : {
3123 : // Close external schema files.
3124 98 : VSIFCloseL(fpSchema);
3125 : }
3126 : }
3127 :
3128 : /************************************************************************/
3129 : /* PrintLine() */
3130 : /************************************************************************/
3131 :
3132 8564 : void OGRGMLDataSource::PrintLine(VSILFILE *fp, const char *fmt, ...)
3133 : {
3134 17128 : CPLString osWork;
3135 : va_list args;
3136 :
3137 8564 : va_start(args, fmt);
3138 8564 : osWork.vPrintf(fmt, args);
3139 8564 : va_end(args);
3140 :
3141 : #ifdef _WIN32
3142 : constexpr const char *pszEOL = "\r\n";
3143 : #else
3144 8564 : constexpr const char *pszEOL = "\n";
3145 : #endif
3146 :
3147 17123 : if (VSIFWriteL(osWork.data(), osWork.size(), 1, fp) != 1 ||
3148 8559 : VSIFWriteL(pszEOL, strlen(pszEOL), 1, fp) != 1)
3149 : {
3150 5 : m_bWriteError = true;
3151 5 : ReportError(CE_Failure, CPLE_FileIO, "Could not write line %s",
3152 : osWork.c_str());
3153 : }
3154 8564 : }
3155 :
3156 : /************************************************************************/
3157 : /* OGRGMLSingleFeatureLayer */
3158 : /************************************************************************/
3159 :
3160 : class OGRGMLSingleFeatureLayer final : public OGRLayer
3161 : {
3162 : private:
3163 : const int nVal;
3164 : OGRFeatureDefn *poFeatureDefn = nullptr;
3165 : int iNextShapeId = 0;
3166 :
3167 : CPL_DISALLOW_COPY_ASSIGN(OGRGMLSingleFeatureLayer)
3168 :
3169 : public:
3170 : explicit OGRGMLSingleFeatureLayer(int nVal);
3171 :
3172 0 : virtual ~OGRGMLSingleFeatureLayer()
3173 0 : {
3174 0 : poFeatureDefn->Release();
3175 0 : }
3176 :
3177 0 : virtual void ResetReading() override
3178 : {
3179 0 : iNextShapeId = 0;
3180 0 : }
3181 :
3182 : virtual OGRFeature *GetNextFeature() override;
3183 :
3184 0 : virtual OGRFeatureDefn *GetLayerDefn() override
3185 : {
3186 0 : return poFeatureDefn;
3187 : }
3188 :
3189 0 : virtual int TestCapability(const char *) override
3190 : {
3191 0 : return FALSE;
3192 : }
3193 : };
3194 :
3195 : /************************************************************************/
3196 : /* OGRGMLSingleFeatureLayer() */
3197 : /************************************************************************/
3198 :
3199 0 : OGRGMLSingleFeatureLayer::OGRGMLSingleFeatureLayer(int nValIn)
3200 0 : : nVal(nValIn), poFeatureDefn(new OGRFeatureDefn("SELECT")), iNextShapeId(0)
3201 : {
3202 0 : poFeatureDefn->Reference();
3203 0 : OGRFieldDefn oField("Validates", OFTInteger);
3204 0 : poFeatureDefn->AddFieldDefn(&oField);
3205 0 : }
3206 :
3207 : /************************************************************************/
3208 : /* GetNextFeature() */
3209 : /************************************************************************/
3210 :
3211 0 : OGRFeature *OGRGMLSingleFeatureLayer::GetNextFeature()
3212 : {
3213 0 : if (iNextShapeId != 0)
3214 0 : return nullptr;
3215 :
3216 0 : OGRFeature *poFeature = new OGRFeature(poFeatureDefn);
3217 0 : poFeature->SetField(0, nVal);
3218 0 : poFeature->SetFID(iNextShapeId++);
3219 0 : return poFeature;
3220 : }
3221 :
3222 : /************************************************************************/
3223 : /* ExecuteSQL() */
3224 : /************************************************************************/
3225 :
3226 6 : OGRLayer *OGRGMLDataSource::ExecuteSQL(const char *pszSQLCommand,
3227 : OGRGeometry *poSpatialFilter,
3228 : const char *pszDialect)
3229 : {
3230 6 : if (poReader != nullptr && EQUAL(pszSQLCommand, "SELECT ValidateSchema()"))
3231 : {
3232 0 : bool bIsValid = false;
3233 0 : if (!osXSDFilename.empty())
3234 : {
3235 0 : CPLErrorReset();
3236 : bIsValid =
3237 0 : CPL_TO_BOOL(CPLValidateXML(osFilename, osXSDFilename, nullptr));
3238 : }
3239 0 : return new OGRGMLSingleFeatureLayer(bIsValid);
3240 : }
3241 :
3242 6 : return GDALDataset::ExecuteSQL(pszSQLCommand, poSpatialFilter, pszDialect);
3243 : }
3244 :
3245 : /************************************************************************/
3246 : /* ReleaseResultSet() */
3247 : /************************************************************************/
3248 :
3249 5 : void OGRGMLDataSource::ReleaseResultSet(OGRLayer *poResultsSet)
3250 : {
3251 5 : delete poResultsSet;
3252 5 : }
3253 :
3254 : /************************************************************************/
3255 : /* FindAndParseTopElements() */
3256 : /************************************************************************/
3257 :
3258 446 : void OGRGMLDataSource::FindAndParseTopElements(VSILFILE *fp)
3259 : {
3260 : // Build a shortened XML file that contain only the global
3261 : // boundedBy element, so as to be able to parse it easily.
3262 :
3263 : char szStartTag[128];
3264 446 : char *pszXML = static_cast<char *>(CPLMalloc(8192 + 128 + 3 + 1));
3265 446 : VSIFSeekL(fp, 0, SEEK_SET);
3266 446 : int nRead = static_cast<int>(VSIFReadL(pszXML, 1, 8192, fp));
3267 446 : pszXML[nRead] = 0;
3268 :
3269 446 : const char *pszStartTag = strchr(pszXML, '<');
3270 446 : if (pszStartTag != nullptr)
3271 : {
3272 813 : while (pszStartTag != nullptr && pszStartTag[1] == '?')
3273 367 : pszStartTag = strchr(pszStartTag + 1, '<');
3274 :
3275 446 : if (pszStartTag != nullptr)
3276 : {
3277 446 : pszStartTag++;
3278 446 : const char *pszEndTag = nullptr;
3279 9539 : for (const char *pszIter = pszStartTag; *pszIter != '\0'; pszIter++)
3280 : {
3281 9539 : if (isspace(static_cast<unsigned char>(*pszIter)) ||
3282 9095 : *pszIter == '>')
3283 : {
3284 446 : pszEndTag = pszIter;
3285 446 : break;
3286 : }
3287 : }
3288 446 : if (pszEndTag != nullptr && pszEndTag - pszStartTag < 128)
3289 : {
3290 446 : memcpy(szStartTag, pszStartTag, pszEndTag - pszStartTag);
3291 446 : szStartTag[pszEndTag - pszStartTag] = '\0';
3292 : }
3293 : else
3294 0 : pszStartTag = nullptr;
3295 : }
3296 : }
3297 :
3298 446 : const char *pszFeatureMember = strstr(pszXML, "<gml:featureMember");
3299 446 : if (pszFeatureMember == nullptr)
3300 279 : pszFeatureMember = strstr(pszXML, ":featureMember>");
3301 446 : if (pszFeatureMember == nullptr)
3302 168 : pszFeatureMember = strstr(pszXML, "<wfs:member>");
3303 :
3304 : // Is it a standalone geometry ?
3305 446 : if (pszFeatureMember == nullptr && pszStartTag != nullptr)
3306 : {
3307 106 : const char *pszElement = szStartTag;
3308 106 : const char *pszColon = strchr(pszElement, ':');
3309 106 : if (pszColon)
3310 73 : pszElement = pszColon + 1;
3311 106 : if (OGRGMLIsGeometryElement(pszElement))
3312 : {
3313 1 : VSIFSeekL(fp, 0, SEEK_END);
3314 1 : const auto nLen = VSIFTellL(fp);
3315 1 : if (nLen < 10 * 1024 * 1024U)
3316 : {
3317 1 : VSIFSeekL(fp, 0, SEEK_SET);
3318 2 : std::string osBuffer;
3319 : try
3320 : {
3321 1 : osBuffer.resize(static_cast<size_t>(nLen));
3322 1 : VSIFReadL(&osBuffer[0], 1, osBuffer.size(), fp);
3323 : }
3324 0 : catch (const std::exception &)
3325 : {
3326 : }
3327 1 : CPLPushErrorHandler(CPLQuietErrorHandler);
3328 1 : CPLXMLNode *psTree = CPLParseXMLString(osBuffer.data());
3329 1 : CPLPopErrorHandler();
3330 1 : CPLErrorReset();
3331 1 : if (psTree)
3332 : {
3333 1 : m_poStandaloneGeom.reset(GML2OGRGeometry_XMLNode(
3334 : psTree, false, 0, 0, false, true, false));
3335 :
3336 1 : if (m_poStandaloneGeom)
3337 : {
3338 2 : for (CPLXMLNode *psCur = psTree; psCur;
3339 1 : psCur = psCur->psNext)
3340 : {
3341 2 : if (psCur->eType == CXT_Element &&
3342 2 : strcmp(psCur->pszValue, szStartTag) == 0)
3343 : {
3344 : const char *pszSRSName =
3345 1 : CPLGetXMLValue(psCur, "srsName", nullptr);
3346 1 : if (pszSRSName)
3347 : {
3348 1 : m_oStandaloneGeomSRS.SetFromUserInput(
3349 : pszSRSName,
3350 : OGRSpatialReference::
3351 : SET_FROM_USER_INPUT_LIMITATIONS_get());
3352 1 : m_oStandaloneGeomSRS.SetAxisMappingStrategy(
3353 : OAMS_TRADITIONAL_GIS_ORDER);
3354 1 : if (GML_IsSRSLatLongOrder(pszSRSName))
3355 1 : m_poStandaloneGeom->swapXY();
3356 : }
3357 1 : break;
3358 : }
3359 : }
3360 : }
3361 1 : CPLDestroyXMLNode(psTree);
3362 : }
3363 : }
3364 : }
3365 : }
3366 :
3367 446 : const char *pszDescription = strstr(pszXML, "<gml:description>");
3368 446 : if (pszDescription &&
3369 1 : (pszFeatureMember == nullptr || pszDescription < pszFeatureMember))
3370 : {
3371 8 : pszDescription += strlen("<gml:description>");
3372 : const char *pszEndDescription =
3373 8 : strstr(pszDescription, "</gml:description>");
3374 8 : if (pszEndDescription)
3375 : {
3376 16 : CPLString osTmp(pszDescription);
3377 8 : osTmp.resize(pszEndDescription - pszDescription);
3378 8 : char *pszTmp = CPLUnescapeString(osTmp, nullptr, CPLES_XML);
3379 8 : if (pszTmp)
3380 8 : SetMetadataItem("DESCRIPTION", pszTmp);
3381 8 : CPLFree(pszTmp);
3382 : }
3383 : }
3384 :
3385 446 : const char *l_pszName = strstr(pszXML, "<gml:name");
3386 446 : if (l_pszName)
3387 11 : l_pszName = strchr(l_pszName, '>');
3388 446 : if (l_pszName &&
3389 4 : (pszFeatureMember == nullptr || l_pszName < pszFeatureMember))
3390 : {
3391 8 : l_pszName++;
3392 8 : const char *pszEndName = strstr(l_pszName, "</gml:name>");
3393 8 : if (pszEndName)
3394 : {
3395 16 : CPLString osTmp(l_pszName);
3396 8 : osTmp.resize(pszEndName - l_pszName);
3397 8 : char *pszTmp = CPLUnescapeString(osTmp, nullptr, CPLES_XML);
3398 8 : if (pszTmp)
3399 8 : SetMetadataItem("NAME", pszTmp);
3400 8 : CPLFree(pszTmp);
3401 : }
3402 : }
3403 :
3404 : // Detect a few fields in gml: namespace inside features
3405 446 : if (pszFeatureMember)
3406 : {
3407 340 : if (strstr(pszFeatureMember, "<gml:description>"))
3408 1 : m_aosGMLExtraElements.push_back("description");
3409 340 : if (strstr(pszFeatureMember, "<gml:identifier>") ||
3410 340 : strstr(pszFeatureMember, "<gml:identifier "))
3411 1 : m_aosGMLExtraElements.push_back("identifier");
3412 340 : if (strstr(pszFeatureMember, "<gml:name>") ||
3413 336 : strstr(pszFeatureMember, "<gml:name "))
3414 4 : m_aosGMLExtraElements.push_back("name");
3415 : }
3416 :
3417 446 : char *pszEndBoundedBy = strstr(pszXML, "</wfs:boundedBy>");
3418 446 : bool bWFSBoundedBy = false;
3419 446 : if (pszEndBoundedBy != nullptr)
3420 2 : bWFSBoundedBy = true;
3421 : else
3422 444 : pszEndBoundedBy = strstr(pszXML, "</gml:boundedBy>");
3423 446 : if (pszStartTag != nullptr && pszEndBoundedBy != nullptr)
3424 : {
3425 225 : char szSRSName[128] = {};
3426 :
3427 : // Find a srsName somewhere for some WFS 2.0 documents that have not it
3428 : // set at the <wfs:boundedBy> element. e.g.
3429 : // http://geoserv.weichand.de:8080/geoserver/wfs?SERVICE=WFS&REQUEST=GetFeature&VERSION=2.0.0&TYPENAME=bvv:gmd_ex
3430 225 : if (bIsWFS)
3431 : {
3432 24 : ExtractSRSName(pszXML, szSRSName, sizeof(szSRSName));
3433 : }
3434 :
3435 225 : pszEndBoundedBy[strlen("</gml:boundedBy>")] = '\0';
3436 225 : strcat(pszXML, "</");
3437 225 : strcat(pszXML, szStartTag);
3438 225 : strcat(pszXML, ">");
3439 :
3440 225 : CPLPushErrorHandler(CPLQuietErrorHandler);
3441 225 : CPLXMLNode *psXML = CPLParseXMLString(pszXML);
3442 225 : CPLPopErrorHandler();
3443 225 : CPLErrorReset();
3444 225 : if (psXML != nullptr)
3445 : {
3446 220 : CPLXMLNode *psBoundedBy = nullptr;
3447 220 : CPLXMLNode *psIter = psXML;
3448 436 : while (psIter != nullptr)
3449 : {
3450 436 : psBoundedBy = CPLGetXMLNode(
3451 : psIter, bWFSBoundedBy ? "wfs:boundedBy" : "gml:boundedBy");
3452 436 : if (psBoundedBy != nullptr)
3453 220 : break;
3454 216 : psIter = psIter->psNext;
3455 : }
3456 :
3457 220 : const char *pszLowerCorner = nullptr;
3458 220 : const char *pszUpperCorner = nullptr;
3459 220 : const char *pszSRSName = nullptr;
3460 220 : if (psBoundedBy != nullptr)
3461 : {
3462 : CPLXMLNode *psEnvelope =
3463 220 : CPLGetXMLNode(psBoundedBy, "gml:Envelope");
3464 220 : if (psEnvelope)
3465 : {
3466 114 : pszSRSName = CPLGetXMLValue(psEnvelope, "srsName", nullptr);
3467 : pszLowerCorner =
3468 114 : CPLGetXMLValue(psEnvelope, "gml:lowerCorner", nullptr);
3469 : pszUpperCorner =
3470 114 : CPLGetXMLValue(psEnvelope, "gml:upperCorner", nullptr);
3471 : }
3472 : }
3473 :
3474 220 : if (bIsWFS && pszSRSName == nullptr && pszLowerCorner != nullptr &&
3475 0 : pszUpperCorner != nullptr && szSRSName[0] != '\0')
3476 : {
3477 0 : pszSRSName = szSRSName;
3478 : }
3479 :
3480 220 : if (pszSRSName != nullptr && pszLowerCorner != nullptr &&
3481 : pszUpperCorner != nullptr)
3482 : {
3483 62 : char **papszLC = CSLTokenizeString(pszLowerCorner);
3484 62 : char **papszUC = CSLTokenizeString(pszUpperCorner);
3485 62 : if (CSLCount(papszLC) >= 2 && CSLCount(papszUC) >= 2)
3486 : {
3487 62 : CPLDebug("GML", "Global SRS = %s", pszSRSName);
3488 :
3489 62 : if (STARTS_WITH(pszSRSName,
3490 : "http://www.opengis.net/gml/srs/epsg.xml#"))
3491 : {
3492 0 : std::string osWork;
3493 0 : osWork.assign("EPSG:", 5);
3494 0 : osWork.append(pszSRSName + 40);
3495 0 : poReader->SetGlobalSRSName(osWork.c_str());
3496 : }
3497 : else
3498 : {
3499 62 : poReader->SetGlobalSRSName(pszSRSName);
3500 : }
3501 :
3502 62 : const double dfMinX = CPLAtofM(papszLC[0]);
3503 62 : const double dfMinY = CPLAtofM(papszLC[1]);
3504 62 : const double dfMaxX = CPLAtofM(papszUC[0]);
3505 62 : const double dfMaxY = CPLAtofM(papszUC[1]);
3506 :
3507 62 : SetExtents(dfMinX, dfMinY, dfMaxX, dfMaxY);
3508 : }
3509 62 : CSLDestroy(papszLC);
3510 62 : CSLDestroy(papszUC);
3511 : }
3512 :
3513 220 : CPLDestroyXMLNode(psXML);
3514 : }
3515 : }
3516 :
3517 446 : CPLFree(pszXML);
3518 446 : }
3519 :
3520 : /************************************************************************/
3521 : /* SetExtents() */
3522 : /************************************************************************/
3523 :
3524 62 : void OGRGMLDataSource::SetExtents(double dfMinX, double dfMinY, double dfMaxX,
3525 : double dfMaxY)
3526 : {
3527 62 : sBoundingRect.MinX = dfMinX;
3528 62 : sBoundingRect.MinY = dfMinY;
3529 62 : sBoundingRect.MaxX = dfMaxX;
3530 62 : sBoundingRect.MaxY = dfMaxY;
3531 62 : }
3532 :
3533 : /************************************************************************/
3534 : /* GetAppPrefix() */
3535 : /************************************************************************/
3536 :
3537 1100 : const char *OGRGMLDataSource::GetAppPrefix() const
3538 : {
3539 1100 : return CSLFetchNameValueDef(papszCreateOptions, "PREFIX", "ogr");
3540 : }
3541 :
3542 : /************************************************************************/
3543 : /* RemoveAppPrefix() */
3544 : /************************************************************************/
3545 :
3546 563 : bool OGRGMLDataSource::RemoveAppPrefix() const
3547 : {
3548 563 : if (CPLTestBool(
3549 563 : CSLFetchNameValueDef(papszCreateOptions, "STRIP_PREFIX", "FALSE")))
3550 26 : return true;
3551 537 : const char *pszPrefix = GetAppPrefix();
3552 537 : return pszPrefix[0] == '\0';
3553 : }
3554 :
3555 : /************************************************************************/
3556 : /* WriteFeatureBoundedBy() */
3557 : /************************************************************************/
3558 :
3559 181 : bool OGRGMLDataSource::WriteFeatureBoundedBy() const
3560 : {
3561 181 : return CPLTestBool(CSLFetchNameValueDef(
3562 362 : papszCreateOptions, "WRITE_FEATURE_BOUNDED_BY", "TRUE"));
3563 : }
3564 :
3565 : /************************************************************************/
3566 : /* GetSRSDimensionLoc() */
3567 : /************************************************************************/
3568 :
3569 215 : const char *OGRGMLDataSource::GetSRSDimensionLoc() const
3570 : {
3571 215 : return CSLFetchNameValue(papszCreateOptions, "SRSDIMENSION_LOC");
3572 : }
3573 :
3574 : /************************************************************************/
3575 : /* GMLFeatureCollection() */
3576 : /************************************************************************/
3577 :
3578 564 : bool OGRGMLDataSource::GMLFeatureCollection() const
3579 : {
3580 1064 : return IsGML3Output() &&
3581 1064 : CPLFetchBool(papszCreateOptions, "GML_FEATURE_COLLECTION", false);
3582 : }
|