LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/wfs - ogrwfslayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1219 1492 81.7 %
Date: 2025-10-27 00:14:23 Functions: 38 41 92.7 %

          Line data    Source code
       1             : /******************************************************************************
       2             :  *
       3             :  * Project:  WFS Translator
       4             :  * Purpose:  Implements OGRWFSLayer class.
       5             :  * Author:   Even Rouault, <even dot rouault at spatialys.com>
       6             :  *
       7             :  ******************************************************************************
       8             :  * Copyright (c) 2010-2013, Even Rouault <even dot rouault at spatialys.com>
       9             :  *
      10             :  * SPDX-License-Identifier: MIT
      11             :  ****************************************************************************/
      12             : 
      13             : #include "cpl_port.h"
      14             : #include "ogr_wfs.h"
      15             : #include "ogr_api.h"
      16             : #include "cpl_minixml.h"
      17             : #include "cpl_http.h"
      18             : #include "parsexsd.h"
      19             : #include "ogrwfsfilter.h"
      20             : 
      21             : /************************************************************************/
      22             : /*                            OGRWFSLayer()                             */
      23             : /************************************************************************/
      24             : 
      25         212 : OGRWFSLayer::OGRWFSLayer(OGRWFSDataSource *poDSIn, OGRSpatialReference *poSRSIn,
      26             :                          int bAxisOrderAlreadyInvertedIn,
      27             :                          const char *pszBaseURLIn, const char *pszNameIn,
      28         212 :                          const char *pszNSIn, const char *pszNSValIn)
      29             :     : poDS(poDSIn), bAxisOrderAlreadyInverted(bAxisOrderAlreadyInvertedIn),
      30         212 :       m_poSRS(poSRSIn), pszBaseURL(CPLStrdup(pszBaseURLIn)),
      31         424 :       pszName(CPLStrdup(pszNameIn)),
      32         212 :       pszNS(pszNSIn ? CPLStrdup(pszNSIn) : nullptr),
      33         212 :       pszNSVal(pszNSValIn ? CPLStrdup(pszNSValIn) : nullptr),
      34             :       // If changing that, change in the GML driver too
      35         848 :       m_osTmpDir(VSIMemGenerateHiddenFilename("_ogr_wfs_"))
      36             : {
      37         212 :     SetDescription(pszName);
      38         212 : }
      39             : 
      40             : /************************************************************************/
      41             : /*                             Clone()                                  */
      42             : /************************************************************************/
      43             : 
      44           0 : OGRWFSLayer *OGRWFSLayer::Clone()
      45             : {
      46             :     OGRWFSLayer *poDupLayer =
      47           0 :         new OGRWFSLayer(poDS, m_poSRS, bAxisOrderAlreadyInverted, pszBaseURL,
      48           0 :                         pszName, pszNS, pszNSVal);
      49           0 :     if (m_poSRS)
      50           0 :         m_poSRS->Reference();
      51           0 :     poDupLayer->poFeatureDefn = GetLayerDefn()->Clone();
      52           0 :     poDupLayer->poFeatureDefn->Reference();
      53           0 :     poDupLayer->bGotApproximateLayerDefn = bGotApproximateLayerDefn;
      54           0 :     poDupLayer->eGeomType = poDupLayer->poFeatureDefn->GetGeomType();
      55           0 :     poDupLayer->pszRequiredOutputFormat =
      56           0 :         pszRequiredOutputFormat ? CPLStrdup(pszRequiredOutputFormat) : nullptr;
      57             : 
      58             :     /* Copy existing schema file if already found */
      59           0 :     CPLString osSrcFileName = CPLSPrintf("%s/file.xsd", m_osTmpDir.c_str());
      60             :     CPLString osTargetFileName =
      61           0 :         CPLSPrintf("%s/file.xsd", poDupLayer->m_osTmpDir.c_str());
      62           0 :     CPL_IGNORE_RET_VAL(CPLCopyFile(osTargetFileName, osSrcFileName));
      63             : 
      64           0 :     return poDupLayer;
      65             : }
      66             : 
      67             : /************************************************************************/
      68             : /*                            ~OGRWFSLayer()                            */
      69             : /************************************************************************/
      70             : 
      71         424 : OGRWFSLayer::~OGRWFSLayer()
      72             : 
      73             : {
      74         212 :     if (bInTransaction)
      75           0 :         OGRWFSLayer::CommitTransaction();
      76             : 
      77         212 :     if (m_poSRS != nullptr)
      78         194 :         m_poSRS->Release();
      79             : 
      80         212 :     if (poFeatureDefn != nullptr)
      81         166 :         poFeatureDefn->Release();
      82         212 :     delete poGMLFeatureClass;
      83             : 
      84         212 :     CPLFree(pszBaseURL);
      85         212 :     CPLFree(pszName);
      86         212 :     CPLFree(pszNS);
      87         212 :     CPLFree(pszNSVal);
      88             : 
      89         212 :     GDALClose(poBaseDS);
      90             : 
      91         212 :     delete poFetchedFilterGeom;
      92             : 
      93         212 :     VSIRmdirRecursive(m_osTmpDir.c_str());
      94             : 
      95         212 :     CPLFree(pszRequiredOutputFormat);
      96         424 : }
      97             : 
      98             : /************************************************************************/
      99             : /*                          SetActiveSRS()                              */
     100             : /************************************************************************/
     101             : 
     102           4 : OGRErr OGRWFSLayer::SetActiveSRS(int /*iGeomField*/,
     103             :                                  const OGRSpatialReference *poSRS)
     104             : {
     105           4 :     if (poSRS == nullptr)
     106           1 :         return OGRERR_FAILURE;
     107           3 :     const char *const apszOptions[] = {
     108             :         "IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES", nullptr};
     109           3 :     size_t i = 0;
     110           9 :     for (const auto &poSupportedSRS : m_apoSupportedCRSList)
     111             :     {
     112           8 :         if (poSupportedSRS->IsSame(poSRS, apszOptions))
     113             :         {
     114           2 :             m_osSRSName = m_aosSupportedCRSList[i];
     115           2 :             if (m_poSRS)
     116           2 :                 m_poSRS->Release();
     117           2 :             m_poSRS = poSRS->Clone();
     118           2 :             m_poSRS->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     119           2 :             if (poFeatureDefn)
     120             :             {
     121           2 :                 auto poGeomFieldDefn = poFeatureDefn->GetGeomFieldDefn(0);
     122           2 :                 if (poGeomFieldDefn)
     123             :                 {
     124           2 :                     poGeomFieldDefn->SetSpatialRef(m_poSRS);
     125             :                 }
     126             :             }
     127           2 :             m_oExtents = OGREnvelope();
     128           2 :             if (m_oWGS84Extents.IsInit())
     129             :             {
     130           4 :                 OGRSpatialReference oWGS84;
     131           2 :                 oWGS84.SetWellKnownGeogCS("WGS84");
     132           2 :                 oWGS84.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
     133             :                 auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
     134           4 :                     OGRCreateCoordinateTransformation(&oWGS84, m_poSRS));
     135           2 :                 if (poCT)
     136             :                 {
     137           2 :                     poCT->TransformBounds(
     138             :                         m_oWGS84Extents.MinX, m_oWGS84Extents.MinY,
     139             :                         m_oWGS84Extents.MaxX, m_oWGS84Extents.MaxY,
     140             :                         &m_oExtents.MinX, &m_oExtents.MinY, &m_oExtents.MaxX,
     141           2 :                         &m_oExtents.MaxY, 20);
     142             :                 }
     143             :             }
     144           2 :             SetSpatialFilter(nullptr);
     145           2 :             ResetReading();
     146           2 :             return OGRERR_NONE;
     147             :         }
     148           6 :         ++i;
     149             :     }
     150           1 :     return OGRERR_FAILURE;
     151             : }
     152             : 
     153             : /************************************************************************/
     154             : /*                    GetDescribeFeatureTypeURL()                       */
     155             : /************************************************************************/
     156             : 
     157         166 : CPLString OGRWFSLayer::GetDescribeFeatureTypeURL(CPL_UNUSED int bWithNS)
     158             : {
     159         166 :     CPLString osURL(pszBaseURL);
     160         166 :     osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS");
     161         166 :     osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion());
     162         166 :     osURL = CPLURLAddKVP(osURL, "REQUEST", "DescribeFeatureType");
     163         166 :     osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName));
     164         166 :     osURL = CPLURLAddKVP(osURL, "PROPERTYNAME", nullptr);
     165         166 :     osURL = CPLURLAddKVP(osURL, "MAXFEATURES", nullptr);
     166         166 :     osURL = CPLURLAddKVP(osURL, "COUNT", nullptr);
     167         166 :     osURL = CPLURLAddKVP(osURL, "FILTER", nullptr);
     168         332 :     osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT",
     169         166 :                          pszRequiredOutputFormat &&
     170           0 :                                  !EQUAL(pszRequiredOutputFormat, "json")
     171         166 :                              ? WFS_EscapeURL(pszRequiredOutputFormat).c_str()
     172         166 :                              : nullptr);
     173             : 
     174         166 :     if (pszNS && poDS->GetNeedNAMESPACE())
     175             :     {
     176             :         /* Older Deegree version require NAMESPACE (e.g.
     177             :          * http://www.nokis.org/deegree2/ogcwebservice) */
     178             :         /* This has been now corrected */
     179           0 :         CPLString osValue("xmlns(");
     180           0 :         osValue += pszNS;
     181           0 :         osValue += "=";
     182           0 :         osValue += pszNSVal;
     183           0 :         osValue += ")";
     184           0 :         osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue));
     185             :     }
     186             : 
     187         166 :     return osURL;
     188             : }
     189             : 
     190             : /************************************************************************/
     191             : /*                      DescribeFeatureType()                           */
     192             : /************************************************************************/
     193             : 
     194         104 : OGRFeatureDefn *OGRWFSLayer::DescribeFeatureType()
     195             : {
     196         208 :     CPLString osURL = GetDescribeFeatureTypeURL(TRUE);
     197             : 
     198         104 :     CPLDebug("WFS", "%s", osURL.c_str());
     199             : 
     200         104 :     CPLHTTPResult *psResult = poDS->HTTPFetch(osURL, nullptr);
     201         104 :     if (psResult == nullptr)
     202             :     {
     203          15 :         return nullptr;
     204             :     }
     205             : 
     206          89 :     if (strstr(reinterpret_cast<const char *>(psResult->pabyData),
     207             :                "<ServiceExceptionReport") != nullptr)
     208             :     {
     209           0 :         if (poDS->IsOldDeegree(
     210           0 :                 reinterpret_cast<const char *>(psResult->pabyData)))
     211             :         {
     212           0 :             CPLHTTPDestroyResult(psResult);
     213           0 :             return DescribeFeatureType();
     214             :         }
     215           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
     216             :                  psResult->pabyData);
     217           0 :         CPLHTTPDestroyResult(psResult);
     218           0 :         return nullptr;
     219             :     }
     220             : 
     221             :     CPLXMLNode *psXML =
     222          89 :         CPLParseXMLString(reinterpret_cast<const char *>(psResult->pabyData));
     223          89 :     if (psXML == nullptr)
     224             :     {
     225           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
     226             :                  psResult->pabyData);
     227           1 :         CPLHTTPDestroyResult(psResult);
     228           1 :         return nullptr;
     229             :     }
     230          88 :     CPLHTTPDestroyResult(psResult);
     231             : 
     232          88 :     const CPLXMLNode *psSchema = WFSFindNode(psXML, "schema");
     233          88 :     if (psSchema == nullptr)
     234             :     {
     235           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find <Schema>");
     236           1 :         CPLDestroyXMLNode(psXML);
     237             : 
     238           1 :         return nullptr;
     239             :     }
     240             : 
     241          87 :     OGRFeatureDefn *poFDefn = ParseSchema(psSchema);
     242          87 :     if (poFDefn)
     243          80 :         poDS->SaveLayerSchema(pszName, psSchema);
     244             : 
     245          87 :     CPLDestroyXMLNode(psXML);
     246          87 :     return poFDefn;
     247             : }
     248             : 
     249             : /************************************************************************/
     250             : /*                            ParseSchema()                             */
     251             : /************************************************************************/
     252             : 
     253         149 : OGRFeatureDefn *OGRWFSLayer::ParseSchema(const CPLXMLNode *psSchema)
     254             : {
     255         149 :     osTargetNamespace = CPLGetXMLValue(psSchema, "targetNamespace", "");
     256             : 
     257         298 :     CPLString osTmpFileName;
     258             : 
     259         149 :     osTmpFileName = CPLSPrintf("%s/file.xsd", m_osTmpDir.c_str());
     260         149 :     CPLSerializeXMLTreeToFile(psSchema, osTmpFileName);
     261             : 
     262         298 :     std::vector<GMLFeatureClass *> aosClasses;
     263         149 :     bool bFullyUnderstood = false;
     264         149 :     bool bUseSchemaImports = false;
     265         149 :     bool bHaveSchema = GMLParseXSD(osTmpFileName, bUseSchemaImports, aosClasses,
     266             :                                    bFullyUnderstood);
     267             : 
     268         149 :     if (bHaveSchema && aosClasses.size() == 1)
     269             :     {
     270             :         // CPLDebug("WFS", "Creating %s for %s", osTmpFileName.c_str(),
     271             :         // GetName());
     272         142 :         return BuildLayerDefnFromFeatureClass(aosClasses[0]);
     273             :     }
     274           7 :     else if (bHaveSchema)
     275             :     {
     276             :         std::vector<GMLFeatureClass *>::const_iterator oIter =
     277           0 :             aosClasses.begin();
     278             :         std::vector<GMLFeatureClass *>::const_iterator oEndIter =
     279           0 :             aosClasses.end();
     280           0 :         while (oIter != oEndIter)
     281             :         {
     282           0 :             GMLFeatureClass *poClass = *oIter;
     283           0 :             ++oIter;
     284           0 :             delete poClass;
     285             :         }
     286             :     }
     287             : 
     288           7 :     VSIUnlink(osTmpFileName);
     289             : 
     290           7 :     return nullptr;
     291             : }
     292             : 
     293             : /************************************************************************/
     294             : /*                   BuildLayerDefnFromFeatureClass()                   */
     295             : /************************************************************************/
     296             : 
     297             : OGRFeatureDefn *
     298         142 : OGRWFSLayer::BuildLayerDefnFromFeatureClass(GMLFeatureClass *poClass)
     299             : {
     300         142 :     poGMLFeatureClass = poClass;
     301             : 
     302         142 :     OGRFeatureDefn *poFDefn = new OGRFeatureDefn(pszName);
     303         142 :     poFDefn->SetGeomType(wkbNone);
     304         142 :     if (poGMLFeatureClass->GetGeometryPropertyCount() > 0)
     305             :     {
     306         127 :         poFDefn->SetGeomType(static_cast<OGRwkbGeometryType>(
     307         127 :             poGMLFeatureClass->GetGeometryProperty(0)->GetType()));
     308         127 :         poFDefn->GetGeomFieldDefn(0)->SetSpatialRef(m_poSRS);
     309             :     }
     310             : 
     311             :     /* -------------------------------------------------------------------- */
     312             :     /*      Added attributes (properties).                                  */
     313             :     /* -------------------------------------------------------------------- */
     314         142 :     if (poDS->ExposeGMLId())
     315             :     {
     316         278 :         OGRFieldDefn oField("gml_id", OFTString);
     317         139 :         oField.SetNullable(FALSE);
     318         139 :         poFDefn->AddFieldDefn(&oField);
     319             :     }
     320             : 
     321         710 :     for (int iField = 0; iField < poGMLFeatureClass->GetPropertyCount();
     322             :          iField++)
     323             :     {
     324         568 :         GMLPropertyDefn *poProperty = poGMLFeatureClass->GetProperty(iField);
     325         568 :         OGRFieldSubType eSubType = OFSTNone;
     326             :         const OGRFieldType eFType =
     327         568 :             GML_GetOGRFieldType(poProperty->GetType(), eSubType);
     328             : 
     329        1136 :         OGRFieldDefn oField(poProperty->GetName(), eFType);
     330         568 :         oField.SetSubType(eSubType);
     331         568 :         if (STARTS_WITH_CI(oField.GetNameRef(), "ogr:"))
     332           0 :             oField.SetName(poProperty->GetName() + 4);
     333         568 :         if (poProperty->GetWidth() > 0)
     334           0 :             oField.SetWidth(poProperty->GetWidth());
     335         568 :         if (poProperty->GetPrecision() > 0)
     336           0 :             oField.SetPrecision(poProperty->GetPrecision());
     337         568 :         if (!poDS->IsEmptyAsNull())
     338           0 :             oField.SetNullable(poProperty->IsNullable());
     339             : 
     340         568 :         poFDefn->AddFieldDefn(&oField);
     341             :     }
     342             : 
     343         142 :     if (poGMLFeatureClass->GetGeometryPropertyCount() > 0)
     344             :     {
     345             :         const char *pszGeometryColumnName =
     346         127 :             poGMLFeatureClass->GetGeometryProperty(0)->GetSrcElement();
     347         127 :         if (pszGeometryColumnName[0] != '\0')
     348             :         {
     349         127 :             osGeometryColumnName = pszGeometryColumnName;
     350         127 :             if (poFDefn->GetGeomFieldCount() > 0)
     351             :             {
     352         254 :                 poFDefn->GetGeomFieldDefn(0)->SetNullable(
     353         127 :                     poGMLFeatureClass->GetGeometryProperty(0)->IsNullable());
     354         127 :                 poFDefn->GetGeomFieldDefn(0)->SetName(pszGeometryColumnName);
     355             :             }
     356             :         }
     357             :     }
     358             : 
     359         142 :     return poFDefn;
     360             : }
     361             : 
     362             : /************************************************************************/
     363             : /*                       MakeGetFeatureURL()                            */
     364             : /************************************************************************/
     365             : 
     366         147 : CPLString OGRWFSLayer::MakeGetFeatureURL(int nRequestMaxFeatures,
     367             :                                          int bRequestHits)
     368             : {
     369         147 :     CPLString osURL(pszBaseURL);
     370         147 :     osURL = CPLURLAddKVP(osURL, "SERVICE", "WFS");
     371         147 :     osURL = CPLURLAddKVP(osURL, "VERSION", poDS->GetVersion());
     372         147 :     osURL = CPLURLAddKVP(osURL, "REQUEST", "GetFeature");
     373         147 :     if (atoi(poDS->GetVersion()) >= 2)
     374          36 :         osURL = CPLURLAddKVP(osURL, "TYPENAMES", WFS_EscapeURL(pszName));
     375             :     else
     376         111 :         osURL = CPLURLAddKVP(osURL, "TYPENAME", WFS_EscapeURL(pszName));
     377         147 :     if (!m_osSRSName.empty())
     378             :         osURL =
     379           1 :             CPLURLAddKVP(osURL, "SRSNAME", WFS_EscapeURL(m_osSRSName.c_str()));
     380         147 :     if (pszRequiredOutputFormat)
     381           0 :         osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT",
     382           0 :                              WFS_EscapeURL(pszRequiredOutputFormat));
     383             : 
     384         147 :     if (poDS->IsPagingAllowed() && !bRequestHits)
     385             :     {
     386          20 :         nRequestMaxFeatures = poDS->GetPageSize();
     387             :         /* If the feature count is known and is less than the page size, we don't
     388             :          * need to do paging. Skipping the pagination parameters improves compatibility
     389             :          * with remote datasources that don't have a primary key.
     390             :          * Without a primary key, the WFS server can't support paging, since there
     391             :          * is no natural sort order defined. */
     392          20 :         if (nFeatures < 0 ||
     393           6 :             (nRequestMaxFeatures && nFeatures > nRequestMaxFeatures))
     394             :         {
     395             :             osURL =
     396          36 :                 CPLURLAddKVP(osURL, "STARTINDEX",
     397          18 :                              CPLSPrintf("%d", nPagingStartIndex +
     398          36 :                                                   poDS->GetBaseStartIndex()));
     399          18 :             bPagingActive = true;
     400             :         }
     401             :     }
     402             : 
     403         147 :     if (nRequestMaxFeatures)
     404             :     {
     405         132 :         osURL = CPLURLAddKVP(
     406          44 :             osURL, atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES",
     407          44 :             CPLSPrintf("%d", nRequestMaxFeatures));
     408             :     }
     409         147 :     if (pszNS && poDS->GetNeedNAMESPACE())
     410             :     {
     411             :         /* Older Deegree version require NAMESPACE (e.g.
     412             :          * http://www.nokis.org/deegree2/ogcwebservice) */
     413             :         /* This has been now corrected */
     414           0 :         CPLString osValue("xmlns(");
     415           0 :         osValue += pszNS;
     416           0 :         osValue += "=";
     417           0 :         osValue += pszNSVal;
     418           0 :         osValue += ")";
     419           0 :         osURL = CPLURLAddKVP(osURL, "NAMESPACE", WFS_EscapeURL(osValue));
     420             :     }
     421             : 
     422         147 :     delete poFetchedFilterGeom;
     423         147 :     poFetchedFilterGeom = nullptr;
     424             : 
     425         294 :     CPLString osGeomFilter;
     426             : 
     427         147 :     if (m_poFilterGeom != nullptr && !osGeometryColumnName.empty())
     428             :     {
     429           6 :         OGREnvelope oEnvelope;
     430           6 :         m_poFilterGeom->getEnvelope(&oEnvelope);
     431             : 
     432           6 :         poFetchedFilterGeom = m_poFilterGeom->clone();
     433             : 
     434           6 :         osGeomFilter = "<BBOX>";
     435           6 :         if (atoi(poDS->GetVersion()) >= 2)
     436           1 :             osGeomFilter += "<ValueReference>";
     437             :         else
     438           5 :             osGeomFilter += "<PropertyName>";
     439           6 :         if (pszNS)
     440             :         {
     441           0 :             osGeomFilter += pszNS;
     442           0 :             osGeomFilter += ":";
     443             :         }
     444           6 :         osGeomFilter += osGeometryColumnName;
     445           6 :         if (atoi(poDS->GetVersion()) >= 2)
     446           1 :             osGeomFilter += "</ValueReference>";
     447             :         else
     448           5 :             osGeomFilter += "</PropertyName>";
     449             : 
     450           6 :         if (atoi(poDS->GetVersion()) >= 2)
     451             :         {
     452           1 :             osGeomFilter += "<gml:Envelope";
     453             : 
     454           2 :             CPLString osSRSName = CPLURLGetValue(pszBaseURL, "SRSNAME");
     455           1 :             if (!osSRSName.empty())
     456             :             {
     457           0 :                 osGeomFilter += " srsName=\"";
     458           0 :                 osGeomFilter += osSRSName;
     459           0 :                 osGeomFilter += "\"";
     460             :             }
     461             : 
     462           1 :             osGeomFilter += ">";
     463           1 :             if (bAxisOrderAlreadyInverted)
     464             :             {
     465             :                 osGeomFilter +=
     466             :                     CPLSPrintf("<gml:lowerCorner>%.16f "
     467             :                                "%.16f</gml:lowerCorner><gml:upperCorner>%.16f "
     468             :                                "%.16f</gml:upperCorner>",
     469             :                                oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY,
     470           1 :                                oEnvelope.MaxX);
     471             :             }
     472             :             else
     473             :                 osGeomFilter +=
     474             :                     CPLSPrintf("<gml:lowerCorner>%.16f "
     475             :                                "%.16f</gml:lowerCorner><gml:upperCorner>%.16f "
     476             :                                "%.16f</gml:upperCorner>",
     477             :                                oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX,
     478           0 :                                oEnvelope.MaxY);
     479           1 :             osGeomFilter += "</gml:Envelope>";
     480             :         }
     481           5 :         else if (poDS->RequiresEnvelopeSpatialFilter())
     482             :         {
     483           0 :             osGeomFilter += "<Envelope xmlns=\"http://www.opengis.net/gml\">";
     484           0 :             if (bAxisOrderAlreadyInverted)
     485             :             {
     486             :                 /* We can go here in WFS 1.1 with geographic coordinate systems
     487             :                  */
     488             :                 /* that are natively return in lat,long order, but as we have */
     489             :                 /* presented long,lat order to the user, we must switch back */
     490             :                 /* for the server... */
     491             :                 osGeomFilter +=
     492             :                     CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></"
     493             :                                "coord><coord><X>%.16f</X><Y>%.16f</Y></coord>",
     494             :                                oEnvelope.MinY, oEnvelope.MinX, oEnvelope.MaxY,
     495           0 :                                oEnvelope.MaxX);
     496             :             }
     497             :             else
     498             :                 osGeomFilter +=
     499             :                     CPLSPrintf("<coord><X>%.16f</X><Y>%.16f</Y></"
     500             :                                "coord><coord><X>%.16f</X><Y>%.16f</Y></coord>",
     501             :                                oEnvelope.MinX, oEnvelope.MinY, oEnvelope.MaxX,
     502           0 :                                oEnvelope.MaxY);
     503           0 :             osGeomFilter += "</Envelope>";
     504             :         }
     505             :         else
     506             :         {
     507           5 :             osGeomFilter += "<gml:Box>";
     508           5 :             osGeomFilter += "<gml:coordinates>";
     509           5 :             if (bAxisOrderAlreadyInverted)
     510             :             {
     511             :                 /* We can go here in WFS 1.1 with geographic coordinate systems
     512             :                  */
     513             :                 /* that are natively return in lat,long order, but as we have */
     514             :                 /* presented long,lat order to the user, we must switch back */
     515             :                 /* for the server... */
     516             :                 osGeomFilter +=
     517             :                     CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinY,
     518           5 :                                oEnvelope.MinX, oEnvelope.MaxY, oEnvelope.MaxX);
     519             :             }
     520             :             else
     521             :                 osGeomFilter +=
     522             :                     CPLSPrintf("%.16f,%.16f %.16f,%.16f", oEnvelope.MinX,
     523           0 :                                oEnvelope.MinY, oEnvelope.MaxX, oEnvelope.MaxY);
     524           5 :             osGeomFilter += "</gml:coordinates>";
     525           5 :             osGeomFilter += "</gml:Box>";
     526             :         }
     527           6 :         osGeomFilter += "</BBOX>";
     528             :     }
     529             : 
     530         147 :     if (!osGeomFilter.empty() || !osWFSWhere.empty())
     531             :     {
     532          34 :         CPLString osFilter;
     533          34 :         if (atoi(poDS->GetVersion()) >= 2)
     534           1 :             osFilter = "<Filter xmlns=\"http://www.opengis.net/fes/2.0\"";
     535             :         else
     536          33 :             osFilter = "<Filter xmlns=\"http://www.opengis.net/ogc\"";
     537          34 :         if (pszNS)
     538             :         {
     539           0 :             osFilter += " xmlns:";
     540           0 :             osFilter += pszNS;
     541           0 :             osFilter += "=\"";
     542           0 :             osFilter += pszNSVal;
     543           0 :             osFilter += "\"";
     544             :         }
     545          34 :         if (atoi(poDS->GetVersion()) >= 2)
     546           1 :             osFilter += " xmlns:gml=\"http://www.opengis.net/gml/3.2\">";
     547             :         else
     548          33 :             osFilter += " xmlns:gml=\"http://www.opengis.net/gml\">";
     549          34 :         if (!osGeomFilter.empty() && !osWFSWhere.empty())
     550           2 :             osFilter += "<And>";
     551          34 :         osFilter += osWFSWhere;
     552          34 :         osFilter += osGeomFilter;
     553          34 :         if (!osGeomFilter.empty() && !osWFSWhere.empty())
     554           2 :             osFilter += "</And>";
     555          34 :         osFilter += "</Filter>";
     556             : 
     557          34 :         osURL = CPLURLAddKVP(osURL, "FILTER", WFS_EscapeURL(osFilter));
     558             :     }
     559             : 
     560         147 :     if (bRequestHits)
     561             :     {
     562           9 :         osURL = CPLURLAddKVP(osURL, "RESULTTYPE", "hits");
     563             :     }
     564         138 :     else if (!aoSortColumns.empty())
     565             :     {
     566           0 :         CPLString osSortBy;
     567           0 :         for (const auto &sColumn : aoSortColumns)
     568             :         {
     569           0 :             if (!osSortBy.empty())
     570           0 :                 osSortBy += ',';
     571           0 :             osSortBy += sColumn.osColumn;
     572           0 :             if (!sColumn.bAsc)
     573             :             {
     574           0 :                 if (atoi(poDS->GetVersion()) >= 2)
     575           0 :                     osSortBy += " DESC";
     576             :                 else
     577           0 :                     osSortBy += " D";
     578             :             }
     579             :         }
     580           0 :         osURL = CPLURLAddKVP(osURL, "SORTBY", WFS_EscapeURL(osSortBy));
     581             :     }
     582             : 
     583             :     /* If no PROPERTYNAME is specified, build one if there are ignored fields */
     584         294 :     CPLString osPropertyName = CPLURLGetValue(osURL, "PROPERTYNAME");
     585         147 :     const char *pszPropertyName = osPropertyName.c_str();
     586         147 :     if (pszPropertyName[0] == 0 && poFeatureDefn != nullptr)
     587             :     {
     588         138 :         bool bHasIgnoredField = false;
     589         138 :         osPropertyName.clear();
     590         910 :         for (int iField = 0; iField < poFeatureDefn->GetFieldCount(); iField++)
     591             :         {
     592         772 :             if (EQUAL(poFeatureDefn->GetFieldDefn(iField)->GetNameRef(),
     593             :                       "gml_id"))
     594             :             {
     595             :                 /* fake field : skip it */
     596             :             }
     597         663 :             else if (poFeatureDefn->GetFieldDefn(iField)->IsIgnored())
     598             :             {
     599          24 :                 bHasIgnoredField = true;
     600             :             }
     601             :             else
     602             :             {
     603         639 :                 if (!osPropertyName.empty())
     604         534 :                     osPropertyName += ",";
     605             :                 osPropertyName +=
     606         639 :                     poFeatureDefn->GetFieldDefn(iField)->GetNameRef();
     607             :             }
     608             :         }
     609         138 :         if (!osGeometryColumnName.empty())
     610             :         {
     611         105 :             if (poFeatureDefn->IsGeometryIgnored())
     612             :             {
     613           0 :                 bHasIgnoredField = true;
     614             :             }
     615             :             else
     616             :             {
     617         105 :                 if (!osPropertyName.empty())
     618         103 :                     osPropertyName += ",";
     619         105 :                 osPropertyName += osGeometryColumnName;
     620             :             }
     621             :         }
     622             : 
     623         138 :         if (bHasIgnoredField && !osPropertyName.empty())
     624             :         {
     625           8 :             osURL = CPLURLAddKVP(osURL, "PROPERTYNAME",
     626          12 :                                  WFS_EscapeURL(osPropertyName));
     627             :         }
     628             :     }
     629             : 
     630         294 :     return osURL;
     631             : }
     632             : 
     633             : /************************************************************************/
     634             : /*               OGRWFSFetchContentDispositionFilename()                */
     635             : /************************************************************************/
     636             : 
     637          52 : static const char *OGRWFSFetchContentDispositionFilename(char **papszHeaders)
     638             : {
     639             :     const char *pszContentDisposition =
     640          52 :         CSLFetchNameValue(papszHeaders, "Content-Disposition");
     641          52 :     if (pszContentDisposition &&
     642           6 :         STARTS_WITH(pszContentDisposition, "attachment; filename="))
     643             :     {
     644           6 :         return pszContentDisposition + strlen("attachment; filename=");
     645             :     }
     646          46 :     return nullptr;
     647             : }
     648             : 
     649             : /************************************************************************/
     650             : /*                  MustRetryIfNonCompliantServer()                     */
     651             : /************************************************************************/
     652             : 
     653          64 : bool OGRWFSLayer::MustRetryIfNonCompliantServer(const char *pszServerAnswer)
     654             : {
     655          64 :     bool bRetry = false;
     656             : 
     657             :     /* Deegree server does not support PropertyIsNotEqualTo */
     658             :     /* We have to turn it into <Not><PropertyIsEqualTo> */
     659          77 :     if (!osWFSWhere.empty() && poDS->PropertyIsNotEqualToSupported() &&
     660          13 :         strstr(pszServerAnswer,
     661             :                "Unknown comparison operation: 'PropertyIsNotEqualTo'") !=
     662             :             nullptr)
     663             :     {
     664           0 :         poDS->SetPropertyIsNotEqualToUnSupported();
     665           0 :         bRetry = true;
     666             :     }
     667             : 
     668             :     /* Deegree server requires the gml: prefix in GmlObjectId element, but ESRI
     669             :      */
     670             :     /* doesn't like it at all ! Other servers don't care... */
     671          77 :     if (!osWFSWhere.empty() && !poDS->DoesGmlObjectIdNeedGMLPrefix() &&
     672          13 :         strstr(pszServerAnswer,
     673             :                "&lt;GmlObjectId&gt; requires 'gml:id'-attribute!") != nullptr)
     674             :     {
     675           0 :         poDS->SetGmlObjectIdNeedsGMLPrefix();
     676           0 :         bRetry = true;
     677             :     }
     678             : 
     679             :     /* GeoServer can return the error 'Only FeatureIds are supported when
     680             :      * encoding id filters to SDE' */
     681          77 :     if (!osWFSWhere.empty() && !bUseFeatureIdAtLayerLevel &&
     682          13 :         strstr(pszServerAnswer, "Only FeatureIds are supported") != nullptr)
     683             :     {
     684           0 :         bUseFeatureIdAtLayerLevel = true;
     685           0 :         bRetry = true;
     686             :     }
     687             : 
     688          64 :     if (bRetry)
     689             :     {
     690           0 :         SetAttributeFilter(osSQLWhere);
     691           0 :         bHasFetched = true;
     692           0 :         bReloadNeeded = false;
     693             :     }
     694             : 
     695          64 :     return bRetry;
     696             : }
     697             : 
     698             : /************************************************************************/
     699             : /*                         FetchGetFeature()                            */
     700             : /************************************************************************/
     701             : 
     702         122 : GDALDataset *OGRWFSLayer::FetchGetFeature(int nRequestMaxFeatures)
     703             : {
     704             : 
     705         244 :     CPLString osURL = MakeGetFeatureURL(nRequestMaxFeatures, FALSE);
     706         122 :     CPLDebug("WFS", "%s", osURL.c_str());
     707             : 
     708         122 :     CPLHTTPResult *psResult = nullptr;
     709             : 
     710         244 :     CPLString osOutputFormat = CPLURLGetValue(osURL, "OUTPUTFORMAT");
     711             : 
     712          84 :     const auto ReadNumberMatched = [this](const char *pszData)
     713             :     {
     714          76 :         const char *pszNumberMatched = strstr(pszData, " numberMatched=\"");
     715          76 :         if (!pszNumberMatched)
     716          69 :             pszNumberMatched = strstr(pszData, "\n"
     717             :                                                "numberMatched=\"");
     718          76 :         if (pszNumberMatched)
     719             :         {
     720          19 :             pszNumberMatched += strlen(" numberMatched=\"");
     721          19 :             if (*pszNumberMatched >= '0' && *pszNumberMatched <= '9')
     722             :             {
     723           2 :                 m_nNumberMatched = CPLAtoGIntBig(pszNumberMatched);
     724           2 :                 CPLDebug("WFS", "numberMatched = " CPL_FRMT_GIB,
     725             :                          m_nNumberMatched);
     726           2 :                 if (!bCountFeaturesInGetNextFeature)
     727           2 :                     nFeatures = m_nNumberMatched;
     728             :             }
     729             :         }
     730         198 :     };
     731             : 
     732         122 :     if (CPLTestBool(CPLGetConfigOption("OGR_WFS_USE_STREAMING", "YES")))
     733             :     {
     734          71 :         CPLString osStreamingName;
     735         139 :         if (STARTS_WITH(osURL, "/vsimem/") &&
     736          68 :             CPLTestBool(CPLGetConfigOption("CPL_CURL_ENABLE_VSIMEM", "FALSE")))
     737             :         {
     738          68 :             osStreamingName = osURL;
     739             :         }
     740             :         else
     741             :         {
     742           3 :             osStreamingName += "/vsicurl_streaming/";
     743           3 :             osStreamingName += osURL;
     744             :         }
     745             : 
     746             :         /* Try streaming when the output format is GML and that we have a .xsd
     747             :          */
     748             :         /* that we are able to understand */
     749          71 :         CPLString osXSDFileName = CPLSPrintf("%s/file.xsd", m_osTmpDir.c_str());
     750             :         VSIStatBufL sBuf;
     751          71 :         GDALDriver *poDriver = nullptr;
     752          71 :         if ((osOutputFormat.empty() ||
     753           6 :              osOutputFormat.ifind("GML") != std::string::npos) &&
     754         110 :             VSIStatL(osXSDFileName, &sBuf) == 0 &&
     755          45 :             (poDriver = GDALDriver::FromHandle(GDALGetDriverByName("GML"))) !=
     756         142 :                 nullptr &&
     757          44 :             poDriver->pfnOpen)
     758             :         {
     759          44 :             bStreamingDS = true;
     760          44 :             CPLStringList aosOptions;
     761          44 :             aosOptions.SetNameValue("XSD", osXSDFileName.c_str());
     762             :             aosOptions.SetNameValue("EMPTY_AS_NULL",
     763          44 :                                     poDS->IsEmptyAsNull() ? "YES" : "NO");
     764          44 :             if (CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG",
     765          44 :                                    nullptr) == nullptr)
     766             :             {
     767             :                 aosOptions.SetNameValue(
     768             :                     "INVERT_AXIS_ORDER_IF_LAT_LONG",
     769          44 :                     poDS->InvertAxisOrderIfLatLong() ? "YES" : "NO");
     770             :             }
     771          44 :             if (CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", nullptr) ==
     772             :                 nullptr)
     773             :             {
     774             :                 aosOptions.SetNameValue("CONSIDER_EPSG_AS_URN",
     775          44 :                                         poDS->GetConsiderEPSGAsURN().c_str());
     776             :             }
     777          44 :             if (CPLGetConfigOption("GML_EXPOSE_GML_ID", nullptr) == nullptr)
     778             :             {
     779             :                 aosOptions.SetNameValue("EXPOSE_GML_ID",
     780          44 :                                         poDS->ExposeGMLId() ? "YES" : "NO");
     781             :                 // iGMLOOIdex ++;
     782             :             }
     783             : 
     784          44 :             GDALOpenInfo oOpenInfo(osStreamingName.c_str(), GA_ReadOnly);
     785          44 :             if (oOpenInfo.nHeaderBytes && m_nNumberMatched < 0)
     786             :             {
     787          29 :                 const char *pszData =
     788             :                     reinterpret_cast<const char *>(oOpenInfo.pabyHeader);
     789          29 :                 ReadNumberMatched(pszData);
     790             :             }
     791          44 :             oOpenInfo.papszOpenOptions = aosOptions.List();
     792             : 
     793          44 :             auto poOutputDS = poDriver->Open(&oOpenInfo, true);
     794          44 :             if (poOutputDS)
     795             :             {
     796          29 :                 return poOutputDS;
     797             :             }
     798             :         }
     799             :         /* Try streaming when the output format is FlatGeobuf */
     800          27 :         else if ((osOutputFormat.empty() ||
     801           6 :                   osOutputFormat.ifind("flatgeobuf") != std::string::npos) &&
     802          35 :                  VSIStatL(osXSDFileName, &sBuf) == 0 &&
     803           2 :                  GDALGetDriverByName("FlatGeobuf") != nullptr)
     804             :         {
     805           2 :             bStreamingDS = true;
     806           2 :             const char *const apszAllowedDrivers[] = {"FlatGeobuf", nullptr};
     807             : 
     808             :             GDALDataset *poFlatGeobuf_DS =
     809           2 :                 GDALDataset::Open(osStreamingName, GDAL_OF_VECTOR,
     810             :                                   apszAllowedDrivers, nullptr, nullptr);
     811           2 :             if (poFlatGeobuf_DS)
     812             :             {
     813           1 :                 return poFlatGeobuf_DS;
     814             :             }
     815             :         }
     816             :         else
     817             :         {
     818          25 :             bStreamingDS = false;
     819             :         }
     820             : 
     821             :         {
     822             :             /* In case of failure, read directly the content to examine */
     823             :             /* it, if it is XML error content */
     824             :             char szBuffer[2048];
     825          41 :             int nRead = 0;
     826          41 :             VSILFILE *fp = VSIFOpenL(osStreamingName, "rb");
     827          41 :             if (fp)
     828             :             {
     829          15 :                 nRead = static_cast<int>(
     830          15 :                     VSIFReadL(szBuffer, 1, sizeof(szBuffer) - 1, fp));
     831          15 :                 szBuffer[nRead] = '\0';
     832          15 :                 VSIFCloseL(fp);
     833             :             }
     834             : 
     835          41 :             if (nRead != 0)
     836             :             {
     837          15 :                 if (strstr(szBuffer, "<wfs:FeatureCollection") != nullptr)
     838             :                 {
     839             :                     poDriver =
     840           8 :                         GDALDriver::FromHandle(GDALGetDriverByName("GML"));
     841           8 :                     if (poDriver == nullptr)
     842             :                     {
     843           1 :                         CPLError(
     844             :                             CE_Failure, CPLE_AppDefined,
     845             :                             "Cannot read features as GML driver is missing");
     846           2 :                         return nullptr;
     847             :                     }
     848           7 :                     else if (poDriver->pfnOpen == nullptr)
     849             :                     {
     850           0 :                         CPLError(CE_Failure, CPLE_AppDefined,
     851             :                                  "Cannot read features as GML driver has no "
     852             :                                  "read support");
     853           0 :                         return nullptr;
     854             :                     }
     855             :                 }
     856             : 
     857          14 :                 if (MustRetryIfNonCompliantServer(szBuffer))
     858           0 :                     return FetchGetFeature(nRequestMaxFeatures);
     859             : 
     860          14 :                 if (strstr(szBuffer, "<ServiceExceptionReport") != nullptr ||
     861          13 :                     strstr(szBuffer, "<ows:ExceptionReport") != nullptr)
     862             :                 {
     863           1 :                     if (poDS->IsOldDeegree(szBuffer))
     864             :                     {
     865           0 :                         return FetchGetFeature(nRequestMaxFeatures);
     866             :                     }
     867             : 
     868           1 :                     CPLError(CE_Failure, CPLE_AppDefined,
     869             :                              "Error returned by server : %s", szBuffer);
     870           1 :                     return nullptr;
     871             :                 }
     872             :             }
     873             :         }
     874             :     }
     875             : 
     876          90 :     bStreamingDS = false;
     877          90 :     psResult = poDS->HTTPFetch(osURL, nullptr);
     878          90 :     if (psResult == nullptr)
     879             :     {
     880          40 :         return nullptr;
     881             :     }
     882             : 
     883          50 :     const char *pszContentType = "";
     884          50 :     if (psResult->pszContentType)
     885           6 :         pszContentType = psResult->pszContentType;
     886             : 
     887          50 :     VSIMkdir(m_osTmpDir.c_str(), 0);
     888             : 
     889          50 :     GByte *pabyData = psResult->pabyData;
     890          50 :     int nDataLen = psResult->nDataLen;
     891          50 :     bool bIsMultiPart = false;
     892          50 :     const char *pszAttachmentFilename = nullptr;
     893             : 
     894          56 :     if (strstr(pszContentType, "multipart") &&
     895           6 :         CPLHTTPParseMultipartMime(psResult))
     896             :     {
     897           6 :         bIsMultiPart = true;
     898           6 :         VSIRmdirRecursive(m_osTmpDir.c_str());
     899           6 :         VSIMkdir(m_osTmpDir.c_str(), 0);
     900          14 :         for (int i = 0; i < psResult->nMimePartCount; i++)
     901             :         {
     902          16 :             CPLString osTmpFileName = m_osTmpDir + "/";
     903          16 :             pszAttachmentFilename = OGRWFSFetchContentDispositionFilename(
     904           8 :                 psResult->pasMimePart[i].papszHeaders);
     905             : 
     906           8 :             if (pszAttachmentFilename)
     907           6 :                 osTmpFileName += pszAttachmentFilename;
     908             :             else
     909           2 :                 osTmpFileName += CPLSPrintf("file_%d", i);
     910             : 
     911             :             GByte *pData = static_cast<GByte *>(
     912           8 :                 VSI_MALLOC_VERBOSE(psResult->pasMimePart[i].nDataLen));
     913           8 :             if (pData)
     914             :             {
     915           8 :                 memcpy(pData, psResult->pasMimePart[i].pabyData,
     916           8 :                        psResult->pasMimePart[i].nDataLen);
     917           8 :                 VSILFILE *fp = VSIFileFromMemBuffer(
     918           8 :                     osTmpFileName, pData, psResult->pasMimePart[i].nDataLen,
     919             :                     TRUE);
     920           8 :                 VSIFCloseL(fp);
     921             :             }
     922             :         }
     923             :     }
     924             :     else
     925             :         pszAttachmentFilename =
     926          44 :             OGRWFSFetchContentDispositionFilename(psResult->papszHeaders);
     927             : 
     928          50 :     bool bJSON = false;
     929          50 :     bool bCSV = false;
     930          50 :     bool bKML = false;
     931          50 :     bool bKMZ = false;
     932          50 :     bool bFlatGeobuf = false;
     933          50 :     bool bZIP = false;
     934          50 :     bool bGZIP = false;
     935             : 
     936          50 :     const char *pszOutputFormat = osOutputFormat.c_str();
     937             : 
     938         100 :     if (FindSubStringInsensitive(pszContentType, "json") ||
     939          50 :         FindSubStringInsensitive(pszOutputFormat, "json"))
     940             :     {
     941           4 :         bJSON = true;
     942             :     }
     943          92 :     else if (FindSubStringInsensitive(pszContentType, "csv") ||
     944          46 :              FindSubStringInsensitive(pszOutputFormat, "csv"))
     945             :     {
     946           0 :         bCSV = true;
     947             :     }
     948          92 :     else if (FindSubStringInsensitive(pszContentType, "kml") ||
     949          46 :              FindSubStringInsensitive(pszOutputFormat, "kml"))
     950             :     {
     951           0 :         bKML = true;
     952             :     }
     953          92 :     else if (FindSubStringInsensitive(pszContentType, "kmz") ||
     954          46 :              FindSubStringInsensitive(pszOutputFormat, "kmz"))
     955             :     {
     956           0 :         bKMZ = true;
     957             :     }
     958          92 :     else if (FindSubStringInsensitive(pszContentType, "flatgeobuf") ||
     959          46 :              FindSubStringInsensitive(pszOutputFormat, "flatgeobuf"))
     960             :     {
     961           0 :         bFlatGeobuf = true;
     962             :     }
     963          46 :     else if (strstr(pszContentType, "application/zip") != nullptr)
     964             :     {
     965           0 :         bZIP = true;
     966             :     }
     967          46 :     else if (strstr(pszContentType, "application/gzip") != nullptr)
     968             :     {
     969           0 :         bGZIP = true;
     970             :     }
     971             : 
     972          50 :     const char *pszData = reinterpret_cast<const char *>(pabyData);
     973          50 :     if (MustRetryIfNonCompliantServer(pszData))
     974             :     {
     975           0 :         CPLHTTPDestroyResult(psResult);
     976           0 :         return FetchGetFeature(nRequestMaxFeatures);
     977             :     }
     978             : 
     979          50 :     if (strstr(pszData, "<ServiceExceptionReport") != nullptr ||
     980          49 :         strstr(pszData, "<ows:ExceptionReport") != nullptr)
     981             :     {
     982           1 :         if (poDS->IsOldDeegree(pszData))
     983             :         {
     984           0 :             CPLHTTPDestroyResult(psResult);
     985           0 :             return FetchGetFeature(nRequestMaxFeatures);
     986             :         }
     987             : 
     988           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
     989             :                  pabyData);
     990           1 :         CPLHTTPDestroyResult(psResult);
     991           1 :         return nullptr;
     992             :     }
     993             : 
     994          49 :     if (m_nNumberMatched < 0)
     995          47 :         ReadNumberMatched(pszData);
     996             : 
     997          98 :     CPLString osTmpFileName;
     998             : 
     999          49 :     if (!bIsMultiPart)
    1000             :     {
    1001          43 :         if (bJSON)
    1002           4 :             osTmpFileName = m_osTmpDir + "/file.geojson";
    1003          39 :         else if (bZIP)
    1004           0 :             osTmpFileName = m_osTmpDir + "/file.zip";
    1005          39 :         else if (bCSV)
    1006           0 :             osTmpFileName = m_osTmpDir + "/file.csv";
    1007          39 :         else if (bKML)
    1008           0 :             osTmpFileName = m_osTmpDir + "/file.kml";
    1009          39 :         else if (bKMZ)
    1010           0 :             osTmpFileName = m_osTmpDir + "/file.kmz";
    1011          39 :         else if (bFlatGeobuf)
    1012           0 :             osTmpFileName = m_osTmpDir + "/file.fgb";
    1013             :         /* GML is a special case. It needs the .xsd file that has been saved */
    1014             :         /* as file.xsd, so we cannot used the attachment filename */
    1015          39 :         else if (pszAttachmentFilename &&
    1016          39 :                  !EQUAL(CPLGetExtensionSafe(pszAttachmentFilename).c_str(),
    1017             :                         "GML"))
    1018             :         {
    1019           0 :             osTmpFileName = m_osTmpDir + "/";
    1020           0 :             osTmpFileName += pszAttachmentFilename;
    1021             :         }
    1022             :         else
    1023             :         {
    1024          39 :             osTmpFileName = m_osTmpDir + "/file.gfs";
    1025          39 :             VSIUnlink(osTmpFileName);
    1026             : 
    1027          39 :             osTmpFileName = m_osTmpDir + "/file.gml";
    1028             :         }
    1029             : 
    1030             :         VSILFILE *fp =
    1031          43 :             VSIFileFromMemBuffer(osTmpFileName, pabyData, nDataLen, TRUE);
    1032          43 :         VSIFCloseL(fp);
    1033          43 :         psResult->pabyData = nullptr;
    1034             : 
    1035          43 :         if (bZIP)
    1036             :         {
    1037           0 :             osTmpFileName = "/vsizip/" + osTmpFileName;
    1038             :         }
    1039          43 :         else if (bGZIP)
    1040             :         {
    1041           0 :             osTmpFileName = "/vsigzip/" + osTmpFileName;
    1042             :         }
    1043             :     }
    1044             :     else
    1045             :     {
    1046           6 :         pabyData = nullptr;
    1047           6 :         nDataLen = 0;
    1048           6 :         osTmpFileName = m_osTmpDir;
    1049             :     }
    1050             : 
    1051          49 :     CPLHTTPDestroyResult(psResult);
    1052             : 
    1053          49 :     const char *const *papszOpenOptions = nullptr;
    1054          49 :     const char *apszGMLOpenOptions[4] = {nullptr, nullptr, nullptr, nullptr};
    1055          49 :     int iGMLOOIdex = 0;
    1056          49 :     if (CPLGetConfigOption("GML_INVERT_AXIS_ORDER_IF_LAT_LONG", nullptr) ==
    1057             :         nullptr)
    1058             :     {
    1059          49 :         apszGMLOpenOptions[iGMLOOIdex] =
    1060          49 :             CPLSPrintf("INVERT_AXIS_ORDER_IF_LAT_LONG=%s",
    1061          49 :                        poDS->InvertAxisOrderIfLatLong() ? "YES" : "NO");
    1062          49 :         iGMLOOIdex++;
    1063             :     }
    1064          49 :     if (CPLGetConfigOption("GML_CONSIDER_EPSG_AS_URN", nullptr) == nullptr)
    1065             :     {
    1066          49 :         apszGMLOpenOptions[iGMLOOIdex] = CPLSPrintf(
    1067          49 :             "CONSIDER_EPSG_AS_URN=%s", poDS->GetConsiderEPSGAsURN().c_str());
    1068          49 :         iGMLOOIdex++;
    1069             :     }
    1070          49 :     if (CPLGetConfigOption("GML_EXPOSE_GML_ID", nullptr) == nullptr)
    1071             :     {
    1072          49 :         apszGMLOpenOptions[iGMLOOIdex] =
    1073          49 :             CPLSPrintf("EXPOSE_GML_ID=%s", poDS->ExposeGMLId() ? "YES" : "NO");
    1074             :         // iGMLOOIdex ++;
    1075             :     }
    1076             : 
    1077          49 :     GDALDriverH hDrv = GDALIdentifyDriver(osTmpFileName, nullptr);
    1078          49 :     if (hDrv != nullptr && hDrv == GDALGetDriverByName("GML"))
    1079          37 :         papszOpenOptions = apszGMLOpenOptions;
    1080             : 
    1081             :     auto poPageDS = std::unique_ptr<GDALDataset>(GDALDataset::Open(
    1082          98 :         osTmpFileName, GDAL_OF_VECTOR, nullptr, papszOpenOptions, nullptr));
    1083          49 :     if (poPageDS == nullptr && (bZIP || bIsMultiPart))
    1084             :     {
    1085           4 :         char **papszFileList = VSIReadDir(osTmpFileName);
    1086           4 :         for (int i = 0; papszFileList != nullptr && papszFileList[i] != nullptr;
    1087             :              i++)
    1088             :         {
    1089             :             const CPLString osFullFilename =
    1090           4 :                 CPLFormFilenameSafe(osTmpFileName, papszFileList[i], nullptr);
    1091           4 :             hDrv = GDALIdentifyDriver(osFullFilename, nullptr);
    1092           4 :             if (hDrv != nullptr && hDrv == GDALGetDriverByName("GML"))
    1093           0 :                 papszOpenOptions = apszGMLOpenOptions;
    1094           4 :             poPageDS.reset(GDALDataset::Open(osFullFilename, GDAL_OF_VECTOR,
    1095             :                                              nullptr, papszOpenOptions,
    1096             :                                              nullptr));
    1097           4 :             if (poPageDS != nullptr)
    1098           4 :                 break;
    1099             :         }
    1100             : 
    1101           4 :         CSLDestroy(papszFileList);
    1102             :     }
    1103             : 
    1104          49 :     if (poPageDS == nullptr)
    1105             :     {
    1106           2 :         if (pabyData != nullptr && !bJSON && !bZIP &&
    1107           2 :             strstr(reinterpret_cast<const char *>(pabyData),
    1108           2 :                    "<wfs:FeatureCollection") == nullptr &&
    1109           2 :             strstr(reinterpret_cast<const char *>(pabyData),
    1110             :                    "<gml:FeatureCollection") == nullptr)
    1111             :         {
    1112           2 :             if (nDataLen > 1000)
    1113           0 :                 pabyData[1000] = 0;
    1114           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Error: cannot parse %s",
    1115             :                      pabyData);
    1116             :         }
    1117           2 :         return nullptr;
    1118             :     }
    1119             : 
    1120          47 :     OGRLayer *poLayer = poPageDS->GetLayer(0);
    1121          47 :     if (poLayer == nullptr)
    1122             :     {
    1123           0 :         return nullptr;
    1124             :     }
    1125             : 
    1126          47 :     return poPageDS.release();
    1127             : }
    1128             : 
    1129             : /************************************************************************/
    1130             : /*                            GetLayerDefn()                            */
    1131             : /************************************************************************/
    1132             : 
    1133        2047 : const OGRFeatureDefn *OGRWFSLayer::GetLayerDefn() const
    1134             : {
    1135        2047 :     if (!poFeatureDefn)
    1136             :     {
    1137         132 :         const_cast<OGRWFSLayer *>(this)->BuildLayerDefn();
    1138             :     }
    1139        2047 :     return poFeatureDefn;
    1140             : }
    1141             : 
    1142             : /************************************************************************/
    1143             : /*                          BuildLayerDefn()                            */
    1144             : /************************************************************************/
    1145             : 
    1146         132 : void OGRWFSLayer::BuildLayerDefn()
    1147             : {
    1148         132 :     CPLAssert(!poFeatureDefn);
    1149             : 
    1150         132 :     if (poDS->GetLayerCount() > 1)
    1151             :     {
    1152          53 :         poDS->LoadMultipleLayerDefn(GetName(), pszNS, pszNSVal);
    1153             :     }
    1154             : 
    1155         132 :     if (!poFeatureDefn)
    1156         104 :         BuildLayerDefn(nullptr);
    1157         132 : }
    1158             : 
    1159             : /************************************************************************/
    1160             : /*                          BuildLayerDefn()                            */
    1161             : /************************************************************************/
    1162             : 
    1163         166 : OGRFeatureDefn *OGRWFSLayer::BuildLayerDefn(OGRFeatureDefn *poSrcFDefn)
    1164             : {
    1165         166 :     bool bUnsetWidthPrecision = false;
    1166             : 
    1167         166 :     poFeatureDefn = new OGRFeatureDefn(pszName);
    1168         166 :     poFeatureDefn->GetGeomFieldDefn(0)->SetSpatialRef(m_poSRS);
    1169         166 :     poFeatureDefn->Reference();
    1170             : 
    1171         166 :     GDALDataset *l_poDS = nullptr;
    1172             : 
    1173         166 :     if (poSrcFDefn == nullptr)
    1174         104 :         poSrcFDefn = DescribeFeatureType();
    1175         166 :     if (poSrcFDefn == nullptr)
    1176             :     {
    1177          24 :         l_poDS = FetchGetFeature(1);
    1178          24 :         if (l_poDS == nullptr)
    1179             :         {
    1180          20 :             return poFeatureDefn;
    1181             :         }
    1182           4 :         OGRLayer *l_poLayer = l_poDS->GetLayer(0);
    1183           4 :         if (l_poLayer == nullptr)
    1184             :         {
    1185           0 :             return poFeatureDefn;
    1186             :         }
    1187           4 :         poSrcFDefn = l_poLayer->GetLayerDefn();
    1188           4 :         osGeometryColumnName = l_poLayer->GetGeometryColumn();
    1189           4 :         bGotApproximateLayerDefn = true;
    1190             :         /* We cannot trust width and precision based on a single feature */
    1191           4 :         bUnsetWidthPrecision = true;
    1192             :     }
    1193             : 
    1194             :     const CPLStringList aosPropertyName(CSLTokenizeString2(
    1195         146 :         CPLURLGetValue(pszBaseURL, "PROPERTYNAME"), "(,)", 0));
    1196             : 
    1197         146 :     poFeatureDefn->SetGeomType(poSrcFDefn->GetGeomType());
    1198         146 :     if (poSrcFDefn->GetGeomFieldCount() > 0)
    1199         262 :         poFeatureDefn->GetGeomFieldDefn(0)->SetName(
    1200         131 :             poSrcFDefn->GetGeomFieldDefn(0)->GetNameRef());
    1201         873 :     for (int i = 0; i < poSrcFDefn->GetFieldCount(); i++)
    1202             :     {
    1203         727 :         if (!aosPropertyName.empty())
    1204             :         {
    1205           0 :             if (aosPropertyName.FindString(
    1206           0 :                     poSrcFDefn->GetFieldDefn(i)->GetNameRef()) >= 0)
    1207           0 :                 poFeatureDefn->AddFieldDefn(poSrcFDefn->GetFieldDefn(i));
    1208             :             else
    1209           0 :                 bGotApproximateLayerDefn = true;
    1210             :         }
    1211             :         else
    1212             :         {
    1213        1454 :             OGRFieldDefn oFieldDefn(poSrcFDefn->GetFieldDefn(i));
    1214         727 :             if (bUnsetWidthPrecision)
    1215             :             {
    1216          20 :                 oFieldDefn.SetWidth(0);
    1217          20 :                 oFieldDefn.SetPrecision(0);
    1218             :             }
    1219         727 :             poFeatureDefn->AddFieldDefn(&oFieldDefn);
    1220             :         }
    1221             :     }
    1222             : 
    1223         146 :     if (l_poDS)
    1224           4 :         GDALClose(l_poDS);
    1225             :     else
    1226         142 :         delete poSrcFDefn;
    1227             : 
    1228         146 :     return poFeatureDefn;
    1229             : }
    1230             : 
    1231             : /************************************************************************/
    1232             : /*                            ResetReading()                            */
    1233             : /************************************************************************/
    1234             : 
    1235         202 : void OGRWFSLayer::ResetReading()
    1236             : 
    1237             : {
    1238         202 :     if (poFeatureDefn == nullptr)
    1239           7 :         return;
    1240         195 :     if (bPagingActive)
    1241           0 :         bReloadNeeded = true;
    1242         195 :     nPagingStartIndex = 0;
    1243         195 :     nFeatureRead = 0;
    1244         195 :     m_nNumberMatched = -1;
    1245         195 :     m_bHasReadAtLeastOneFeatureInThisPage = false;
    1246         195 :     if (bReloadNeeded)
    1247             :     {
    1248          42 :         GDALClose(poBaseDS);
    1249          42 :         poBaseDS = nullptr;
    1250          42 :         poBaseLayer = nullptr;
    1251          42 :         bHasFetched = false;
    1252          42 :         bReloadNeeded = false;
    1253             :     }
    1254         195 :     if (poBaseLayer)
    1255          52 :         poBaseLayer->ResetReading();
    1256             : }
    1257             : 
    1258             : /************************************************************************/
    1259             : /*                         SetIgnoredFields()                           */
    1260             : /************************************************************************/
    1261             : 
    1262          16 : OGRErr OGRWFSLayer::SetIgnoredFields(CSLConstList papszFields)
    1263             : {
    1264          16 :     bReloadNeeded = true;
    1265          16 :     ResetReading();
    1266          16 :     return OGRLayer::SetIgnoredFields(papszFields);
    1267             : }
    1268             : 
    1269             : /************************************************************************/
    1270             : /*                           GetNextFeature()                           */
    1271             : /************************************************************************/
    1272             : 
    1273         128 : OGRFeature *OGRWFSLayer::GetNextFeature()
    1274             : {
    1275         128 :     GetLayerDefn();
    1276             : 
    1277             :     while (true)
    1278             :     {
    1279         141 :         if (bReloadNeeded)
    1280             :         {
    1281          40 :             m_bHasReadAtLeastOneFeatureInThisPage = false;
    1282          40 :             GDALClose(poBaseDS);
    1283          40 :             poBaseDS = nullptr;
    1284          40 :             poBaseLayer = nullptr;
    1285          40 :             bHasFetched = false;
    1286          40 :             bReloadNeeded = false;
    1287             :         }
    1288         141 :         if (poBaseDS == nullptr && !bHasFetched)
    1289             :         {
    1290          98 :             bHasFetched = true;
    1291          98 :             poBaseDS = FetchGetFeature(0);
    1292          98 :             poBaseLayer = nullptr;
    1293          98 :             if (poBaseDS)
    1294             :             {
    1295          73 :                 poBaseLayer = poBaseDS->GetLayer(0);
    1296          73 :                 if (poBaseLayer == nullptr)
    1297           0 :                     return nullptr;
    1298          73 :                 poBaseLayer->ResetReading();
    1299             : 
    1300             :                 /* Check that the layer field definition is consistent with the
    1301             :                  * one */
    1302             :                 /* we got in BuildLayerDefn() */
    1303          73 :                 if (poFeatureDefn->GetFieldCount() !=
    1304          73 :                     poBaseLayer->GetLayerDefn()->GetFieldCount())
    1305           6 :                     bGotApproximateLayerDefn = true;
    1306             :                 else
    1307             :                 {
    1308         505 :                     for (int iField = 0;
    1309         505 :                          iField < poFeatureDefn->GetFieldCount(); iField++)
    1310             :                     {
    1311             :                         OGRFieldDefn *poFDefn1 =
    1312         444 :                             poFeatureDefn->GetFieldDefn(iField);
    1313             :                         OGRFieldDefn *poFDefn2 =
    1314         444 :                             poBaseLayer->GetLayerDefn()->GetFieldDefn(iField);
    1315         444 :                         if (strcmp(poFDefn1->GetNameRef(),
    1316         882 :                                    poFDefn2->GetNameRef()) != 0 ||
    1317         438 :                             poFDefn1->GetType() != poFDefn2->GetType())
    1318             :                         {
    1319           6 :                             bGotApproximateLayerDefn = true;
    1320           6 :                             break;
    1321             :                         }
    1322             :                     }
    1323             :                 }
    1324             :             }
    1325             :         }
    1326         141 :         if (poBaseDS == nullptr || poBaseLayer == nullptr)
    1327          38 :             return nullptr;
    1328             : 
    1329         103 :         OGRFeature *poSrcFeature = poBaseLayer->GetNextFeature();
    1330         103 :         if (poSrcFeature == nullptr)
    1331             :         {
    1332          24 :             if (bPagingActive && m_bHasReadAtLeastOneFeatureInThisPage &&
    1333          14 :                 (m_nNumberMatched < 0 || nFeatureRead < m_nNumberMatched))
    1334             :             {
    1335          12 :                 bReloadNeeded = true;
    1336          12 :                 nPagingStartIndex = nFeatureRead;
    1337          12 :                 continue;
    1338             :             }
    1339          12 :             return nullptr;
    1340             :         }
    1341          79 :         nFeatureRead++;
    1342          79 :         m_bHasReadAtLeastOneFeatureInThisPage = true;
    1343          79 :         if (bCountFeaturesInGetNextFeature)
    1344           2 :             nFeatures++;
    1345             : 
    1346          79 :         OGRGeometry *poGeom = poSrcFeature->GetGeometryRef();
    1347          86 :         if (m_poFilterGeom != nullptr && poGeom != nullptr &&
    1348           7 :             !FilterGeometry(poGeom))
    1349             :         {
    1350           0 :             delete poSrcFeature;
    1351           0 :             continue;
    1352             :         }
    1353             : 
    1354             :         /* Client-side attribute filtering with underlying layer defn */
    1355             :         /* identical to exposed layer defn. */
    1356          64 :         if (!bGotApproximateLayerDefn && osWFSWhere.empty() &&
    1357         143 :             m_poAttrQuery != nullptr && !m_poAttrQuery->Evaluate(poSrcFeature))
    1358             :         {
    1359           0 :             delete poSrcFeature;
    1360           0 :             continue;
    1361             :         }
    1362             : 
    1363          79 :         OGRFeature *poNewFeature = new OGRFeature(poFeatureDefn);
    1364          79 :         if (bGotApproximateLayerDefn)
    1365             :         {
    1366          15 :             poNewFeature->SetFrom(poSrcFeature);
    1367          15 :             poNewFeature->SetFID(poSrcFeature->GetFID());
    1368             : 
    1369             :             /* Client-side attribute filtering. */
    1370          17 :             if (m_poAttrQuery != nullptr && osWFSWhere.empty() &&
    1371           2 :                 !m_poAttrQuery->Evaluate(poNewFeature))
    1372             :             {
    1373           1 :                 delete poSrcFeature;
    1374           1 :                 delete poNewFeature;
    1375           1 :                 continue;
    1376             :             }
    1377             :         }
    1378             :         else
    1379             :         {
    1380          64 :             poNewFeature->SetFID(poSrcFeature->GetFID());
    1381         524 :             for (int iField = 0; iField < poFeatureDefn->GetFieldCount();
    1382             :                  iField++)
    1383             :             {
    1384         460 :                 poNewFeature->SetField(iField,
    1385         460 :                                        poSrcFeature->GetRawFieldRef(iField));
    1386             :             }
    1387          64 :             poNewFeature->SetStyleString(poSrcFeature->GetStyleString());
    1388          64 :             poNewFeature->SetGeometryDirectly(poSrcFeature->StealGeometry());
    1389             :         }
    1390          78 :         poGeom = poNewFeature->GetGeometryRef();
    1391             : 
    1392             :         /* FIXME? I don't really know what we should do with WFS 1.1.0 */
    1393             :         /* and non-GML format !!! I guess 50% WFS servers must do it wrong
    1394             :          * anyway */
    1395             :         /* GeoServer does currently axis inversion for non GML output, but */
    1396             :         /* apparently this is not correct :
    1397             :          * http://jira.codehaus.org/browse/GEOS-3657 */
    1398         120 :         if (poGeom != nullptr && bAxisOrderAlreadyInverted &&
    1399          42 :             strcmp(poBaseDS->GetDriverName(), "GML") != 0)
    1400             :         {
    1401           9 :             poGeom->swapXY();
    1402             :         }
    1403             : 
    1404          78 :         if (poGeom && m_poSRS)
    1405          44 :             poGeom->assignSpatialReference(m_poSRS);
    1406          78 :         delete poSrcFeature;
    1407          78 :         return poNewFeature;
    1408          13 :     }
    1409             : }
    1410             : 
    1411             : /************************************************************************/
    1412             : /*                         ISetSpatialFilter()                          */
    1413             : /************************************************************************/
    1414             : 
    1415          30 : OGRErr OGRWFSLayer::ISetSpatialFilter(int iGeomField, const OGRGeometry *poGeom)
    1416             : {
    1417          30 :     if (bStreamingDS)
    1418             :     {
    1419           7 :         bReloadNeeded = true;
    1420             :     }
    1421          23 :     else if (poFetchedFilterGeom == nullptr && poBaseDS != nullptr)
    1422             :     {
    1423             :         /* If there was no filter set, and that we set one */
    1424             :         /* the new result set can only be a subset of the whole */
    1425             :         /* so no need to reload from source */
    1426           5 :         bReloadNeeded = false;
    1427             :     }
    1428          18 :     else if (poFetchedFilterGeom != nullptr && poGeom != nullptr &&
    1429           2 :              poBaseDS != nullptr)
    1430             :     {
    1431           1 :         OGREnvelope oOldEnvelope, oNewEnvelope;
    1432           1 :         poFetchedFilterGeom->getEnvelope(&oOldEnvelope);
    1433           1 :         poGeom->getEnvelope(&oNewEnvelope);
    1434             :         /* Optimization : we don't need to request the server */
    1435             :         /* if the new BBOX is inside the old BBOX as we have */
    1436             :         /* already all the features */
    1437           1 :         bReloadNeeded = !oOldEnvelope.Contains(oNewEnvelope);
    1438             :     }
    1439             :     else
    1440             :     {
    1441          17 :         bReloadNeeded = true;
    1442             :     }
    1443          30 :     nFeatures = -1;
    1444          30 :     const OGRErr eErr = OGRLayer::ISetSpatialFilter(iGeomField, poGeom);
    1445          30 :     ResetReading();
    1446          30 :     return eErr;
    1447             : }
    1448             : 
    1449             : /************************************************************************/
    1450             : /*                        SetAttributeFilter()                          */
    1451             : /************************************************************************/
    1452             : 
    1453          92 : OGRErr OGRWFSLayer::SetAttributeFilter(const char *pszFilter)
    1454             : {
    1455          92 :     if (pszFilter != nullptr && pszFilter[0] == 0)
    1456           8 :         pszFilter = nullptr;
    1457             : 
    1458         184 :     CPLString osOldWFSWhere(osWFSWhere);
    1459             : 
    1460          92 :     CPLFree(m_pszAttrQueryString);
    1461          92 :     m_pszAttrQueryString = (pszFilter) ? CPLStrdup(pszFilter) : nullptr;
    1462             : 
    1463          92 :     delete m_poAttrQuery;
    1464          92 :     m_poAttrQuery = nullptr;
    1465             : 
    1466          92 :     if (pszFilter != nullptr)
    1467             :     {
    1468          60 :         m_poAttrQuery = new OGRFeatureQuery();
    1469             : 
    1470          60 :         OGRErr eErr = m_poAttrQuery->Compile(GetLayerDefn(), pszFilter, TRUE,
    1471             :                                              WFSGetCustomFuncRegistrar());
    1472          60 :         if (eErr != OGRERR_NONE)
    1473             :         {
    1474          28 :             delete m_poAttrQuery;
    1475          28 :             m_poAttrQuery = nullptr;
    1476          28 :             return eErr;
    1477             :         }
    1478             :     }
    1479             : 
    1480          64 :     if (poDS->HasMinOperators() && m_poAttrQuery != nullptr)
    1481             :     {
    1482             :         swq_expr_node *poNode =
    1483          30 :             static_cast<swq_expr_node *>(m_poAttrQuery->GetSWQExpr());
    1484          30 :         poNode->ReplaceBetweenByGEAndLERecurse();
    1485          30 :         poNode->ReplaceInByOrRecurse();
    1486             : 
    1487          30 :         int bNeedsNullCheck = FALSE;
    1488          60 :         int nVersion = (strcmp(poDS->GetVersion(), "1.0.0") == 0) ? 100
    1489          30 :                        : (atoi(poDS->GetVersion()) >= 2)          ? 200
    1490          30 :                                                                   : 110;
    1491          30 :         if (poNode->field_type != SWQ_BOOLEAN)
    1492           0 :             osWFSWhere = "";
    1493             :         else
    1494          60 :             osWFSWhere = WFS_TurnSQLFilterToOGCFilter(
    1495             :                 poNode, nullptr, GetLayerDefn(), nVersion,
    1496          30 :                 poDS->PropertyIsNotEqualToSupported(),
    1497          30 :                 poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel,
    1498          60 :                 poDS->DoesGmlObjectIdNeedGMLPrefix(), "", &bNeedsNullCheck);
    1499          30 :         if (bNeedsNullCheck && !poDS->HasNullCheck())
    1500           0 :             osWFSWhere = "";
    1501             :     }
    1502             :     else
    1503          34 :         osWFSWhere = "";
    1504             : 
    1505          64 :     if (m_poAttrQuery != nullptr && osWFSWhere.empty())
    1506             :     {
    1507           2 :         CPLDebug("WFS", "Using client-side only mode for filter \"%s\"",
    1508             :                  pszFilter);
    1509           2 :         OGRErr eErr = OGRLayer::SetAttributeFilter(pszFilter);
    1510           2 :         if (eErr != OGRERR_NONE)
    1511           0 :             return eErr;
    1512             :     }
    1513          64 :     ResetReading();
    1514             : 
    1515          64 :     osSQLWhere = (pszFilter) ? pszFilter : "";
    1516             : 
    1517          64 :     if (osWFSWhere != osOldWFSWhere)
    1518          46 :         bReloadNeeded = true;
    1519             :     else
    1520          18 :         bReloadNeeded = false;
    1521          64 :     nFeatures = -1;
    1522             : 
    1523          64 :     return OGRERR_NONE;
    1524             : }
    1525             : 
    1526             : /************************************************************************/
    1527             : /*                           TestCapability()                           */
    1528             : /************************************************************************/
    1529             : 
    1530         146 : int OGRWFSLayer::TestCapability(const char *pszCap) const
    1531             : 
    1532             : {
    1533         146 :     if (EQUAL(pszCap, OLCFastFeatureCount))
    1534             :     {
    1535           1 :         if (nFeatures >= 0)
    1536           0 :             return TRUE;
    1537             : 
    1538           1 :         return poBaseLayer != nullptr && m_poFilterGeom == nullptr &&
    1539           1 :                m_poAttrQuery == nullptr &&
    1540           2 :                poBaseLayer->TestCapability(pszCap) &&
    1541           0 :                (!poDS->IsPagingAllowed() &&
    1542           1 :                 poBaseLayer->GetFeatureCount() < poDS->GetPageSize());
    1543             :     }
    1544             : 
    1545         145 :     else if (EQUAL(pszCap, OLCFastGetExtent))
    1546             :     {
    1547           7 :         if (m_oExtents.IsInit())
    1548           0 :             return TRUE;
    1549             : 
    1550           7 :         return poBaseLayer != nullptr && poBaseLayer->TestCapability(pszCap);
    1551             :     }
    1552             : 
    1553         138 :     else if (EQUAL(pszCap, OLCStringsAsUTF8))
    1554           2 :         return poBaseLayer != nullptr && poBaseLayer->TestCapability(pszCap);
    1555             : 
    1556         136 :     else if (EQUAL(pszCap, OLCSequentialWrite) ||
    1557          98 :              EQUAL(pszCap, OLCDeleteFeature) || EQUAL(pszCap, OLCRandomWrite))
    1558             :     {
    1559          78 :         GetLayerDefn();
    1560         156 :         return poDS->SupportTransactions() && poDS->UpdateMode() &&
    1561         156 :                poFeatureDefn->GetFieldIndex("gml_id") == 0;
    1562             :     }
    1563          58 :     else if (EQUAL(pszCap, OLCTransactions))
    1564             :     {
    1565          50 :         return poDS->SupportTransactions() && poDS->UpdateMode();
    1566             :     }
    1567           8 :     else if (EQUAL(pszCap, OLCIgnoreFields))
    1568             :     {
    1569           0 :         return TRUE;
    1570             :     }
    1571             : 
    1572           8 :     return FALSE;
    1573             : }
    1574             : 
    1575             : /************************************************************************/
    1576             : /*                  ExecuteGetFeatureResultTypeHits()                   */
    1577             : /************************************************************************/
    1578             : 
    1579           9 : GIntBig OGRWFSLayer::ExecuteGetFeatureResultTypeHits()
    1580             : {
    1581           9 :     char *pabyData = nullptr;
    1582          18 :     CPLString osURL = MakeGetFeatureURL(0, TRUE);
    1583           9 :     if (pszRequiredOutputFormat)
    1584           0 :         osURL = CPLURLAddKVP(osURL, "OUTPUTFORMAT",
    1585           0 :                              WFS_EscapeURL(pszRequiredOutputFormat));
    1586           9 :     CPLDebug("WFS", "%s", osURL.c_str());
    1587             : 
    1588           9 :     CPLHTTPResult *psResult = poDS->HTTPFetch(osURL, nullptr);
    1589           9 :     if (psResult == nullptr)
    1590             :     {
    1591           1 :         return -1;
    1592             :     }
    1593             : 
    1594             :     /* http://demo.snowflakesoftware.com:8080/Obstacle_AIXM_ZIP/GOPublisherWFS
    1595             :      * returns */
    1596             :     /* zip content, including for RESULTTYPE=hits */
    1597           8 :     if (psResult->pszContentType != nullptr &&
    1598           0 :         strstr(psResult->pszContentType, "application/zip") != nullptr)
    1599             :     {
    1600             :         const CPLString osTmpFileName(
    1601           0 :             VSIMemGenerateHiddenFilename("wfstemphits.zip"));
    1602           0 :         VSILFILE *fp = VSIFileFromMemBuffer(osTmpFileName, psResult->pabyData,
    1603           0 :                                             psResult->nDataLen, FALSE);
    1604           0 :         VSIFCloseL(fp);
    1605             : 
    1606           0 :         CPLString osZipTmpFileName("/vsizip/" + osTmpFileName);
    1607             : 
    1608           0 :         char **papszDirContent = VSIReadDir(osZipTmpFileName);
    1609           0 :         if (CSLCount(papszDirContent) != 1)
    1610             :         {
    1611           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1612             :                      "Cannot parse result of RESULTTYPE=hits request : more "
    1613             :                      "than one file in zip");
    1614           0 :             CSLDestroy(papszDirContent);
    1615           0 :             CPLHTTPDestroyResult(psResult);
    1616           0 :             VSIUnlink(osTmpFileName);
    1617           0 :             return -1;
    1618             :         }
    1619             : 
    1620           0 :         CPLString osFileInZipTmpFileName = osZipTmpFileName + "/";
    1621           0 :         osFileInZipTmpFileName += papszDirContent[0];
    1622             : 
    1623           0 :         fp = VSIFOpenL(osFileInZipTmpFileName.c_str(), "rb");
    1624             :         VSIStatBufL sBuf;
    1625           0 :         if (fp == nullptr ||
    1626           0 :             VSIStatL(osFileInZipTmpFileName.c_str(), &sBuf) != 0)
    1627             :         {
    1628           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1629             :                      "Cannot parse result of RESULTTYPE=hits request : cannot "
    1630             :                      "open one file in zip");
    1631           0 :             CSLDestroy(papszDirContent);
    1632           0 :             CPLHTTPDestroyResult(psResult);
    1633           0 :             VSIUnlink(osTmpFileName);
    1634           0 :             if (fp)
    1635           0 :                 VSIFCloseL(fp);
    1636           0 :             return -1;
    1637             :         }
    1638             :         pabyData = static_cast<char *>(
    1639           0 :             CPLMalloc(static_cast<size_t>(sBuf.st_size + 1)));
    1640           0 :         pabyData[sBuf.st_size] = 0;
    1641           0 :         VSIFReadL(pabyData, 1, static_cast<size_t>(sBuf.st_size), fp);
    1642           0 :         VSIFCloseL(fp);
    1643             : 
    1644           0 :         CSLDestroy(papszDirContent);
    1645           0 :         VSIUnlink(osTmpFileName);
    1646             :     }
    1647             :     else
    1648             :     {
    1649           8 :         pabyData = reinterpret_cast<char *>(psResult->pabyData);
    1650           8 :         psResult->pabyData = nullptr;
    1651             :     }
    1652             : 
    1653           8 :     if (strstr(pabyData, "<ServiceExceptionReport") != nullptr ||
    1654           7 :         strstr(pabyData, "<ows:ExceptionReport") != nullptr)
    1655             :     {
    1656           1 :         if (poDS->IsOldDeegree(pabyData))
    1657             :         {
    1658           0 :             CPLHTTPDestroyResult(psResult);
    1659           0 :             return ExecuteGetFeatureResultTypeHits();
    1660             :         }
    1661           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
    1662             :                  pabyData);
    1663           1 :         CPLHTTPDestroyResult(psResult);
    1664           1 :         CPLFree(pabyData);
    1665           1 :         return -1;
    1666             :     }
    1667             : 
    1668           7 :     CPLXMLNode *psXML = CPLParseXMLString(pabyData);
    1669           7 :     if (psXML == nullptr)
    1670             :     {
    1671           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
    1672             :                  pabyData);
    1673           2 :         CPLHTTPDestroyResult(psResult);
    1674           2 :         CPLFree(pabyData);
    1675           2 :         return -1;
    1676             :     }
    1677             : 
    1678           5 :     CPLStripXMLNamespace(psXML, nullptr, TRUE);
    1679           5 :     CPLXMLNode *psRoot = CPLGetXMLNode(psXML, "=FeatureCollection");
    1680           5 :     if (psRoot == nullptr)
    1681             :     {
    1682           1 :         CPLError(CE_Failure, CPLE_AppDefined,
    1683             :                  "Cannot find <FeatureCollection>");
    1684           1 :         CPLDestroyXMLNode(psXML);
    1685           1 :         CPLHTTPDestroyResult(psResult);
    1686           1 :         CPLFree(pabyData);
    1687           1 :         return -1;
    1688             :     }
    1689             : 
    1690           4 :     const char *pszValue = CPLGetXMLValue(psRoot, "numberOfFeatures", nullptr);
    1691           4 :     if (pszValue == nullptr)
    1692             :         pszValue =
    1693           3 :             CPLGetXMLValue(psRoot, "numberMatched", nullptr); /* WFS 2.0.0 */
    1694           4 :     if (pszValue == nullptr)
    1695             :     {
    1696           1 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find numberOfFeatures");
    1697           1 :         CPLDestroyXMLNode(psXML);
    1698           1 :         CPLHTTPDestroyResult(psResult);
    1699           1 :         CPLFree(pabyData);
    1700             : 
    1701           1 :         poDS->DisableSupportHits();
    1702           1 :         return -1;
    1703             :     }
    1704             : 
    1705           3 :     GIntBig l_nFeatures = CPLAtoGIntBig(pszValue);
    1706             :     /* Hum,
    1707             :      * http://deegree3-testing.deegree.org:80/deegree-inspire-node/services?MAXFEATURES=10&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=ad:Address&OUTPUTFORMAT=text/xml;%20subtype=gml/3.2.1&RESULTTYPE=hits
    1708             :      */
    1709             :     /* returns more than MAXFEATURES features... So truncate to MAXFEATURES */
    1710             :     CPLString osMaxFeatures = CPLURLGetValue(
    1711           3 :         osURL, atoi(poDS->GetVersion()) >= 2 ? "COUNT" : "MAXFEATURES");
    1712           3 :     if (!osMaxFeatures.empty())
    1713             :     {
    1714           0 :         GIntBig nMaxFeatures = CPLAtoGIntBig(osMaxFeatures);
    1715           0 :         if (l_nFeatures > nMaxFeatures)
    1716             :         {
    1717           0 :             CPLDebug("WFS",
    1718             :                      "Truncating result from " CPL_FRMT_GIB " to " CPL_FRMT_GIB,
    1719             :                      l_nFeatures, nMaxFeatures);
    1720           0 :             l_nFeatures = nMaxFeatures;
    1721             :         }
    1722             :     }
    1723             : 
    1724           3 :     CPLDestroyXMLNode(psXML);
    1725           3 :     CPLHTTPDestroyResult(psResult);
    1726           3 :     CPLFree(pabyData);
    1727             : 
    1728           3 :     return l_nFeatures;
    1729             : }
    1730             : 
    1731             : /************************************************************************/
    1732             : /*              CanRunGetFeatureCountAndGetExtentTogether()             */
    1733             : /************************************************************************/
    1734             : 
    1735          16 : int OGRWFSLayer::CanRunGetFeatureCountAndGetExtentTogether()
    1736             : {
    1737             :     /* In some cases, we can evaluate the result of GetFeatureCount() */
    1738             :     /* and GetExtent() with the same data */
    1739          16 :     CPLString osRequestURL = MakeGetFeatureURL(0, FALSE);
    1740          26 :     return (!m_oExtents.IsInit() && nFeatures < 0 &&
    1741          10 :             osRequestURL.ifind("FILTER") == std::string::npos &&
    1742          10 :             osRequestURL.ifind("MAXFEATURES") == std::string::npos &&
    1743          34 :             osRequestURL.ifind("COUNT") == std::string::npos &&
    1744          40 :             !(GetLayerDefn()->IsGeometryIgnored()));
    1745             : }
    1746             : 
    1747             : /************************************************************************/
    1748             : /*                           GetFeatureCount()                          */
    1749             : /************************************************************************/
    1750             : 
    1751          14 : GIntBig OGRWFSLayer::GetFeatureCount(int bForce)
    1752             : {
    1753          14 :     if (nFeatures >= 0)
    1754           2 :         return nFeatures;
    1755             : 
    1756          12 :     if (poBaseLayer && TestCapability(OLCFastFeatureCount))
    1757           0 :         return poBaseLayer->GetFeatureCount(bForce);
    1758             : 
    1759          22 :     if ((m_poAttrQuery == nullptr || !osWFSWhere.empty()) &&
    1760          10 :         poDS->GetFeatureSupportHits())
    1761             :     {
    1762           9 :         nFeatures = ExecuteGetFeatureResultTypeHits();
    1763           9 :         if (nFeatures >= 0)
    1764           3 :             return nFeatures;
    1765             :     }
    1766             : 
    1767             :     /* If we have not yet the base layer, try to read one */
    1768             :     /* feature, and then query again OLCFastFeatureCount on the */
    1769             :     /* base layer. In case the WFS response would contain the */
    1770             :     /* number of features */
    1771          17 :     if (poBaseLayer == nullptr &&
    1772           8 :         (m_poAttrQuery == nullptr || !osWFSWhere.empty()))
    1773             :     {
    1774           7 :         ResetReading();
    1775           7 :         OGRFeature *poFeature = GetNextFeature();
    1776           7 :         delete poFeature;
    1777           7 :         ResetReading();
    1778             : 
    1779           7 :         if (nFeatures >= 0)
    1780           0 :             return nFeatures;
    1781             : 
    1782           7 :         if (poBaseLayer && TestCapability(OLCFastFeatureCount))
    1783           0 :             return poBaseLayer->GetFeatureCount(bForce);
    1784             :     }
    1785             : 
    1786             :     /* In some cases, we can evaluate the result of GetFeatureCount() */
    1787             :     /* and GetExtent() with the same data */
    1788           9 :     if (CanRunGetFeatureCountAndGetExtentTogether())
    1789             :     {
    1790           1 :         OGREnvelope sDummy;
    1791           1 :         CPL_IGNORE_RET_VAL(GetExtent(&sDummy));
    1792             :     }
    1793             : 
    1794           9 :     if (nFeatures < 0)
    1795           9 :         nFeatures = OGRLayer::GetFeatureCount(bForce);
    1796             : 
    1797           9 :     return nFeatures;
    1798             : }
    1799             : 
    1800             : /************************************************************************/
    1801             : /*                              SetExtents()                            */
    1802             : /************************************************************************/
    1803             : 
    1804         152 : void OGRWFSLayer::SetExtents(double dfMinXIn, double dfMinYIn, double dfMaxXIn,
    1805             :                              double dfMaxYIn)
    1806             : {
    1807         152 :     m_oExtents.MinX = dfMinXIn;
    1808         152 :     m_oExtents.MinY = dfMinYIn;
    1809         152 :     m_oExtents.MaxX = dfMaxXIn;
    1810         152 :     m_oExtents.MaxY = dfMaxYIn;
    1811         152 : }
    1812             : 
    1813             : /************************************************************************/
    1814             : /*                            SetWGS84Extents()                         */
    1815             : /************************************************************************/
    1816             : 
    1817         152 : void OGRWFSLayer::SetWGS84Extents(double dfMinXIn, double dfMinYIn,
    1818             :                                   double dfMaxXIn, double dfMaxYIn)
    1819             : {
    1820         152 :     m_oWGS84Extents.MinX = dfMinXIn;
    1821         152 :     m_oWGS84Extents.MinY = dfMinYIn;
    1822         152 :     m_oWGS84Extents.MaxX = dfMaxXIn;
    1823         152 :     m_oWGS84Extents.MaxY = dfMaxYIn;
    1824         152 : }
    1825             : 
    1826             : /************************************************************************/
    1827             : /*                             IGetExtent()                             */
    1828             : /************************************************************************/
    1829             : 
    1830          16 : OGRErr OGRWFSLayer::IGetExtent(int iGeomField, OGREnvelope *psExtent,
    1831             :                                bool bForce)
    1832             : {
    1833          16 :     if (m_oExtents.IsInit())
    1834             :     {
    1835           9 :         *psExtent = m_oExtents;
    1836           9 :         return OGRERR_NONE;
    1837             :     }
    1838             : 
    1839             :     /* If we have not yet the base layer, try to read one */
    1840             :     /* feature, and then query again OLCFastGetExtent on the */
    1841             :     /* base layer. In case the WFS response would contain the */
    1842             :     /* global extent */
    1843           7 :     if (poBaseLayer == nullptr)
    1844             :     {
    1845           7 :         ResetReading();
    1846           7 :         OGRFeature *poFeature = GetNextFeature();
    1847           7 :         delete poFeature;
    1848           7 :         ResetReading();
    1849             :     }
    1850             : 
    1851           7 :     if (TestCapability(OLCFastGetExtent))
    1852           0 :         return poBaseLayer->GetExtent(iGeomField, psExtent, bForce);
    1853             : 
    1854             :     /* In some cases, we can evaluate the result of GetFeatureCount() */
    1855             :     /* and GetExtent() with the same data */
    1856           7 :     if (CanRunGetFeatureCountAndGetExtentTogether())
    1857             :     {
    1858           7 :         bCountFeaturesInGetNextFeature = true;
    1859           7 :         nFeatures = 0;
    1860             :     }
    1861             : 
    1862           7 :     OGRErr eErr = OGRLayer::IGetExtent(iGeomField, psExtent, bForce);
    1863             : 
    1864           7 :     if (bCountFeaturesInGetNextFeature)
    1865             :     {
    1866           7 :         if (eErr == OGRERR_NONE)
    1867             :         {
    1868           2 :             m_oExtents = *psExtent;
    1869             :         }
    1870             :         else
    1871             :         {
    1872           5 :             nFeatures = -1;
    1873             :         }
    1874           7 :         bCountFeaturesInGetNextFeature = false;
    1875             :     }
    1876             : 
    1877           7 :     return eErr;
    1878             : }
    1879             : 
    1880             : /************************************************************************/
    1881             : /*                          GetShortName()                              */
    1882             : /************************************************************************/
    1883             : 
    1884         718 : const char *OGRWFSLayer::GetShortName()
    1885             : {
    1886         718 :     const char *pszShortName = strchr(pszName, ':');
    1887         718 :     if (pszShortName == nullptr)
    1888         622 :         pszShortName = pszName;
    1889             :     else
    1890          96 :         pszShortName++;
    1891         718 :     return pszShortName;
    1892             : }
    1893             : 
    1894             : /************************************************************************/
    1895             : /*                          GetPostHeader()                             */
    1896             : /************************************************************************/
    1897             : 
    1898          62 : CPLString OGRWFSLayer::GetPostHeader()
    1899             : {
    1900          62 :     CPLString osPost;
    1901          62 :     osPost += "<?xml version=\"1.0\"?>\n";
    1902          62 :     osPost += "<wfs:Transaction xmlns:wfs=\"http://www.opengis.net/wfs\"\n";
    1903             :     osPost += "                 "
    1904          62 :               "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
    1905          62 :     osPost += "                 service=\"WFS\" version=\"";
    1906          62 :     osPost += poDS->GetVersion();
    1907          62 :     osPost += "\"\n";
    1908          62 :     osPost += "                 xmlns:gml=\"http://www.opengis.net/gml\"\n";
    1909          62 :     osPost += "                 xmlns:ogc=\"http://www.opengis.net/ogc\"\n";
    1910             :     osPost +=
    1911             :         "                 xsi:schemaLocation=\"http://www.opengis.net/wfs "
    1912          62 :         "http://schemas.opengis.net/wfs/";
    1913          62 :     osPost += poDS->GetVersion();
    1914          62 :     osPost += "/wfs.xsd ";
    1915          62 :     osPost += osTargetNamespace;
    1916          62 :     osPost += " ";
    1917             : 
    1918             :     char *pszXMLEncoded =
    1919          62 :         CPLEscapeString(GetDescribeFeatureTypeURL(FALSE), -1, CPLES_XML);
    1920          62 :     osPost += pszXMLEncoded;
    1921          62 :     CPLFree(pszXMLEncoded);
    1922             : 
    1923          62 :     osPost += "\">\n";
    1924             : 
    1925          62 :     return osPost;
    1926             : }
    1927             : 
    1928             : /************************************************************************/
    1929             : /*                          ICreateFeature()                             */
    1930             : /************************************************************************/
    1931             : 
    1932          38 : OGRErr OGRWFSLayer::ICreateFeature(OGRFeature *poFeature)
    1933             : {
    1934          38 :     if (!TestCapability(OLCSequentialWrite))
    1935             :     {
    1936           0 :         if (!poDS->SupportTransactions())
    1937           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1938             :                      "CreateFeature() not supported: no WMS-T features "
    1939             :                      "advertized by server");
    1940           0 :         else if (!poDS->UpdateMode())
    1941           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    1942             :                      "CreateFeature() not supported: datasource opened as "
    1943             :                      "read-only");
    1944           0 :         return OGRERR_FAILURE;
    1945             :     }
    1946             : 
    1947          38 :     if (poGMLFeatureClass == nullptr)
    1948             :     {
    1949           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    1950             :                  "Cannot insert feature because we didn't manage to parse the "
    1951             :                  ".XSD schema");
    1952           0 :         return OGRERR_FAILURE;
    1953             :     }
    1954             : 
    1955          38 :     if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
    1956             :     {
    1957           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field");
    1958           0 :         return OGRERR_FAILURE;
    1959             :     }
    1960             : 
    1961          38 :     if (poFeature->IsFieldSetAndNotNull(0))
    1962             :     {
    1963           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    1964             :                  "Cannot insert a feature when gml_id field is already set");
    1965           2 :         return OGRERR_FAILURE;
    1966             :     }
    1967             : 
    1968          72 :     CPLString osPost;
    1969             : 
    1970          36 :     const char *pszShortName = GetShortName();
    1971             : 
    1972          36 :     if (!bInTransaction)
    1973             :     {
    1974          20 :         osPost += GetPostHeader();
    1975          20 :         osPost += "  <wfs:Insert>\n";
    1976             :     }
    1977          36 :     osPost += "    <feature:";
    1978          36 :     osPost += pszShortName;
    1979          36 :     osPost += " xmlns:feature=\"";
    1980          36 :     osPost += osTargetNamespace;
    1981          36 :     osPost += "\">\n";
    1982             : 
    1983         288 :     for (int i = 1; i <= poFeature->GetFieldCount(); i++)
    1984             :     {
    1985         576 :         if (poGMLFeatureClass->GetGeometryPropertyCount() == 1 &&
    1986         288 :             poGMLFeatureClass->GetGeometryProperty(0)->GetAttributeIndex() ==
    1987         288 :                 i - 1)
    1988             :         {
    1989          36 :             OGRGeometry *poGeom = poFeature->GetGeometryRef();
    1990          36 :             if (poGeom != nullptr && !osGeometryColumnName.empty())
    1991             :             {
    1992           2 :                 if (poGeom->getSpatialReference() == nullptr)
    1993           2 :                     poGeom->assignSpatialReference(m_poSRS);
    1994           2 :                 char *pszGML = nullptr;
    1995           2 :                 if (strcmp(poDS->GetVersion(), "1.1.0") == 0 ||
    1996           0 :                     atoi(poDS->GetVersion()) >= 2)
    1997             :                 {
    1998           2 :                     char **papszOptions = CSLAddString(nullptr, "FORMAT=GML3");
    1999           2 :                     pszGML = OGR_G_ExportToGMLEx(OGRGeometry::ToHandle(poGeom),
    2000             :                                                  papszOptions);
    2001           2 :                     CSLDestroy(papszOptions);
    2002             :                 }
    2003             :                 else
    2004           0 :                     pszGML = OGR_G_ExportToGML(OGRGeometry::ToHandle(poGeom));
    2005           2 :                 osPost += "      <feature:";
    2006           2 :                 osPost += osGeometryColumnName;
    2007           2 :                 osPost += ">";
    2008           2 :                 osPost += pszGML;
    2009           2 :                 osPost += "</feature:";
    2010           2 :                 osPost += osGeometryColumnName;
    2011           2 :                 osPost += ">\n";
    2012           2 :                 CPLFree(pszGML);
    2013             :             }
    2014             :         }
    2015         288 :         if (i == poFeature->GetFieldCount())
    2016          36 :             break;
    2017             : 
    2018             : #ifdef notdef
    2019             :         if (poFeature->IsFieldNull(i))
    2020             :         {
    2021             :             const OGRFieldDefn *poFDefn = poFeature->GetFieldDefnRef(i);
    2022             :             osPost += "      <feature:";
    2023             :             osPost += poFDefn->GetNameRef();
    2024             :             osPost += " xsi:nil=\"true\" />\n";
    2025             :         }
    2026             :         else
    2027             : #endif
    2028         252 :             if (poFeature->IsFieldSet(i) && !poFeature->IsFieldNull(i))
    2029             :         {
    2030           6 :             const OGRFieldDefn *poFDefn = poFeature->GetFieldDefnRef(i);
    2031           6 :             osPost += "      <feature:";
    2032           6 :             osPost += poFDefn->GetNameRef();
    2033           6 :             osPost += ">";
    2034           6 :             if (poFDefn->GetType() == OFTInteger)
    2035           2 :                 osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i));
    2036           4 :             else if (poFDefn->GetType() == OFTInteger64)
    2037             :                 osPost +=
    2038           0 :                     CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFieldAsInteger64(i));
    2039           4 :             else if (poFDefn->GetType() == OFTReal)
    2040           2 :                 osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i));
    2041             :             else
    2042             :             {
    2043           2 :                 char *pszXMLEncoded = CPLEscapeString(
    2044             :                     poFeature->GetFieldAsString(i), -1, CPLES_XML);
    2045           2 :                 osPost += pszXMLEncoded;
    2046           2 :                 CPLFree(pszXMLEncoded);
    2047             :             }
    2048           6 :             osPost += "</feature:";
    2049           6 :             osPost += poFDefn->GetNameRef();
    2050           6 :             osPost += ">\n";
    2051             :         }
    2052             :     }
    2053             : 
    2054          36 :     osPost += "    </feature:";
    2055          36 :     osPost += pszShortName;
    2056          36 :     osPost += ">\n";
    2057             : 
    2058          36 :     if (!bInTransaction)
    2059             :     {
    2060          20 :         osPost += "  </wfs:Insert>\n";
    2061          20 :         osPost += "</wfs:Transaction>\n";
    2062             :     }
    2063             :     else
    2064             :     {
    2065          16 :         osGlobalInsert += osPost;
    2066          16 :         nExpectedInserts++;
    2067          16 :         return OGRERR_NONE;
    2068             :     }
    2069             : 
    2070          20 :     CPLDebug("WFS", "Post : %s", osPost.c_str());
    2071             : 
    2072          20 :     char **papszOptions = nullptr;
    2073          20 :     papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
    2074             :     papszOptions =
    2075          20 :         CSLAddNameValue(papszOptions, "HEADERS",
    2076             :                         "Content-Type: application/xml; charset=UTF-8");
    2077             : 
    2078             :     CPLHTTPResult *psResult =
    2079          20 :         poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
    2080          20 :     CSLDestroy(papszOptions);
    2081             : 
    2082          20 :     if (psResult == nullptr)
    2083             :     {
    2084           6 :         return OGRERR_FAILURE;
    2085             :     }
    2086             : 
    2087          14 :     if (strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2088          12 :                "<ServiceExceptionReport") != nullptr ||
    2089          12 :         strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2090             :                "<ows:ExceptionReport") != nullptr)
    2091             :     {
    2092           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
    2093             :                  psResult->pabyData);
    2094           2 :         CPLHTTPDestroyResult(psResult);
    2095           2 :         return OGRERR_FAILURE;
    2096             :     }
    2097             : 
    2098          12 :     CPLDebug("WFS", "Response: %s", psResult->pabyData);
    2099             : 
    2100             :     CPLXMLNode *psXML =
    2101          12 :         CPLParseXMLString(reinterpret_cast<const char *>(psResult->pabyData));
    2102          12 :     if (psXML == nullptr)
    2103             :     {
    2104           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
    2105             :                  psResult->pabyData);
    2106           2 :         CPLHTTPDestroyResult(psResult);
    2107           2 :         return OGRERR_FAILURE;
    2108             :     }
    2109             : 
    2110          10 :     CPLStripXMLNamespace(psXML, nullptr, TRUE);
    2111          10 :     bool bUse100Schema = false;
    2112          10 :     CPLXMLNode *psRoot = CPLGetXMLNode(psXML, "=TransactionResponse");
    2113          10 :     if (psRoot == nullptr)
    2114             :     {
    2115           2 :         psRoot = CPLGetXMLNode(psXML, "=WFS_TransactionResponse");
    2116           2 :         if (psRoot)
    2117           0 :             bUse100Schema = true;
    2118             :     }
    2119             : 
    2120          10 :     if (psRoot == nullptr)
    2121             :     {
    2122           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2123             :                  "Cannot find <TransactionResponse>");
    2124           2 :         CPLDestroyXMLNode(psXML);
    2125           2 :         CPLHTTPDestroyResult(psResult);
    2126           2 :         return OGRERR_FAILURE;
    2127             :     }
    2128             : 
    2129           8 :     CPLXMLNode *psFeatureID = nullptr;
    2130             : 
    2131           8 :     if (bUse100Schema)
    2132             :     {
    2133           0 :         if (CPLGetXMLNode(psRoot, "TransactionResult.Status.FAILED"))
    2134             :         {
    2135           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Insert failed : %s",
    2136             :                      psResult->pabyData);
    2137           0 :             CPLDestroyXMLNode(psXML);
    2138           0 :             CPLHTTPDestroyResult(psResult);
    2139           0 :             return OGRERR_FAILURE;
    2140             :         }
    2141             : 
    2142           0 :         psFeatureID = CPLGetXMLNode(psRoot, "InsertResult.FeatureId");
    2143           0 :         if (psFeatureID == nullptr)
    2144             :         {
    2145           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2146             :                      "Cannot find InsertResult.FeatureId");
    2147           0 :             CPLDestroyXMLNode(psXML);
    2148           0 :             CPLHTTPDestroyResult(psResult);
    2149           0 :             return OGRERR_FAILURE;
    2150             :         }
    2151             :     }
    2152             :     else
    2153             :     {
    2154           8 :         const char *pszFeatureIdElt = atoi(poDS->GetVersion()) >= 2
    2155           8 :                                           ? "InsertResults.Feature.ResourceId"
    2156           8 :                                           : "InsertResults.Feature.FeatureId";
    2157           8 :         psFeatureID = CPLGetXMLNode(psRoot, pszFeatureIdElt);
    2158           8 :         if (psFeatureID == nullptr)
    2159             :         {
    2160           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Cannot find %s",
    2161             :                      pszFeatureIdElt);
    2162           2 :             CPLDestroyXMLNode(psXML);
    2163           2 :             CPLHTTPDestroyResult(psResult);
    2164           2 :             return OGRERR_FAILURE;
    2165             :         }
    2166             :     }
    2167             : 
    2168           6 :     const char *pszFIDAttr = atoi(poDS->GetVersion()) >= 2 ? "rid" : "fid";
    2169           6 :     const char *pszFID = CPLGetXMLValue(psFeatureID, pszFIDAttr, nullptr);
    2170           6 :     if (pszFID == nullptr)
    2171             :     {
    2172           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find %s", pszFIDAttr);
    2173           2 :         CPLDestroyXMLNode(psXML);
    2174           2 :         CPLHTTPDestroyResult(psResult);
    2175           2 :         return OGRERR_FAILURE;
    2176             :     }
    2177             : 
    2178           4 :     poFeature->SetField("gml_id", pszFID);
    2179             : 
    2180             :     /* If the returned fid is of the form layer_name.num, then use */
    2181             :     /* num as the OGR FID */
    2182           4 :     if (strncmp(pszFID, pszShortName, strlen(pszShortName)) == 0 &&
    2183           4 :         pszFID[strlen(pszShortName)] == '.')
    2184             :     {
    2185           4 :         GIntBig nFID = CPLAtoGIntBig(pszFID + strlen(pszShortName) + 1);
    2186           4 :         poFeature->SetFID(nFID);
    2187             :     }
    2188             : 
    2189           4 :     CPLDebug("WFS", "Got FID = " CPL_FRMT_GIB, poFeature->GetFID());
    2190             : 
    2191           4 :     CPLDestroyXMLNode(psXML);
    2192           4 :     CPLHTTPDestroyResult(psResult);
    2193             : 
    2194             :     /* Invalidate layer */
    2195           4 :     bReloadNeeded = true;
    2196           4 :     nFeatures = -1;
    2197           4 :     m_oExtents = OGREnvelope();
    2198             : 
    2199           4 :     return OGRERR_NONE;
    2200             : }
    2201             : 
    2202             : /************************************************************************/
    2203             : /*                             ISetFeature()                             */
    2204             : /************************************************************************/
    2205             : 
    2206          16 : OGRErr OGRWFSLayer::ISetFeature(OGRFeature *poFeature)
    2207             : {
    2208          16 :     if (!TestCapability(OLCRandomWrite))
    2209             :     {
    2210           0 :         if (!poDS->SupportTransactions())
    2211           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2212             :                      "SetFeature() not supported: no WMS-T features advertized "
    2213             :                      "by server");
    2214           0 :         else if (!poDS->UpdateMode())
    2215           0 :             CPLError(
    2216             :                 CE_Failure, CPLE_AppDefined,
    2217             :                 "SetFeature() not supported: datasource opened as read-only");
    2218           0 :         return OGRERR_FAILURE;
    2219             :     }
    2220             : 
    2221          16 :     if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
    2222             :     {
    2223           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field");
    2224           0 :         return OGRERR_FAILURE;
    2225             :     }
    2226             : 
    2227          16 :     if (poFeature->IsFieldSetAndNotNull(0) == FALSE)
    2228             :     {
    2229           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2230             :                  "Cannot update a feature when gml_id field is not set");
    2231           2 :         return OGRERR_FAILURE;
    2232             :     }
    2233             : 
    2234          14 :     if (bInTransaction)
    2235             :     {
    2236           0 :         CPLError(
    2237             :             CE_Warning, CPLE_AppDefined,
    2238             :             "SetFeature() not yet dealt in transaction. Issued immediately");
    2239             :     }
    2240             : 
    2241          14 :     const char *pszShortName = GetShortName();
    2242             : 
    2243          28 :     CPLString osPost;
    2244          14 :     osPost += GetPostHeader();
    2245             : 
    2246          14 :     osPost += "  <wfs:Update typeName=\"feature:";
    2247          14 :     osPost += pszShortName;
    2248          14 :     osPost += "\" xmlns:feature=\"";
    2249          14 :     osPost += osTargetNamespace;
    2250          14 :     osPost += "\">\n";
    2251             : 
    2252          14 :     OGRGeometry *poGeom = poFeature->GetGeometryRef();
    2253          14 :     if (!osGeometryColumnName.empty())
    2254             :     {
    2255          14 :         osPost += "    <wfs:Property>\n";
    2256          14 :         osPost += "      <wfs:Name>";
    2257          14 :         osPost += osGeometryColumnName;
    2258          14 :         osPost += "</wfs:Name>\n";
    2259          14 :         if (poGeom != nullptr)
    2260             :         {
    2261           2 :             if (poGeom->getSpatialReference() == nullptr)
    2262           2 :                 poGeom->assignSpatialReference(m_poSRS);
    2263           2 :             char *pszGML = nullptr;
    2264           2 :             if (strcmp(poDS->GetVersion(), "1.1.0") == 0 ||
    2265           0 :                 atoi(poDS->GetVersion()) >= 2)
    2266             :             {
    2267           2 :                 char **papszOptions = CSLAddString(nullptr, "FORMAT=GML3");
    2268           2 :                 pszGML = OGR_G_ExportToGMLEx(OGRGeometry::ToHandle(poGeom),
    2269             :                                              papszOptions);
    2270           2 :                 CSLDestroy(papszOptions);
    2271             :             }
    2272             :             else
    2273           0 :                 pszGML = OGR_G_ExportToGML(OGRGeometry::ToHandle(poGeom));
    2274           2 :             osPost += "      <wfs:Value>";
    2275           2 :             osPost += pszGML;
    2276           2 :             osPost += "</wfs:Value>\n";
    2277           2 :             CPLFree(pszGML);
    2278             :         }
    2279          14 :         osPost += "    </wfs:Property>\n";
    2280             :     }
    2281             : 
    2282         112 :     for (int i = 1; i < poFeature->GetFieldCount(); i++)
    2283             :     {
    2284          98 :         const OGRFieldDefn *poFDefn = poFeature->GetFieldDefnRef(i);
    2285             : 
    2286          98 :         osPost += "    <wfs:Property>\n";
    2287          98 :         osPost += "      <wfs:Name>";
    2288          98 :         osPost += poFDefn->GetNameRef();
    2289          98 :         osPost += "</wfs:Name>\n";
    2290          98 :         if (poFeature->IsFieldSetAndNotNull(i))
    2291             :         {
    2292           6 :             osPost += "      <wfs:Value>";
    2293           6 :             if (poFDefn->GetType() == OFTInteger)
    2294           2 :                 osPost += CPLSPrintf("%d", poFeature->GetFieldAsInteger(i));
    2295           4 :             else if (poFDefn->GetType() == OFTInteger64)
    2296             :                 osPost +=
    2297           0 :                     CPLSPrintf(CPL_FRMT_GIB, poFeature->GetFieldAsInteger64(i));
    2298           4 :             else if (poFDefn->GetType() == OFTReal)
    2299           2 :                 osPost += CPLSPrintf("%.16g", poFeature->GetFieldAsDouble(i));
    2300             :             else
    2301             :             {
    2302           2 :                 char *pszXMLEncoded = CPLEscapeString(
    2303             :                     poFeature->GetFieldAsString(i), -1, CPLES_XML);
    2304           2 :                 osPost += pszXMLEncoded;
    2305           2 :                 CPLFree(pszXMLEncoded);
    2306             :             }
    2307           6 :             osPost += "</wfs:Value>\n";
    2308             :         }
    2309          98 :         osPost += "    </wfs:Property>\n";
    2310             :     }
    2311          14 :     osPost += "    <ogc:Filter>\n";
    2312          14 :     if (poDS->UseFeatureId() || bUseFeatureIdAtLayerLevel)
    2313           0 :         osPost += "      <ogc:FeatureId fid=\"";
    2314          14 :     else if (atoi(poDS->GetVersion()) >= 2)
    2315           0 :         osPost += "      <ogc:ResourceId rid=\"";
    2316             :     else
    2317          14 :         osPost += "      <ogc:GmlObjectId gml:id=\"";
    2318          14 :     osPost += poFeature->GetFieldAsString(0);
    2319          14 :     osPost += "\"/>\n";
    2320          14 :     osPost += "    </ogc:Filter>\n";
    2321          14 :     osPost += "  </wfs:Update>\n";
    2322          14 :     osPost += "</wfs:Transaction>\n";
    2323             : 
    2324          14 :     CPLDebug("WFS", "Post : %s", osPost.c_str());
    2325             : 
    2326          14 :     char **papszOptions = nullptr;
    2327          14 :     papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
    2328             :     papszOptions =
    2329          14 :         CSLAddNameValue(papszOptions, "HEADERS",
    2330             :                         "Content-Type: application/xml; charset=UTF-8");
    2331             : 
    2332             :     CPLHTTPResult *psResult =
    2333          14 :         poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
    2334          14 :     CSLDestroy(papszOptions);
    2335             : 
    2336          14 :     if (psResult == nullptr)
    2337             :     {
    2338           4 :         return OGRERR_FAILURE;
    2339             :     }
    2340             : 
    2341          10 :     if (strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2342           8 :                "<ServiceExceptionReport") != nullptr ||
    2343           8 :         strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2344             :                "<ows:ExceptionReport") != nullptr)
    2345             :     {
    2346           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
    2347             :                  psResult->pabyData);
    2348           2 :         CPLHTTPDestroyResult(psResult);
    2349           2 :         return OGRERR_FAILURE;
    2350             :     }
    2351             : 
    2352           8 :     CPLDebug("WFS", "Response: %s", psResult->pabyData);
    2353             : 
    2354             :     CPLXMLNode *psXML =
    2355           8 :         CPLParseXMLString(reinterpret_cast<const char *>(psResult->pabyData));
    2356           8 :     if (psXML == nullptr)
    2357             :     {
    2358           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
    2359             :                  psResult->pabyData);
    2360           2 :         CPLHTTPDestroyResult(psResult);
    2361           2 :         return OGRERR_FAILURE;
    2362             :     }
    2363             : 
    2364           6 :     CPLStripXMLNamespace(psXML, nullptr, TRUE);
    2365           6 :     int bUse100Schema = false;
    2366           6 :     CPLXMLNode *psRoot = CPLGetXMLNode(psXML, "=TransactionResponse");
    2367           6 :     if (psRoot == nullptr)
    2368             :     {
    2369           2 :         psRoot = CPLGetXMLNode(psXML, "=WFS_TransactionResponse");
    2370           2 :         if (psRoot)
    2371           0 :             bUse100Schema = true;
    2372             :     }
    2373           6 :     if (psRoot == nullptr)
    2374             :     {
    2375           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2376             :                  "Cannot find <TransactionResponse>");
    2377           2 :         CPLDestroyXMLNode(psXML);
    2378           2 :         CPLHTTPDestroyResult(psResult);
    2379           2 :         return OGRERR_FAILURE;
    2380             :     }
    2381             : 
    2382           4 :     if (bUse100Schema)
    2383             :     {
    2384           0 :         if (CPLGetXMLNode(psRoot, "TransactionResult.Status.FAILED"))
    2385             :         {
    2386           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Update failed : %s",
    2387             :                      psResult->pabyData);
    2388           0 :             CPLDestroyXMLNode(psXML);
    2389           0 :             CPLHTTPDestroyResult(psResult);
    2390           0 :             return OGRERR_FAILURE;
    2391             :         }
    2392             :     }
    2393             : 
    2394           4 :     CPLDestroyXMLNode(psXML);
    2395           4 :     CPLHTTPDestroyResult(psResult);
    2396             : 
    2397             :     /* Invalidate layer */
    2398           4 :     bReloadNeeded = true;
    2399           4 :     nFeatures = -1;
    2400           4 :     m_oExtents = OGREnvelope();
    2401             : 
    2402           4 :     return OGRERR_NONE;
    2403             : }
    2404             : 
    2405             : /************************************************************************/
    2406             : /*                               GetFeature()                           */
    2407             : /************************************************************************/
    2408             : 
    2409          14 : OGRFeature *OGRWFSLayer::GetFeature(GIntBig nFID)
    2410             : {
    2411          14 :     GetLayerDefn();
    2412          14 :     if (poBaseLayer == nullptr && poFeatureDefn->GetFieldIndex("gml_id") == 0)
    2413             :     {
    2414             :         /* This is lovely hackish. We assume that then gml_id will be */
    2415             :         /* layer_name.number. This is actually what we can observe with */
    2416             :         /* GeoServer and TinyOWS */
    2417             :         CPLString osVal =
    2418          14 :             CPLSPrintf("gml_id = '%s." CPL_FRMT_GIB "'", GetShortName(), nFID);
    2419          14 :         CPLString osOldSQLWhere(osSQLWhere);
    2420          14 :         SetAttributeFilter(osVal);
    2421          14 :         OGRFeature *poFeature = GetNextFeature();
    2422             :         const char *pszOldFilter =
    2423          14 :             osOldSQLWhere.size() ? osOldSQLWhere.c_str() : nullptr;
    2424          14 :         SetAttributeFilter(pszOldFilter);
    2425          14 :         if (poFeature)
    2426          12 :             return poFeature;
    2427             :     }
    2428             : 
    2429           2 :     return OGRLayer::GetFeature(nFID);
    2430             : }
    2431             : 
    2432             : /************************************************************************/
    2433             : /*                         DeleteFromFilter()                           */
    2434             : /************************************************************************/
    2435             : 
    2436          12 : OGRErr OGRWFSLayer::DeleteFromFilter(const std::string &osOGCFilter)
    2437             : {
    2438          12 :     if (!TestCapability(OLCDeleteFeature))
    2439             :     {
    2440           0 :         if (!poDS->SupportTransactions())
    2441           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2442             :                      "DeleteFromFilter() not supported: no WMS-T features "
    2443             :                      "advertized by server");
    2444           0 :         else if (!poDS->UpdateMode())
    2445           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2446             :                      "DeleteFromFilter() not supported: datasource opened as "
    2447             :                      "read-only");
    2448           0 :         return OGRERR_FAILURE;
    2449             :     }
    2450             : 
    2451          12 :     if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
    2452             :     {
    2453           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field");
    2454           0 :         return OGRERR_FAILURE;
    2455             :     }
    2456          12 :     const char *pszShortName = GetShortName();
    2457             : 
    2458          24 :     CPLString osPost;
    2459          12 :     osPost += GetPostHeader();
    2460             : 
    2461          12 :     osPost += "  <wfs:Delete xmlns:feature=\"";
    2462          12 :     osPost += osTargetNamespace;
    2463          12 :     osPost += "\" typeName=\"feature:";
    2464          12 :     osPost += pszShortName;
    2465          12 :     osPost += "\">\n";
    2466          12 :     osPost += "    <ogc:Filter>\n";
    2467          12 :     osPost += osOGCFilter;
    2468          12 :     osPost += "    </ogc:Filter>\n";
    2469          12 :     osPost += "  </wfs:Delete>\n";
    2470          12 :     osPost += "</wfs:Transaction>\n";
    2471             : 
    2472          12 :     CPLDebug("WFS", "Post : %s", osPost.c_str());
    2473             : 
    2474          12 :     char **papszOptions = nullptr;
    2475          12 :     papszOptions = CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
    2476             :     papszOptions =
    2477          12 :         CSLAddNameValue(papszOptions, "HEADERS",
    2478             :                         "Content-Type: application/xml; charset=UTF-8");
    2479             : 
    2480             :     CPLHTTPResult *psResult =
    2481          12 :         poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
    2482          12 :     CSLDestroy(papszOptions);
    2483             : 
    2484          12 :     if (psResult == nullptr)
    2485             :     {
    2486           4 :         return OGRERR_FAILURE;
    2487             :     }
    2488             : 
    2489           8 :     if (strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2490           8 :                "<ServiceExceptionReport") != nullptr ||
    2491           8 :         strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2492             :                "<ows:ExceptionReport") != nullptr)
    2493             :     {
    2494           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Error returned by server : %s",
    2495             :                  psResult->pabyData);
    2496           0 :         CPLHTTPDestroyResult(psResult);
    2497           0 :         return OGRERR_FAILURE;
    2498             :     }
    2499             : 
    2500           8 :     CPLDebug("WFS", "Response: %s", psResult->pabyData);
    2501             : 
    2502             :     CPLXMLNode *psXML =
    2503           8 :         CPLParseXMLString(reinterpret_cast<const char *>(psResult->pabyData));
    2504           8 :     if (psXML == nullptr)
    2505             :     {
    2506           2 :         CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
    2507             :                  psResult->pabyData);
    2508           2 :         CPLHTTPDestroyResult(psResult);
    2509           2 :         return OGRERR_FAILURE;
    2510             :     }
    2511             : 
    2512           6 :     CPLStripXMLNamespace(psXML, nullptr, TRUE);
    2513           6 :     bool bUse100Schema = false;
    2514           6 :     CPLXMLNode *psRoot = CPLGetXMLNode(psXML, "=TransactionResponse");
    2515           6 :     if (psRoot == nullptr)
    2516             :     {
    2517           2 :         psRoot = CPLGetXMLNode(psXML, "=WFS_TransactionResponse");
    2518           2 :         if (psRoot)
    2519           0 :             bUse100Schema = true;
    2520             :     }
    2521           6 :     if (psRoot == nullptr)
    2522             :     {
    2523           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2524             :                  "Cannot find <TransactionResponse>");
    2525           2 :         CPLDestroyXMLNode(psXML);
    2526           2 :         CPLHTTPDestroyResult(psResult);
    2527           2 :         return OGRERR_FAILURE;
    2528             :     }
    2529             : 
    2530           4 :     if (bUse100Schema)
    2531             :     {
    2532           0 :         if (CPLGetXMLNode(psRoot, "TransactionResult.Status.FAILED"))
    2533             :         {
    2534           0 :             CPLError(CE_Failure, CPLE_AppDefined, "Delete failed : %s",
    2535             :                      psResult->pabyData);
    2536           0 :             CPLDestroyXMLNode(psXML);
    2537           0 :             CPLHTTPDestroyResult(psResult);
    2538           0 :             return OGRERR_FAILURE;
    2539             :         }
    2540             :     }
    2541             : 
    2542           4 :     CPLDestroyXMLNode(psXML);
    2543           4 :     CPLHTTPDestroyResult(psResult);
    2544             : 
    2545             :     /* Invalidate layer */
    2546           4 :     bReloadNeeded = true;
    2547           4 :     nFeatures = -1;
    2548           4 :     m_oExtents = OGREnvelope();
    2549             : 
    2550           4 :     return OGRERR_NONE;
    2551             : }
    2552             : 
    2553             : /************************************************************************/
    2554             : /*                            DeleteFeature()                           */
    2555             : /************************************************************************/
    2556             : 
    2557          12 : OGRErr OGRWFSLayer::DeleteFeature(GIntBig nFID)
    2558             : {
    2559          12 :     if (!TestCapability(OLCDeleteFeature))
    2560             :     {
    2561           0 :         if (!poDS->SupportTransactions())
    2562           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2563             :                      "DeleteFeature() not supported: no WMS-T features "
    2564             :                      "advertized by server");
    2565           0 :         else if (!poDS->UpdateMode())
    2566           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2567             :                      "DeleteFeature() not supported: datasource opened as "
    2568             :                      "read-only");
    2569           0 :         return OGRERR_FAILURE;
    2570             :     }
    2571             : 
    2572          12 :     if (poFeatureDefn->GetFieldIndex("gml_id") != 0)
    2573             :     {
    2574           0 :         CPLError(CE_Failure, CPLE_AppDefined, "Cannot find gml_id field");
    2575           0 :         return OGRERR_FAILURE;
    2576             :     }
    2577             : 
    2578          12 :     OGRFeature *poFeature = GetFeature(nFID);
    2579          12 :     if (poFeature == nullptr)
    2580             :     {
    2581           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2582             :                  "Cannot find feature " CPL_FRMT_GIB, nFID);
    2583           2 :         return OGRERR_FAILURE;
    2584             :     }
    2585             : 
    2586          10 :     const char *pszGMLID = poFeature->GetFieldAsString("gml_id");
    2587          10 :     if (pszGMLID == nullptr)
    2588             :     {
    2589           0 :         CPLError(CE_Failure, CPLE_AppDefined,
    2590             :                  "Cannot delete a feature with gml_id unset");
    2591           0 :         delete poFeature;
    2592           0 :         return OGRERR_FAILURE;
    2593             :     }
    2594             : 
    2595          10 :     if (bInTransaction)
    2596             :     {
    2597           0 :         CPLError(
    2598             :             CE_Warning, CPLE_AppDefined,
    2599             :             "DeleteFeature() not yet dealt in transaction. Issued immediately");
    2600             :     }
    2601             : 
    2602          20 :     CPLString osGMLID = pszGMLID;
    2603          10 :     pszGMLID = nullptr;
    2604          10 :     delete poFeature;
    2605          10 :     poFeature = nullptr;
    2606             : 
    2607          20 :     CPLString osFilter;
    2608          10 :     osFilter = "<ogc:FeatureId fid=\"";
    2609          10 :     osFilter += osGMLID;
    2610          10 :     osFilter += "\"/>\n";
    2611          10 :     return DeleteFromFilter(osFilter);
    2612             : }
    2613             : 
    2614             : /************************************************************************/
    2615             : /*                         StartTransaction()                           */
    2616             : /************************************************************************/
    2617             : 
    2618          24 : OGRErr OGRWFSLayer::StartTransaction()
    2619             : {
    2620          24 :     if (!TestCapability(OLCTransactions))
    2621             :     {
    2622           0 :         if (!poDS->SupportTransactions())
    2623           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2624             :                      "StartTransaction() not supported: no WMS-T features "
    2625             :                      "advertized by server");
    2626           0 :         else if (!poDS->UpdateMode())
    2627           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2628             :                      "StartTransaction() not supported: datasource opened as "
    2629             :                      "read-only");
    2630           0 :         return OGRERR_FAILURE;
    2631             :     }
    2632             : 
    2633          24 :     if (bInTransaction)
    2634             :     {
    2635           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2636             :                  "StartTransaction() has already been called");
    2637           2 :         return OGRERR_FAILURE;
    2638             :     }
    2639             : 
    2640          22 :     bInTransaction = true;
    2641          22 :     osGlobalInsert = "";
    2642          22 :     nExpectedInserts = 0;
    2643          22 :     aosFIDList.resize(0);
    2644             : 
    2645          22 :     return OGRERR_NONE;
    2646             : }
    2647             : 
    2648             : /************************************************************************/
    2649             : /*                        CommitTransaction()                           */
    2650             : /************************************************************************/
    2651             : 
    2652          20 : OGRErr OGRWFSLayer::CommitTransaction()
    2653             : {
    2654          20 :     if (!TestCapability(OLCTransactions))
    2655             :     {
    2656           0 :         if (!poDS->SupportTransactions())
    2657           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2658             :                      "CommitTransaction() not supported: no WMS-T features "
    2659             :                      "advertized by server");
    2660           0 :         else if (!poDS->UpdateMode())
    2661           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2662             :                      "CommitTransaction() not supported: datasource opened as "
    2663             :                      "read-only");
    2664           0 :         return OGRERR_FAILURE;
    2665             :     }
    2666             : 
    2667          20 :     if (!bInTransaction)
    2668             :     {
    2669           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2670             :                  "StartTransaction() has not yet been called");
    2671           2 :         return OGRERR_FAILURE;
    2672             :     }
    2673             : 
    2674          18 :     if (!osGlobalInsert.empty())
    2675             :     {
    2676          16 :         CPLString osPost = GetPostHeader();
    2677          16 :         osPost += "  <wfs:Insert>\n";
    2678          16 :         osPost += osGlobalInsert;
    2679          16 :         osPost += "  </wfs:Insert>\n";
    2680          16 :         osPost += "</wfs:Transaction>\n";
    2681             : 
    2682          16 :         bInTransaction = false;
    2683          16 :         osGlobalInsert = "";
    2684          16 :         int l_nExpectedInserts = nExpectedInserts;
    2685          16 :         nExpectedInserts = 0;
    2686             : 
    2687          16 :         CPLDebug("WFS", "Post : %s", osPost.c_str());
    2688             : 
    2689          16 :         char **papszOptions = nullptr;
    2690             :         papszOptions =
    2691          16 :             CSLAddNameValue(papszOptions, "POSTFIELDS", osPost.c_str());
    2692             :         papszOptions =
    2693          16 :             CSLAddNameValue(papszOptions, "HEADERS",
    2694             :                             "Content-Type: application/xml; charset=UTF-8");
    2695             : 
    2696             :         CPLHTTPResult *psResult =
    2697          16 :             poDS->HTTPFetch(poDS->GetPostTransactionURL(), papszOptions);
    2698          16 :         CSLDestroy(papszOptions);
    2699             : 
    2700          16 :         if (psResult == nullptr)
    2701             :         {
    2702           0 :             return OGRERR_FAILURE;
    2703             :         }
    2704             : 
    2705          16 :         if (strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2706          14 :                    "<ServiceExceptionReport") != nullptr ||
    2707          14 :             strstr(reinterpret_cast<const char *>(psResult->pabyData),
    2708             :                    "<ows:ExceptionReport") != nullptr)
    2709             :         {
    2710           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    2711             :                      "Error returned by server : %s", psResult->pabyData);
    2712           2 :             CPLHTTPDestroyResult(psResult);
    2713           2 :             return OGRERR_FAILURE;
    2714             :         }
    2715             : 
    2716          14 :         CPLDebug("WFS", "Response: %s", psResult->pabyData);
    2717             : 
    2718          28 :         CPLXMLNode *psXML = CPLParseXMLString(
    2719          14 :             reinterpret_cast<const char *>(psResult->pabyData));
    2720          14 :         if (psXML == nullptr)
    2721             :         {
    2722           2 :             CPLError(CE_Failure, CPLE_AppDefined, "Invalid XML content : %s",
    2723             :                      psResult->pabyData);
    2724           2 :             CPLHTTPDestroyResult(psResult);
    2725           2 :             return OGRERR_FAILURE;
    2726             :         }
    2727             : 
    2728          12 :         CPLStripXMLNamespace(psXML, nullptr, TRUE);
    2729          12 :         bool bUse100Schema = false;
    2730          12 :         CPLXMLNode *psRoot = CPLGetXMLNode(psXML, "=TransactionResponse");
    2731          12 :         if (psRoot == nullptr)
    2732             :         {
    2733           2 :             psRoot = CPLGetXMLNode(psXML, "=WFS_TransactionResponse");
    2734           2 :             if (psRoot)
    2735           0 :                 bUse100Schema = true;
    2736             :         }
    2737             : 
    2738          12 :         if (psRoot == nullptr)
    2739             :         {
    2740           2 :             CPLError(CE_Failure, CPLE_AppDefined,
    2741             :                      "Cannot find <TransactionResponse>");
    2742           2 :             CPLDestroyXMLNode(psXML);
    2743           2 :             CPLHTTPDestroyResult(psResult);
    2744           2 :             return OGRERR_FAILURE;
    2745             :         }
    2746             : 
    2747          10 :         if (bUse100Schema)
    2748             :         {
    2749           0 :             if (CPLGetXMLNode(psRoot, "TransactionResult.Status.FAILED"))
    2750             :             {
    2751           0 :                 CPLError(CE_Failure, CPLE_AppDefined, "Insert failed : %s",
    2752             :                          psResult->pabyData);
    2753           0 :                 CPLDestroyXMLNode(psXML);
    2754           0 :                 CPLHTTPDestroyResult(psResult);
    2755           0 :                 return OGRERR_FAILURE;
    2756             :             }
    2757             : 
    2758             :             /* TODO */
    2759             :         }
    2760             :         else
    2761             :         {
    2762          10 :             int nGotInserted = atoi(
    2763             :                 CPLGetXMLValue(psRoot, "TransactionSummary.totalInserted", ""));
    2764          10 :             if (nGotInserted != l_nExpectedInserts)
    2765             :             {
    2766           2 :                 CPLError(
    2767             :                     CE_Failure, CPLE_AppDefined,
    2768             :                     "Only %d features were inserted whereas %d where expected",
    2769             :                     nGotInserted, l_nExpectedInserts);
    2770           2 :                 CPLDestroyXMLNode(psXML);
    2771           2 :                 CPLHTTPDestroyResult(psResult);
    2772           2 :                 return OGRERR_FAILURE;
    2773             :             }
    2774             : 
    2775             :             CPLXMLNode *psInsertResults =
    2776           8 :                 CPLGetXMLNode(psRoot, "InsertResults");
    2777           8 :             if (psInsertResults == nullptr)
    2778             :             {
    2779           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2780             :                          "Cannot find node InsertResults");
    2781           2 :                 CPLDestroyXMLNode(psXML);
    2782           2 :                 CPLHTTPDestroyResult(psResult);
    2783           2 :                 return OGRERR_FAILURE;
    2784             :             }
    2785             : 
    2786           6 :             aosFIDList.resize(0);
    2787             : 
    2788           6 :             CPLXMLNode *psChild = psInsertResults->psChild;
    2789           8 :             while (psChild)
    2790             :             {
    2791             :                 const char *pszFID =
    2792           4 :                     CPLGetXMLValue(psChild, "FeatureId.fid", nullptr);
    2793           4 :                 if (pszFID == nullptr)
    2794             :                 {
    2795           2 :                     CPLError(CE_Failure, CPLE_AppDefined, "Cannot find fid");
    2796           2 :                     CPLDestroyXMLNode(psXML);
    2797           2 :                     CPLHTTPDestroyResult(psResult);
    2798           2 :                     return OGRERR_FAILURE;
    2799             :                 }
    2800           2 :                 aosFIDList.push_back(pszFID);
    2801             : 
    2802           2 :                 psChild = psChild->psNext;
    2803             :             }
    2804             : 
    2805           4 :             if (static_cast<int>(aosFIDList.size()) != nGotInserted)
    2806             :             {
    2807           2 :                 CPLError(CE_Failure, CPLE_AppDefined,
    2808             :                          "Inconsistent InsertResults: did not get expected FID "
    2809             :                          "count");
    2810           2 :                 CPLDestroyXMLNode(psXML);
    2811           2 :                 CPLHTTPDestroyResult(psResult);
    2812           2 :                 return OGRERR_FAILURE;
    2813             :             }
    2814             :         }
    2815             : 
    2816           2 :         CPLDestroyXMLNode(psXML);
    2817           2 :         CPLHTTPDestroyResult(psResult);
    2818             :     }
    2819             : 
    2820           4 :     bInTransaction = false;
    2821           4 :     osGlobalInsert = "";
    2822           4 :     nExpectedInserts = 0;
    2823             : 
    2824           4 :     return OGRERR_NONE;
    2825             : }
    2826             : 
    2827             : /************************************************************************/
    2828             : /*                      RollbackTransaction()                           */
    2829             : /************************************************************************/
    2830             : 
    2831           6 : OGRErr OGRWFSLayer::RollbackTransaction()
    2832             : {
    2833           6 :     if (!TestCapability(OLCTransactions))
    2834             :     {
    2835           0 :         if (!poDS->SupportTransactions())
    2836           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2837             :                      "RollbackTransaction() not supported: no WMS-T features "
    2838             :                      "advertized by server");
    2839           0 :         else if (!poDS->UpdateMode())
    2840           0 :             CPLError(CE_Failure, CPLE_AppDefined,
    2841             :                      "RollbackTransaction() not supported: datasource opened "
    2842             :                      "as read-only");
    2843           0 :         return OGRERR_FAILURE;
    2844             :     }
    2845             : 
    2846           6 :     if (!bInTransaction)
    2847             :     {
    2848           2 :         CPLError(CE_Failure, CPLE_AppDefined,
    2849             :                  "StartTransaction() has not yet been called");
    2850           2 :         return OGRERR_FAILURE;
    2851             :     }
    2852             : 
    2853           4 :     bInTransaction = false;
    2854           4 :     osGlobalInsert = "";
    2855           4 :     nExpectedInserts = 0;
    2856             : 
    2857           4 :     return OGRERR_NONE;
    2858             : }
    2859             : 
    2860             : /************************************************************************/
    2861             : /*                    SetRequiredOutputFormat()                         */
    2862             : /************************************************************************/
    2863             : 
    2864           0 : void OGRWFSLayer::SetRequiredOutputFormat(const char *pszRequiredOutputFormatIn)
    2865             : {
    2866           0 :     CPLFree(pszRequiredOutputFormat);
    2867           0 :     if (pszRequiredOutputFormatIn)
    2868             :     {
    2869           0 :         pszRequiredOutputFormat = CPLStrdup(pszRequiredOutputFormatIn);
    2870             :     }
    2871             :     else
    2872             :     {
    2873           0 :         pszRequiredOutputFormat = nullptr;
    2874             :     }
    2875           0 : }
    2876             : 
    2877             : /************************************************************************/
    2878             : /*                            SetOrderBy()                              */
    2879             : /************************************************************************/
    2880             : 
    2881           0 : void OGRWFSLayer::SetOrderBy(const std::vector<OGRWFSSortDesc> &aoSortColumnsIn)
    2882             : {
    2883           0 :     aoSortColumns = aoSortColumnsIn;
    2884           0 : }

Generated by: LCOV version 1.14