mapwfslayer.c 46.5 KB
Newer Older
1
/**********************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Project:  MapServer
 * Purpose:  Implementation of WFS CONNECTIONTYPE - client to WFS servers
 * Author:   Daniel Morissette, DM Solutions Group (morissette@dmsolutions.ca)
 *
 **********************************************************************
 * Copyright (c) 2002, Daniel Morissette, DM Solutions Group Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
17 18
 *
 * The above copyright notice and this permission notice shall be included in
19
 * all copies of this Software or works derived from this Software.
20
 *
21 22 23 24 25
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
26
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
27 28 29 30 31
 ****************************************************************************/

#include "mapserver.h"
#include "maperror.h"
#include "mapows.h"
32
#include "mapproject.h"
33 34 35 36 37 38 39 40

#include <time.h>
#include <assert.h>

#if defined(_WIN32) && !defined(__CYGWIN__)
#include <process.h>
#endif

41

42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

#define WFS_V_0_0_14  14
#define WFS_V_1_0_0  100


/*====================================================================
 *  Private (static) functions
 *====================================================================*/

#ifdef USE_WFS_LYR

/************************************************************************/
/*                           msBuildRequestParms                        */
/*                                                                      */
/*      Build the params object based on the metadata                   */
/*      information. This object will be used when building the Get     */
/*      and Post requsests.                                             */
/*      Note : Verify the connection string to extract some values      */
/*      for backward compatiblity. (It is though depricated).           */
/*      This will also set layer projection and compute BBOX in that    */
/*      projection.                                                     */
/*                                                                      */
/************************************************************************/
65 66
static wfsParamsObj *msBuildRequestParams(mapObj *map, layerObj *lp,
    rectObj *bbox_ret)
67
{
68 69 70 71
  wfsParamsObj *psParams = NULL;
  rectObj bbox;
  const char *pszTmp;
  int nLength, i = 0;
72
  char *pszVersion, *pszTypeName;
73

74 75
  if (!map || !lp || !bbox_ret)
    return NULL;
76

77 78
  if (lp->connection == NULL)
    return NULL;
79

80 81 82 83 84 85 86 87 88 89 90 91 92 93
  psParams = msWFSCreateParamsObj();
  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "version");
  if (pszTmp)
    psParams->pszVersion = msStrdup(pszTmp);
  else {
    pszTmp = strstr(lp->connection, "VERSION=");
    if (!pszTmp)
      pszTmp = strstr(lp->connection, "version=");
    if (pszTmp) {
      pszVersion = strchr(pszTmp, '=')+1;
      if (strncmp(pszVersion, "0.0.14", 6) == 0)
        psParams->pszVersion = msStrdup("0.0.14");
      else if (strncmp(pszVersion, "1.0.0", 5) == 0)
        psParams->pszVersion = msStrdup("1.0.0");
94
    }
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  }

  /*the service is always set to WFS : see bug 1302 */
  psParams->pszService = msStrdup("WFS");

  /*
  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "service");
  if (pszTmp)
    psParams->pszService = msStrdup(pszTmp);
  else
  {
      pszTmp = strstr(lp->connection, "SERVICE=");
      if (!pszTmp)
        pszTmp = strstr(lp->connection, "service=");
      if (pszTmp)
      {
          pszService = strchr(pszTmp, '=')+1;
          if (strncmp(pszService, "WFS", 3) == 0)
            psParams->pszService = msStrdup("WFS");
      }
  }
  */

  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "geometryname");
  if (pszTmp)
    psParams->pszGeometryName = msStrdup(pszTmp);

  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "typename");
  if (pszTmp)
    psParams->pszTypeName = msStrdup(pszTmp);
  else {
    pszTmp = strstr(lp->connection, "TYPENAME=");
    if (!pszTmp)
      pszTmp = strstr(lp->connection, "typename=");
    if (pszTmp) {
      pszTypeName = strchr(pszTmp, '=')+1;
      if (pszTypeName) {
        nLength = strlen(pszTypeName);
        if (nLength > 0) {
          for (i=0; i<nLength; i++) {
            if (pszTypeName[i] == '&')
              break;
          }

          if (i<nLength) {
            char *pszTypeNameTmp = NULL;
            pszTypeNameTmp = msStrdup(pszTypeName);
            pszTypeNameTmp[i] = '\0';
            psParams->pszTypeName = msStrdup(pszTypeNameTmp);
            free(pszTypeNameTmp);
          } else
            psParams->pszTypeName = msStrdup(pszTypeName);
147
        }
148
      }
149
    }
150 151 152 153 154 155 156 157 158 159
  }

  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "filter");
  if (pszTmp && strlen(pszTmp) > 0) {
    if (strstr(pszTmp, "<Filter>") !=NULL || strstr(pszTmp, "<ogc:Filter") != NULL)
      psParams->pszFilter = msStrdup(pszTmp);
    else {
      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "<ogc:Filter xmlns:ogc=\"http://www.opengis.net/ogc\">");
      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, (char*)pszTmp);
      psParams->pszFilter = msStringConcatenate(psParams->pszFilter, "</ogc:Filter>");
160
    }
161 162 163 164 165 166 167 168
  }

  pszTmp = msOWSLookupMetadata(&(lp->metadata), "FO", "maxfeatures");
  if (pszTmp)
    psParams->nMaxFeatures = atoi(pszTmp);

  /* Request is always GetFeature; */
  psParams->pszRequest = msStrdup("GetFeature");
169

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

  /* ------------------------------------------------------------------
   * Figure the SRS we'll use for the request.
   * - Fetch the map SRS (if it's EPSG)
   * - Check if map SRS is listed in layer wfs_srs metadata
   * - If map SRS is valid for this layer then use it
   * - Otherwise request layer in its default SRS and we'll reproject later
   * ------------------------------------------------------------------ */

  /* __TODO__ WFS servers support only one SRS... need to decide how we'll */
  /* handle this and document it well. */
  /* It's likely that we'll simply reproject the BBOX to teh layer's projection. */

  /* ------------------------------------------------------------------
   * Set layer SRS and reproject map extents to the layer's SRS
   * ------------------------------------------------------------------ */
