LCOV - code coverage report
Current view: top level - ogr/ogrsf_frmts/wfs - ogrwfslayer.cpp (source / functions) Hit Total Coverage
Test: gdal_filtered.info Lines: 1182 1474 80.2 %
Date: 2025-01-18 12:42:00 Functions: 37 40 92.5 %

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

Generated by: LCOV version 1.14