186
#ifdef __TODO__
187 188 189 190 191 192 193 194
  /* No need to set lp->proj if it's already set to the right EPSG code */
  if ((pszTmp = msGetEPSGProj(&(lp->projection), NULL, MS_TRUE)) == NULL ||
      strcasecmp(pszEPSG, pszTmp) != 0) {
    char szProj[20];
    snprintf(szProj, sizeof(szProj), "init=epsg:%s", pszEPSG+5);
    if (msLoadProjectionString(&(lp->projection), szProj) != 0)
      return NULL;
  }
195 196
#endif

197 198 199 200
  bbox = map->extent;
  if (msProjectionsDiffer(&(map->projection), &(lp->projection))) {
    msProjectRect(&(map->projection), &(lp->projection), &bbox);
  }
201

202 203
  if (bbox_ret != NULL)
    *bbox_ret = bbox;
204

205
  return psParams;
206 207 208 209 210 211

}

/**********************************************************************
 *                          msBuildWFSLayerPostRequest()
 *
212
 * Build a WFS GetFeature xml document for a Post Request.
213
 *
214
 * Returns a reference to a newly allocated string that should be freed
215 216
 * by the caller.
 **********************************************************************/
217 218
static char *msBuildWFSLayerPostRequest(mapObj *map, layerObj *lp,
                                        rectObj *bbox, wfsParamsObj *psParams)
219
{
220 221 222 223 224 225 226 227 228 229 230
  char *pszPostReq = NULL;
  char *pszFilter = NULL;
  char *pszGeometryName = "Geometry";
  size_t bufferSize = 0;

  if (psParams->pszVersion == NULL ||
      (strncmp(psParams->pszVersion, "0.0.14", 6) != 0 &&
       strncmp(psParams->pszVersion, "1.0.0", 5)) != 0) {
    msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerPostRequest()");
    return NULL;
  }
231

232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288


  if (psParams->pszTypeName == NULL) {
    msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerPostRequest()");
    return NULL;
  }


  if (psParams->pszGeometryName) {
    pszGeometryName = psParams->pszGeometryName;
  }

  if (psParams->pszFilter)
    pszFilter = psParams->pszFilter;
  else {
    bufferSize = 500;
    pszFilter = (char *)msSmallMalloc(bufferSize);
    snprintf(pszFilter, bufferSize, "<ogc:Filter>\n"
             "<ogc:BBOX>\n"
             "<ogc:PropertyName>%s</ogc:PropertyName>\n"
             "<gml:Box>\n"
             "<gml:coordinates>%f,%f %f,%f</gml:coordinates>\n"
             "</gml:Box>\n"
             "</ogc:BBOX>\n"
             "</ogc:Filter>", pszGeometryName, bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
  }

  bufferSize = strlen(pszFilter)+500;
  pszPostReq = (char *)msSmallMalloc(bufferSize);
  if (psParams->nMaxFeatures > 0)
    snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
             "<wfs:GetFeature\n"
             "service=\"WFS\"\n"
             "version=\"1.0.0\"\n"
             "maxFeatures=\"%d\"\n"
             "outputFormat=\"GML2\"\n"
			 "xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ogc=\"http://www.opengis.net/ogc\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:gml=\"http://www.opengis.net/gml\">\n"
             "<wfs:Query typeName=\"%s\">\n"
             "%s"
             "</wfs:Query>\n"
             "</wfs:GetFeature>\n", psParams->nMaxFeatures, psParams->pszTypeName, pszFilter);
  else
    snprintf(pszPostReq, bufferSize, "<?xml version=\"1.0\" ?>\n"
             "<wfs:GetFeature\n"
             "service=\"WFS\"\n"
             "version=\"1.0.0\"\n"
             "outputFormat=\"GML2\"\n"
             "xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:ogc=\"http://www.opengis.net/ogc\" xsi:schemaLocation=\"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:gml=\"http://www.opengis.net/gml\">\n"
             "<wfs:Query typeName=\"%s\">\n"
             "%s"
             "</wfs:Query>\n"
             "</wfs:GetFeature>\n", psParams->pszTypeName, pszFilter);
  if (psParams->pszFilter == NULL)
    free(pszFilter);


  return pszPostReq;
289 290 291 292 293
}

/**********************************************************************
 *                          msBuildWFSLayerGetURL()
 *
294
 * Build a WFS GetFeature URL for a Get Request.
295
 *
296
 * Returns a reference to a newly allocated string that should be freed
297 298 299
 * by the caller.
 **********************************************************************/
static char *msBuildWFSLayerGetURL(mapObj *map, layerObj *lp, rectObj *bbox,
300
                                   wfsParamsObj *psParams)
301
{
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
  char *pszURL = NULL, *pszOnlineResource=NULL;
  const char *pszTmp;
  char *pszVersion, *pszService, *pszTypename = NULL;
  int bVersionInConnection = 0, bServiceInConnection = 0;
  int bTypenameInConnection = 0;
  size_t bufferSize = 0;

  if (lp->connectiontype != MS_WFS || lp->connection == NULL) {
    msSetError(MS_WFSCONNERR, "Call supported only for CONNECTIONTYPE WFS",
               "msBuildWFSLayerGetURL()");
    return NULL;
  }

  /* -------------------------------------------------------------------- */
  /*      Find out request version. Look first for the wfs_version        */
  /*      metedata. If not available try to find out if the CONNECTION    */
  /*      string contains the version. This last test is done for         */
  /*      backward compatiblity but is depericated.                       */
  /* -------------------------------------------------------------------- */
  pszVersion = psParams->pszVersion;
  if (!pszVersion) {
    if ((pszTmp = strstr(lp->connection, "VERSION=")) == NULL &&
        (pszTmp = strstr(lp->connection, "version=")) == NULL ) {
      msSetError(MS_WFSCONNERR, "Metadata wfs_version must be set in the layer", "msBuildWFSLayerGetURL()");
      return NULL;
327
    }
328 329 330
    pszVersion = strchr(pszTmp, '=')+1;
    bVersionInConnection = 1;
  }
331 332


333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
  if (strncmp(pszVersion, "0.0.14", 6) != 0 &&
      strncmp(pszVersion, "1.0.0", 5) != 0 &&
      strncmp(pszVersion, "1.1", 3) != 0) {
    msSetError(MS_WFSCONNERR, "MapServer supports only WFS 1.0.0 or 0.0.14 (please verify the version metadata wfs_version).", "msBuildWFSLayerGetURL()");
    return NULL;
  }

  /* -------------------------------------------------------------------- */
  /*      Find out the service. It is always set to WFS in function       */
  /*      msBuildRequestParms  (check Bug 1302 for details).              */
  /* -------------------------------------------------------------------- */
  pszService = psParams->pszService;


  /* -------------------------------------------------------------------- */
  /*      Find out the typename. Look first for the wfs_tyename           */
  /*      metadata. If not available try to find out if the CONNECTION    */
  /*      string contains it. This last test is done for                  */
  /*      backward compatiblity but is depericated.                       */
  /* -------------------------------------------------------------------- */
  pszTypename = psParams->pszTypeName;
  if (!pszTypename) {
    if ((pszTmp = strstr(lp->connection, "TYPENAME=")) == NULL &&
        (pszTmp = strstr(lp->connection, "typename=")) == NULL ) {
      msSetError(MS_WFSCONNERR, "Metadata wfs_typename must be set in the layer", "msBuildWFSLayerGetURL()");
      return NULL;
359
    }
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
    bTypenameInConnection = 1;
  }


  /* --------------------------------------------------------------------
   * Build the request URL.
   * At this point we set only the following parameters for GetFeature:
   *   REQUEST
   *   BBOX
   *   VERSION
   *   SERVICE
   *   TYPENAME
   *   FILTER
   *   MAXFEATURES
   *
   * For backward compatiblity the user could also have in the connection
   * string the following parameters (but it is depricated):
   *   VERSION
   *   SERVICE
   *   TYPENAME
   * -------------------------------------------------------------------- */
  /* Make sure we have a big enough buffer for the URL */
  bufferSize = strlen(lp->connection)+1024;
  pszURL = (char *)malloc(bufferSize);
  MS_CHECK_ALLOC(pszURL, bufferSize, NULL);

  /* __TODO__ We have to urlencode each value... especially the BBOX values */
  /* because if they end up in exponent format (123e+06) the + will be seen */
  /* as a space by the remote server. */

  /* -------------------------------------------------------------------- */
  /*      build the URL,                                                  */
  /* -------------------------------------------------------------------- */
  /* make sure connection ends with "&" or "?" */
  pszOnlineResource = msOWSTerminateOnlineResource(lp->connection);
  snprintf(pszURL, bufferSize, "%s", pszOnlineResource);
  msFree(pszOnlineResource);

  /* REQUEST */
  snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&REQUEST=GetFeature");

  /* VERSION */
  if (!bVersionInConnection)
    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&VERSION=%s", pszVersion);

  /* SERVICE */
  if (!bServiceInConnection)
    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&SERVICE=%s", pszService);

  /* TYPENAME */
  if (!bTypenameInConnection)
    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),  "&TYPENAME=%s", pszTypename);

  /* -------------------------------------------------------------------- */
  /*      If the filter parameter is given in the wfs_filter metadata,    */
  /*      we use it and do not send the BBOX paramter as they are         */
  /*      mutually exclusive.                                             */
  /* -------------------------------------------------------------------- */
  if (psParams->pszFilter) {
419 420 421
    char *encoded_filter = msEncodeUrl(psParams->pszFilter);
    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL), "&FILTER=%s",encoded_filter);
    free(encoded_filter);
422 423 424 425 426
  } else {
	  /*
	   * take care about the axis order for WFS 1.1
	   */
	  char *projUrn;
427
	  char *projEpsg;
428
	  projUrn = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", 1);
429
	  msOWSGetEPSGProj(&(lp->projection), &(lp->metadata), "FO", 1, &projEpsg);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

	  /*
	   * WFS 1.1 supports including the SRS in the BBOX parameter, should
	   * respect axis order in the BBOX and has a separate SRSNAME parameter for
	   * the desired result SRS.
	   * WFS 1.0 is always easting, northing, doesn't include the SRS as part of
	   * the BBOX parameter and has no SRSNAME parameter: if we don't have a
	   * URN then fallback to WFS 1.0 style */
	  if ((strncmp(pszVersion, "1.1", 3) == 0) && projUrn) {
		 if (projEpsg && (strncmp(projEpsg, "EPSG:", 5) == 0) &&
				 msIsAxisInverted(atoi(projEpsg + 5))) {
			 snprintf(pszURL + strlen(pszURL), bufferSize - strlen(pszURL),
					 "&BBOX=%.15g,%.15g,%.15g,%.15g,%s&SRSNAME=%s",
					 bbox->miny, bbox->minx, bbox->maxy, bbox->maxx,
					 projUrn, projUrn);
		 } else {
			 snprintf(pszURL + strlen(pszURL), bufferSize - strlen(pszURL),
					 "&BBOX=%.15g,%.15g,%.15g,%.15g,%s&SRSNAME=%s",
448
					 bbox->minx, bbox->miny, bbox->maxx, bbox->maxy,
449 450 451 452 453 454 455 456 457
					 projUrn, projUrn);
		 }
	  } else {
		  snprintf(pszURL + strlen(pszURL), bufferSize - strlen(pszURL),
				  "&BBOX=%.15g,%.15g,%.15g,%.15g",
				  bbox->minx, bbox->miny, bbox->maxx, bbox->maxy);
	  }

	  msFree(projUrn);
458
	  msFree(projEpsg);
459
  }
460 461 462 463 464 465

  if (psParams->nMaxFeatures > 0)
    snprintf(pszURL + strlen(pszURL), bufferSize-strlen(pszURL),
             "&MAXFEATURES=%d", psParams->nMaxFeatures);

  return pszURL;
466 467 468 469 470 471 472

}

/**********************************************************************
 *                          msWFSLayerInfo
 *
 **********************************************************************/
473 474 475 476 477 478
typedef struct ms_wfs_layer_info_t {
  char        *pszGMLFilename;
  rectObj     rect;                     /* set by WhichShapes */
  char        *pszGetUrl;
  int         nStatus;           /* HTTP status */
  int         bLayerHasValidGML;  /* False until msWFSLayerWhichShapes() is called and determines the result GML is valid with features*/
479 480 481 482 483 484 485 486 487
} msWFSLayerInfo;


/**********************************************************************
 *                          msAllocWFSLayerInfo()
 *
 **********************************************************************/
static msWFSLayerInfo *msAllocWFSLayerInfo(void)
{
488
  msWFSLayerInfo *psInfo;
489

490 491
  psInfo = (msWFSLayerInfo*)calloc(1,sizeof(msWFSLayerInfo));
  MS_CHECK_ALLOC(psInfo, sizeof(msWFSLayerInfo), NULL);
492

493 494 495 496 497
  psInfo->pszGMLFilename = NULL;
  psInfo->rect.minx = psInfo->rect.maxx = 0;
  psInfo->rect.miny = psInfo->rect.maxy = 0;
  psInfo->pszGetUrl = NULL;
  psInfo->nStatus = 0;
498

499
  return psInfo;
500 501 502 503 504 505 506 507
}

/**********************************************************************
 *                          msFreeWFSLayerInfo()
 *
 **********************************************************************/
static void msFreeWFSLayerInfo(msWFSLayerInfo *psInfo)
{
508 509 510 511 512 513 514 515
  if (psInfo) {
    if (psInfo->pszGMLFilename)
      free(psInfo->pszGMLFilename);
    if (psInfo->pszGetUrl)
      free(psInfo->pszGetUrl);

    free(psInfo);
  }
516 517 518 519 520 521 522 523 524 525 526 527 528 529
}

#endif /* USE_WFS_LYR */

/*====================================================================
 *  Public functions
 *====================================================================*/

/**********************************************************************
 *                          msPrepareWFSLayerRequest()
 *
 **********************************************************************/

int msPrepareWFSLayerRequest(int nLayerId, mapObj *map, layerObj *lp,
530
                             httpRequestObj *pasReqInfo, int *numRequests)
531 532
{
#ifdef USE_WFS_LYR
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
  char *pszURL = NULL;
  const char *pszTmp;
  rectObj bbox;
  int nTimeout;
  int nStatus = MS_SUCCESS;
  msWFSLayerInfo *psInfo = NULL;
  int bPostRequest = 0;
  wfsParamsObj *psParams = NULL;
  char *pszHTTPCookieData = NULL;


  if (lp->connectiontype != MS_WFS || lp->connection == NULL)
    return MS_FAILURE;

  /* ------------------------------------------------------------------
   * Build a params object that will be used by to build the request,
    this will also set layer projection and compute BBOX in that projection.
   * ------------------------------------------------------------------ */
  psParams = msBuildRequestParams(map, lp, &bbox);
  if (!psParams)
    return MS_FAILURE;

  /* -------------------------------------------------------------------- */
  /*      Depending on the metadata wfs_request_method, build a Get or    */
  /*      a Post URL.                                                     */
  /*    If it is a Get request the URL would contain all the parameters in*/
  /*      the string;                                                     */
  /*      If it is a Post request, the URL will only contain the          */
  /*      connection string comming from the layer.                       */
  /* -------------------------------------------------------------------- */
  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
                                    "FO", "request_method")) != NULL) {
    if (strncmp(pszTmp, "GET", 3) ==0) {
      pszURL = msBuildWFSLayerGetURL(map, lp, &bbox, psParams);
      if (!pszURL) {
        /* an error was already reported. */
569
        return MS_FAILURE;
570
      }
571
    }
572 573 574 575 576 577 578 579 580 581 582 583 584
  }
  /* else it is a post request and just get the connection string */
  if (!pszURL) {
    bPostRequest = 1;
    pszURL = msStrdup(lp->connection);
  }

  /* ------------------------------------------------------------------
   * check to see if a the metadata wfs_connectiontimeout is set. If it is
   * the case we will use it, else we use the default which is 30 seconds.
   * First check the metadata in the layer object and then in the map object.
   * ------------------------------------------------------------------ */
  nTimeout = 30;  /* Default is 30 seconds  */
585
  if ((pszTmp = msOWSLookupMetadata2(&(lp->metadata), &(map->web.metadata),
586 587 588 589 590 591 592 593 594 595
                                    "FO", "connectiontimeout")) != NULL) {
    nTimeout = atoi(pszTmp);
  }

  /*------------------------------------------------------------------
   * Check to see if there's a HTTP Cookie to forward
   * If Cookie differ between the two connection, it's NOT OK to merge
   * the connection
   * ------------------------------------------------------------------ */
  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
596
                                    "FO", "http_cookie")) != NULL) {
597 598 599 600 601 602 603
    if(strcasecmp(pszTmp, "forward") == 0) {
      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
      if(pszTmp != NULL) {
        pszHTTPCookieData = msStrdup(pszTmp);
      }
    } else {
      pszHTTPCookieData = msStrdup(pszTmp);
604
    }
605
  } else if ((pszTmp = msOWSLookupMetadata(&(map->web.metadata),
606
                       "FO", "http_cookie")) != NULL) {
607 608 609 610 611 612 613
    if(strcasecmp(pszTmp, "forward") == 0) {
      pszTmp= msLookupHashTable(&(map->web.metadata),"http_cookie_data");
      if(pszTmp != NULL) {
        pszHTTPCookieData = msStrdup(pszTmp);
      }
    } else {
      pszHTTPCookieData = msStrdup(pszTmp);
614
    }
615 616 617 618 619 620 621 622 623 624 625 626
  }

  /* ------------------------------------------------------------------
   * If nLayerId == -1 then we need to figure it
   * ------------------------------------------------------------------ */
  if (nLayerId == -1) {
    int iLayer;
    for(iLayer=0; iLayer < map->numlayers; iLayer++) {
      if (GET_LAYER(map, iLayer) == lp) {
        nLayerId = iLayer;
        break;
      }
627
    }
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
  }

  /* ------------------------------------------------------------------
   * Add a request to the array (already preallocated)
   * ------------------------------------------------------------------ */
  pasReqInfo[(*numRequests)].nLayerId = nLayerId;
  pasReqInfo[(*numRequests)].pszGetUrl = pszURL;

  if (bPostRequest) {
    pasReqInfo[(*numRequests)].pszPostRequest =
      msBuildWFSLayerPostRequest(map, lp, &bbox, psParams);
    pasReqInfo[(*numRequests)].pszPostContentType =
      msStrdup("text/xml");
  }


  /* We'll store the remote server's response to a tmp file. */
  pasReqInfo[(*numRequests)].pszOutputFile = msTmpFile(map, map->mappath, NULL, "tmp.gml");

  /* TODO: Implement Caching of GML responses. There was an older caching
   * method, but it suffered from a race condition. See #3137.
   */

  pasReqInfo[(*numRequests)].pszHTTPCookieData = pszHTTPCookieData;
  pszHTTPCookieData = NULL;
  pasReqInfo[(*numRequests)].nStatus = 0;
  pasReqInfo[(*numRequests)].nTimeout = nTimeout;
  pasReqInfo[(*numRequests)].bbox = bbox;
  pasReqInfo[(*numRequests)].debug = lp->debug;

658
  if (msHTTPAuthProxySetup(&(map->web.metadata), &(lp->metadata),
659 660 661 662
                           pasReqInfo, *numRequests, map, "FO") != MS_SUCCESS) {
    if (psParams) {
      msWFSFreeParamsObj(psParams);
    }
663
    return MS_FAILURE;
664
  }
665
  
666 667 668 669 670 671 672 673 674 675
  /* ------------------------------------------------------------------
   * Pre-Open the layer now, (i.e. alloc and fill msWFSLayerInfo inside
   * layer obj).  Layer will be ready for use when the main mapserver
   * code calls msLayerOpen().
   * ------------------------------------------------------------------ */
  if (lp->wfslayerinfo != NULL) {
    psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
  } else {
    lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();
  }
676

677 678 679
  if (psInfo->pszGMLFilename)
    free(psInfo->pszGMLFilename);
  psInfo->pszGMLFilename=msStrdup(pasReqInfo[(*numRequests)].pszOutputFile);
680

681
  psInfo->rect = pasReqInfo[(*numRequests)].bbox;
682

683 684 685
  if (psInfo->pszGetUrl)
    free(psInfo->pszGetUrl);
  psInfo->pszGetUrl = msStrdup(pasReqInfo[(*numRequests)].pszGetUrl);
686

687
  psInfo->nStatus = 0;
688

689
  (*numRequests)++;
690

691 692 693 694
  if (psParams) {
    msWFSFreeParamsObj(psParams);
  }
  return nStatus;
695 696

#else
697 698 699 700
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
             "msPrepareWFSLayerRequest");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSUpdateRequestInfo()
 *
 * This function is called after a WFS request has been completed so that
 * we can copy request result information from the httpRequestObj to the
 * msWFSLayerInfo struct.  Things to copy here are the HTTP status, exceptions
 * information, mime type, etc.
 **********************************************************************/
void msWFSUpdateRequestInfo(layerObj *lp, httpRequestObj *pasReqInfo)
{
#ifdef USE_WFS_LYR
719 720
  if (lp->wfslayerinfo) {
    msWFSLayerInfo *psInfo = NULL;
721

722
    psInfo =(msWFSLayerInfo*)(lp->wfslayerinfo);
723

724 725 726 727 728
    /* Copy request results infos to msWFSLayerInfo struct */
    /* For now there is only nStatus, but we should eventually add */
    /* mime type and WFS exceptions information. */
    psInfo->nStatus = pasReqInfo->nStatus;
  }
729
#else
730 731 732 733
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
734 735 736 737 738 739 740 741 742 743 744 745 746
             "msWFSUpdateRequestInfo()");
#endif /* USE_WFS_LYR */
}

/**********************************************************************
 *                          msWFSLayerOpen()
 *
 * WFS layers are just a special case of OGR connection.  Only the open/close
 * methods differ since they have to download and maintain GML files in cache
 * but the rest is mapped directly to OGR function calls in maplayer.c
 *
 **********************************************************************/

747 748
int msWFSLayerOpen(layerObj *lp,
                   const char *pszGMLFilename, rectObj *defaultBBOX)
749 750
{
#ifdef USE_WFS_LYR
751 752
  int status = MS_SUCCESS;
  msWFSLayerInfo *psInfo = NULL;
753

754 755
  if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
    return MS_FAILURE;
756

757 758
  if (lp->wfslayerinfo != NULL) {
    psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
759

760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
    /* Layer already opened.  If explicit filename requested then check */
    /* that file was already opened with the same filename. */
    /* If no explicit filename requested then we'll try to reuse the */
    /* previously opened layer... this will happen in a msDrawMap() call. */
    if (pszGMLFilename == NULL ||
        (psInfo->pszGMLFilename && pszGMLFilename &&
         strcmp(psInfo->pszGMLFilename, pszGMLFilename) == 0) ) {
      if (lp->layerinfo == NULL) {
        if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE) /* no access to context (draw vs. query) here, although I doubt it matters... */
          return MS_FAILURE;
      }
      return MS_SUCCESS;  /* Nothing to do... layer is already opened */
    } else {
      /* Hmmm... should we produce a fatal error? */
      /* For now we'll just close the layer and reopen it. */
      if (lp->debug)
        msDebug("msWFSLayerOpen(): Layer already opened (%s)\n",
                lp->name?lp->name:"(null)" );
      msWFSLayerClose(lp);
779
    }
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
  }

  /* ------------------------------------------------------------------
   * Alloc and fill msWFSLayerInfo inside layer obj
   * ------------------------------------------------------------------ */
  lp->wfslayerinfo = psInfo = msAllocWFSLayerInfo();

  if (pszGMLFilename)
    psInfo->pszGMLFilename = msStrdup(pszGMLFilename);
  else {
    psInfo->pszGMLFilename = msTmpFile(lp->map,
                                       lp->map->mappath,
                                       NULL,
                                       "tmp.gml");
  }

  if (defaultBBOX) {
    /* __TODO__ If new bbox differs from current one then we should */
    /* invalidate current GML file in cache */
    psInfo->rect = *defaultBBOX;
  } else {
    /* Use map bbox by default */
    psInfo->rect = lp->map->extent;
  }

  /* We will call whichshapes() now and force downloading layer right */
  /* away.  This saves from having to call DescribeFeatureType and */
  /* parsing the response (being lazy I guess) and anyway given the */
  /* way we work with layers right now the bbox is unlikely to change */
  /* between now and the time whichshapes() would have been called by */
  /* the MapServer core. */
811
#ifdef USE_PROJ
812 813
  if((lp->map->projection.numargs > 0) && (lp->projection.numargs > 0))
    msProjectRect(&lp->map->projection, &lp->projection, &psInfo->rect); /* project the searchrect to source coords */
814 815
#endif

816 817
  if (msWFSLayerWhichShapes(lp, psInfo->rect, MS_FALSE) == MS_FAILURE)  /* no access to context (draw vs. query) here, although I doubt it matters... */
    status = MS_FAILURE;
818

819 820

  return status;
821
#else
822 823 824 825
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
826 827 828 829 830 831 832 833 834 835 836
             "msWFSLayerOpen()");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */
}

/**********************************************************************
 *                          msWFSLayerOpenVT()
 *
 * Overloaded version of msWFSLayerOpen for virtual table architecture
 **********************************************************************/
837
int
838 839
msWFSLayerOpenVT(layerObj *lp)
{
840
  return msWFSLayerOpen(lp, NULL, NULL);
841 842 843 844 845 846 847 848 849
}

/**********************************************************************
 *                          msWFSLayerIsOpen()
 *
 * Returns MS_TRUE if layer is already open, MS_FALSE otherwise.
 *
 **********************************************************************/

850
int msWFSLayerIsOpen(layerObj *lp)
851 852
{
#ifdef USE_WFS_LYR
853 854
  if (lp->wfslayerinfo != NULL)
    return MS_TRUE;
855

856
  return MS_FALSE;
857
#else
858 859 860 861
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
862 863 864 865 866 867 868 869 870 871 872 873 874
             "msWFSLayerIsOpen()");
  return(MS_FALSE);

#endif /* USE_WFS_LYR */
}

/**********************************************************************
 *                          msWFSLayerInitItemInfo()
 *
 **********************************************************************/

int msWFSLayerInitItemInfo(layerObj *layer)
{
875 876 877 878 879
  /* Nothing to do here.  OGR will do its own initialization when it */
  /* opens the actual file. */
  /* Note that we didn't implement our own msWFSLayerFreeItemInfo() */
  /* so that the OGR one gets called. */
  return MS_SUCCESS;
880 881 882 883 884 885
}

/**********************************************************************
 *                          msWFSLayerGetShape()
 *
 **********************************************************************/
886
int msWFSLayerGetShape(layerObj *layer, shapeObj *shape, resultObj *record)
887 888
{
#ifdef USE_WFS_LYR
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
  msWFSLayerInfo* psInfo = NULL;

  if(layer != NULL && layer->wfslayerinfo != NULL)
    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
  else {
    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetShape()");
    return MS_FAILURE;
  }

  if(psInfo->bLayerHasValidGML)
    return msOGRLayerGetShape(layer, shape, record);
  else {
    /* Layer is successful, but there is no data to process */
    msFreeShape(shape);
    shape->type = MS_SHAPE_NULL;
    return MS_FAILURE;
  }
906
#else
907 908 909 910
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
911 912 913 914 915 916 917 918 919 920 921 922 923
             "msWFSLayerGetShape()");
  return(MS_FAILURE);
#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSLayerGetNextShape()
 *
 **********************************************************************/
int msWFSLayerNextShape(layerObj *layer, shapeObj *shape)
{
#ifdef USE_WFS_LYR
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  msWFSLayerInfo* psInfo = NULL;

  if(layer != NULL && layer->wfslayerinfo != NULL)
    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
  else {
    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerNextShape()");
    return MS_FAILURE;
  }

  if(psInfo->bLayerHasValidGML)
    return msOGRLayerNextShape(layer, shape);
  else {
    /* Layer is successful, but there is no data to process */
    msFreeShape(shape);
    shape->type = MS_SHAPE_NULL;
    return MS_FAILURE;
  }
941
#else
942 943 944 945
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
946 947 948 949 950 951 952 953 954 955
             "msWFSLayerNextShape()");
  return(MS_FAILURE);
#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSLayerGetExtent()
 *
 **********************************************************************/
956
int msWFSLayerGetExtent(layerObj *layer, rectObj *extent)
957 958
{
#ifdef USE_WFS_LYR
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
  msWFSLayerInfo* psInfo = NULL;

  if(layer != NULL && layer->wfslayerinfo != NULL)
    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
  else {
    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetExtent()");
    return MS_FAILURE;
  }

  if(psInfo->bLayerHasValidGML)
    return msOGRLayerGetExtent(layer, extent);
  else {
    /* Layer is successful, but there is no data to process */
    msSetError(MS_WFSERR, "Unable to get extents for this layer.", "msWFSLayerGetExtent()");
    return MS_FAILURE;
  }
975
#else
976 977 978 979
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
980 981 982 983 984 985 986 987 988 989 990 991 992 993
             "msWFSLayerGetExtent()");
  return(MS_FAILURE);
#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSLayerGetItems()
 *
 **********************************************************************/

int msWFSLayerGetItems(layerObj *layer)
{
#ifdef USE_WFS_LYR
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
  /* For now this method simply lets OGR parse the GML and figure the  */
  /* schema itself. */
  /* It could also be implemented to call DescribeFeatureType for */
  /* this layer, but we don't need to do it so why waste resources? */

  msWFSLayerInfo* psInfo = NULL;

  if(layer != NULL && layer->wfslayerinfo != NULL)
    psInfo = (msWFSLayerInfo*)layer->wfslayerinfo;
  else {
    msSetError(MS_WFSERR, "Layer is not opened.", "msWFSLayerGetItems()");
    return MS_FAILURE;
  }

  if(psInfo->bLayerHasValidGML)
    return msOGRLayerGetItems(layer);
  else {
    /* Layer is successful, but there is no data to process */
    layer->numitems = 0;
    layer->items = NULL;
    return MS_SUCCESS;
  }
1016
#else
1017 1018 1019 1020
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
             "msWFSLayerGetItems()");
  return(MS_FAILURE);
#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSLayerWhichShapes()
 *
 **********************************************************************/

1032
int msWFSLayerWhichShapes(layerObj *lp, rectObj rect, int isQuery)
1033 1034
{
#ifdef USE_WFS_LYR
1035 1036 1037 1038
  msWFSLayerInfo *psInfo;
  int status = MS_SUCCESS;
  const char *pszTmp;
  FILE *fp;
1039

1040 1041
  if ( msCheckParentPointer(lp->map,"map")==MS_FAILURE )
    return MS_FAILURE;
1042 1043


1044
  psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
1045

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
  if (psInfo == NULL) {
    msSetError(MS_WFSCONNERR, "Assertion failed: WFS layer not opened!!!",
               "msWFSLayerWhichShapes()");
    return(MS_FAILURE);
  }

  /* ------------------------------------------------------------------
   * Check if layer overlaps current view window (using wfs_latlonboundingbox)
   * ------------------------------------------------------------------ */
  if ((pszTmp = msOWSLookupMetadata(&(lp->metadata),
                                    "FO", "latlonboundingbox")) != NULL) {
    char **tokens;
    int n;
    rectObj ext;

    tokens = msStringSplit(pszTmp, ' ', &n);
    if (tokens==NULL || n != 4) {
      msSetError(MS_WFSCONNERR, "Wrong number of values in 'wfs_latlonboundingbox' metadata.",
                 "msWFSLayerWhichShapes()");
      return MS_FAILURE;
    }
1067

1068 1069 1070 1071
    ext.minx = atof(tokens[0]);
    ext.miny = atof(tokens[1]);
    ext.maxx = atof(tokens[2]);
    ext.maxy = atof(tokens[3]);
1072

1073
    msFreeCharArray(tokens, n);
1074

1075 1076 1077 1078 1079 1080 1081 1082
    /* Reproject latlonboundingbox to the selected SRS for the layer and */
    /* check if it overlaps the bbox that we calculated for the request */

    msProjectRect(&(lp->map->latlon), &(lp->projection), &ext);
    if (!msRectOverlap(&rect, &ext)) {
      /* No overlap... nothing to do. If layer was never opened, go open it.*/
      if (lp->layerinfo)
        return MS_DONE;  /* No overlap. */
1083
    }
1084
  }
1085 1086


1087 1088 1089 1090 1091
  /* ------------------------------------------------------------------
   * __TODO__ If new bbox differs from current one then we should
   * invalidate current GML file in cache
   * ------------------------------------------------------------------ */
  psInfo->rect = rect;
1092 1093


1094 1095 1096 1097 1098 1099
  /* ------------------------------------------------------------------
   * If file not downloaded yet then do it now.
   * ------------------------------------------------------------------ */
  if (psInfo->nStatus == 0) {
    httpRequestObj asReqInfo[2];
    int numReq = 0;
1100

1101
    msHTTPInitRequestObj(asReqInfo, 2);
1102

1103 1104 1105 1106 1107 1108 1109 1110
    if ( msPrepareWFSLayerRequest(-1, lp->map, lp,
                                  asReqInfo, &numReq) == MS_FAILURE  ||
         msOWSExecuteRequests(asReqInfo, numReq,
                              lp->map, MS_TRUE) == MS_FAILURE ) {
      /* Delete tmp file... we don't want it to stick around. */
      unlink(asReqInfo[0].pszOutputFile);
      return MS_FAILURE;
    }
1111

1112 1113
    /* Cleanup */
    msHTTPFreeRequestObj(asReqInfo, numReq);
1114

1115
  }
1116

1117 1118 1119
  if ( !MS_HTTP_SUCCESS( psInfo->nStatus ) ) {
    /* Delete tmp file... we don't want it to stick around. */
    unlink(psInfo->pszGMLFilename);
1120

1121 1122 1123 1124 1125 1126
    msSetError(MS_WFSCONNERR,
               "Got HTTP status %d downloading WFS layer %s",
               "msWFSLayerWhichShapes()",
               psInfo->nStatus, lp->name?lp->name:"(null)");
    return(MS_FAILURE);
  }
1127

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  /* ------------------------------------------------------------------
   * Check that file is really GML... it could be an exception, or just junk.
   * ------------------------------------------------------------------ */
  if ((fp = fopen(psInfo->pszGMLFilename, "r")) != NULL) {
    char szHeader[2000];
    int  nBytes = 0;

    nBytes = fread( szHeader, 1, sizeof(szHeader)-1, fp );
    fclose(fp);

    if (nBytes < 0)
      nBytes = 0;
    szHeader[nBytes] = '\0';

    if ( nBytes == 0 ) {
      msSetError(MS_WFSCONNERR,
                 "WFS request produced no oputput for layer %s.",
                 "msWFSLayerWhichShapes()",
                 lp->name?lp->name:"(null)");
      return(MS_FAILURE);
1148 1149

    }
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    if ( strstr(szHeader, "<WFS_Exception>") ||
         strstr(szHeader, "<ServiceExceptionReport>") ) {
      msOWSProcessException(lp, psInfo->pszGMLFilename,
                            MS_WFSCONNERR, "msWFSLayerWhichShapes()" );
      return MS_FAILURE;
    } else if ( strstr(szHeader,"opengis.net/gml") &&
                strstr(szHeader,"featureMember>") == NULL ) {
      /* This looks like valid GML, but contains 0 features. */
      return MS_DONE;
    } else if ( strstr(szHeader,"opengis.net/gml") == NULL ||
                strstr(szHeader,"featureMember>") == NULL ) {
      /* This is probably just junk. */
      msSetError(MS_WFSCONNERR,
                 "WFS request produced unexpected output (junk?) for layer %s.",
                 "msWFSLayerWhichShapes()",
                 lp->name?lp->name:"(null)");
      return(MS_FAILURE);
    }

    /* If we got this far, it must be a valid GML dataset... keep going */
  }
1171 1172


1173 1174 1175 1176
  /* ------------------------------------------------------------------
   * Open GML file using OGR.
   * ------------------------------------------------------------------ */
  if ((status = msOGRLayerOpen(lp, psInfo->pszGMLFilename)) != MS_SUCCESS)
1177
    return status;
1178 1179 1180 1181 1182 1183 1184

  status = msOGRLayerWhichShapes(lp, rect, isQuery);

  /* Mark that the OGR Layer is valid */
  psInfo->bLayerHasValidGML = MS_TRUE;

  return status;
1185
#else
1186 1187 1188 1189
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
             "msWFSLayerWhichShapes()");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */
}



/**********************************************************************
 *                          msWFSLayerClose()
 *
 **********************************************************************/

int msWFSLayerClose(layerObj *lp)
{
#ifdef USE_WFS_LYR

1207 1208 1209 1210 1211
  /* ------------------------------------------------------------------
   * Cleanup OGR connection
   * ------------------------------------------------------------------ */
  if (lp->layerinfo)
    msOGRLayerClose(lp);
1212

1213 1214 1215 1216 1217 1218
  /* ------------------------------------------------------------------
   * Cleanup WFS connection info.
   * __TODO__ For now we flush everything, but we should try to cache some stuff
   * ------------------------------------------------------------------ */
  /* __TODO__ unlink()  .gml file and OGR's schema file if they exist */
  /* unlink( */
1219

1220 1221
  msFreeWFSLayerInfo(lp->wfslayerinfo);
  lp->wfslayerinfo = NULL;
1222

1223
  return MS_SUCCESS;
1224 1225

#else
1226 1227 1228 1229
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
             "msWFSLayerClose()");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */

}

/**********************************************************************
 *                          msWFSExecuteGetFeature()
 * Returns the temporary gml file name. User shpuld free the return string.
 **********************************************************************/
char *msWFSExecuteGetFeature(layerObj *lp)
{
#ifdef USE_WFS_LYR
  char *gmltmpfile = NULL;
  msWFSLayerInfo *psInfo = NULL;

  if (lp == NULL || lp->connectiontype != MS_WFS)
    return NULL;

  msWFSLayerOpen(lp, NULL, NULL);
  psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;
  if (psInfo &&  psInfo->pszGMLFilename)
1253
    gmltmpfile = msStrdup(psInfo->pszGMLFilename);
1254 1255 1256 1257 1258
  msWFSLayerClose(lp);

  return gmltmpfile;

#else
1259 1260 1261 1262
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
             "msExecuteWFSGetFeature()");
  return NULL;

#endif /* USE_WFS_LYR */

}

int
msWFSLayerInitializeVirtualTable(layerObj *layer)
{
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
  assert(layer != NULL);
  assert(layer->vtable != NULL);

  layer->vtable->LayerInitItemInfo = msWFSLayerInitItemInfo;
  layer->vtable->LayerFreeItemInfo = msOGRLayerFreeItemInfo; /* yes, OGR */
  layer->vtable->LayerOpen = msWFSLayerOpenVT;
  layer->vtable->LayerIsOpen = msWFSLayerIsOpen;
  layer->vtable->LayerWhichShapes = msWFSLayerWhichShapes;
  layer->vtable->LayerNextShape = msWFSLayerNextShape;
  /* layer->vtable->LayerResultsGetShape = msWFSLayerResultGetShape; */
1283
  /* layer->vtable->LayerGetShapeCount, use default */
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
  layer->vtable->LayerGetShape = msWFSLayerGetShape;
  layer->vtable->LayerClose = msWFSLayerClose;
  layer->vtable->LayerGetItems = msWFSLayerGetItems;
  layer->vtable->LayerGetExtent = msWFSLayerGetExtent;
  /* layer->vtable->LayerGetAutoStyle, use default */
  /* layer->vtable->LayerApplyFilterToLayer, use default */
  /* layer->vtable->LayerCloseConnection, use default */
  layer->vtable->LayerSetTimeFilter = msLayerMakePlainTimeFilter;
  /* layer->vtable->LayerCreateItems, use default */
  /* layer->vtable->LayerGetNumFeatures, use default */
  /* layer->vtable->LayerGetAutoProjection, use defaut*/

  return MS_SUCCESS;
1297 1298
}