mapogr.cpp 135 KB
Newer Older
1
/**********************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Project:  MapServer
 * Purpose:  OGR Link
 * Author:   Daniel Morissette, DM Solutions Group (morissette@dmsolutions.ca)
 *           Frank Warmerdam (warmerdam@pobox.com)
 *
 **********************************************************************
 * Copyright (c) 2000-2005, 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:
18 19
 *
 * The above copyright notice and this permission notice shall be included in
20
 * all copies of this Software or works derived from this Software.
21
 *
22 23 24 25 26
 * 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
27
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
28 29 30 31 32 33 34
 * DEALINGS IN THE SOFTWARE.
 **********************************************************************/

#include <assert.h>
#include "mapserver.h"
#include "mapproject.h"
#include "mapthread.h"
35
#include "mapows.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

#if defined(USE_OGR) || defined(USE_GDAL)
#  include "gdal_version.h"
#  include "cpl_conv.h"
#  include "cpl_string.h"
#  include "ogr_srs_api.h"
#endif

#define ACQUIRE_OGR_LOCK       msAcquireLock( TLOCK_OGR )
#define RELEASE_OGR_LOCK       msReleaseLock( TLOCK_OGR )

#ifdef USE_OGR

#include "ogr_api.h"

51
typedef struct ms_ogr_file_info_t {
52
  char        *pszFname;
53
  char        *pszLayerDef;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
  int         nLayerIndex;
  OGRDataSourceH hDS;
  OGRLayerH   hLayer;
  OGRFeatureH hLastFeature;

  int         nTileId;                  /* applies on the tiles themselves. */

  struct ms_ogr_file_info_t *poCurTile; /* exists on tile index, -> tiles */
  rectObj     rect;                     /* set by WhichShapes */

  int         last_record_index_read;

} msOGRFileInfo;

static int msOGRLayerIsOpen(layerObj *layer);
static int msOGRLayerInitItemInfo(layerObj *layer);
70
static int msOGRLayerGetAutoStyle(mapObj *map, layerObj *layer, classObj *c,
71
                                  shapeObj* shape);
72 73 74 75 76 77 78 79 80 81 82
static void msOGRCloseConnection( void *conn_handle );

/* ==================================================================
 * Geometry conversion functions
 * ================================================================== */

/**********************************************************************
 *                     ogrPointsAddPoint()
 *
 * NOTE: This function assumes the line->point array already has been
 * allocated large enough for the point to be added, but that numpoints
83
 * does not include this new point.
84
 **********************************************************************/
85
static void ogrPointsAddPoint(lineObj *line, double dX, double dY,
86 87 88
#ifdef USE_POINT_Z_M
                              double dZ,
#endif
89 90
                              int lineindex, rectObj *bounds)
{
91 92 93 94 95 96 97 98 99 100 101 102 103
  /* Keep track of shape bounds */
  if (line->numpoints == 0 && lineindex == 0) {
    bounds->minx = bounds->maxx = dX;
    bounds->miny = bounds->maxy = dY;
  } else {
    if (dX < bounds->minx)  bounds->minx = dX;
    if (dX > bounds->maxx)  bounds->maxx = dX;
    if (dY < bounds->miny)  bounds->miny = dY;
    if (dY > bounds->maxy)  bounds->maxy = dY;
  }

  line->point[line->numpoints].x = dX;
  line->point[line->numpoints].y = dY;
104
#ifdef USE_POINT_Z_M
105
  line->point[line->numpoints].z = dZ;
106
  line->point[line->numpoints].m = 0.0;
107
#endif
108
  line->numpoints++;
109 110 111 112 113
}

/**********************************************************************
 *                     ogrGeomPoints()
 **********************************************************************/
114
static int ogrGeomPoints(OGRGeometryH hGeom, shapeObj *outshp)
115 116 117 118
{
  int   i;
  int   numpoints;

119 120
  if (hGeom == NULL)
    return 0;
121 122 123

  OGRwkbGeometryType eGType =  wkbFlatten( OGR_G_GetGeometryType( hGeom ) );

124 125 126 127 128 129 130 131 132 133 134 135 136 137
  /* -------------------------------------------------------------------- */
  /*      Container types result in recursive invocation on each          */
  /*      subobject to add a set of points to the current list.           */
  /* -------------------------------------------------------------------- */
  switch( eGType ) {
    case wkbGeometryCollection:
    case wkbMultiLineString:
    case wkbMultiPolygon:
    case wkbPolygon: {
      /* Treat it as GeometryCollection */
      for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ ) {
        if( ogrGeomPoints( OGR_G_GetGeometryRef( hGeom, iGeom ),
                           outshp ) == -1 )
          return -1;
138 139
      }

140 141 142
      return 0;
    }
    break;
143

144 145 146 147 148 149
    case wkbPoint:
    case wkbMultiPoint:
    case wkbLineString:
    case wkbLinearRing:
      /* We will handle these directly */
      break;
150

151 152 153 154
    default:
      /* There shouldn't be any more cases should there? */
      msSetError(MS_OGRERR,
                 "OGRGeometry type `%s' not supported yet.",
155 156 157 158 159
                 "ogrGeomPoints()",
                 OGR_G_GetGeometryName( hGeom ) );
      return(-1);
  }

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193

  /* ------------------------------------------------------------------
   * Count total number of points
   * ------------------------------------------------------------------ */
  if ( eGType == wkbPoint ) {
    numpoints = 1;
  } else if ( eGType == wkbLineString
              ||  eGType == wkbLinearRing ) {
    numpoints = OGR_G_GetPointCount( hGeom );
  } else if ( eGType == wkbMultiPoint ) {
    numpoints = OGR_G_GetGeometryCount( hGeom );
  } else {
    msSetError(MS_OGRERR,
               "OGRGeometry type `%s' not supported yet.",
               "ogrGeomPoints()",
               OGR_G_GetGeometryName( hGeom ) );
    return(-1);
  }

  /* ------------------------------------------------------------------
   * Do we need to allocate a line object to contain all our points?
   * ------------------------------------------------------------------ */
  if( outshp->numlines == 0 ) {
    lineObj newline;

    newline.numpoints = 0;
    newline.point = NULL;
    msAddLine(outshp, &newline);
  }

  /* ------------------------------------------------------------------
   * Extend the point array for the new of points to add from the
   * current geometry.
   * ------------------------------------------------------------------ */
194 195 196
  lineObj *line = outshp->line + outshp->numlines-1;

  if( line->point == NULL )
197
    line->point = (pointObj *) malloc(sizeof(pointObj) * numpoints);
198
  else
199 200 201 202 203 204 205 206 207 208 209 210 211 212
    line->point = (pointObj *)
                  realloc(line->point,sizeof(pointObj) * (numpoints+line->numpoints));

  if(!line->point) {
    msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
               "ogrGeomPoints()");
    return(-1);
  }

  /* ------------------------------------------------------------------
   * alloc buffer and filter/transform points
   * ------------------------------------------------------------------ */
  if( eGType == wkbPoint ) {
    ogrPointsAddPoint(line, OGR_G_GetX(hGeom, 0), OGR_G_GetY(hGeom, 0),
213 214 215
#ifdef USE_POINT_Z_M
                      OGR_G_GetZ(hGeom, 0),
#endif
216 217 218 219 220
                      outshp->numlines-1, &(outshp->bounds));
  } else if( eGType == wkbLineString
             || eGType == wkbLinearRing ) {
    for(i=0; i<numpoints; i++)
      ogrPointsAddPoint(line, OGR_G_GetX(hGeom, i), OGR_G_GetY(hGeom, i),
221 222 223
#ifdef USE_POINT_Z_M
                        OGR_G_GetZ(hGeom, i),
#endif
224
                        outshp->numlines-1, &(outshp->bounds));
225 226 227 228
  } else if( eGType == wkbMultiPoint ) {
    for(i=0; i<numpoints; i++) {
      OGRGeometryH hPoint = OGR_G_GetGeometryRef( hGeom, i );
      ogrPointsAddPoint(line, OGR_G_GetX(hPoint, 0), OGR_G_GetY(hPoint, 0),
229 230 231
#ifdef USE_POINT_Z_M
                        OGR_G_GetZ(hPoint, 0),
#endif
232 233
                        outshp->numlines-1, &(outshp->bounds));
    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  }

  outshp->type = MS_SHAPE_POINT;

  return(0);
}


/**********************************************************************
 *                     ogrGeomLine()
 *
 * Recursively convert any OGRGeometry into a shapeObj.  Each part becomes
 * a line in the overall shapeObj.
 **********************************************************************/
static int ogrGeomLine(OGRGeometryH hGeom, shapeObj *outshp,
249
                       int bCloseRings)
250 251
{
  if (hGeom == NULL)
252
    return 0;
253

254 255 256
  /* ------------------------------------------------------------------
   * Use recursive calls for complex geometries
   * ------------------------------------------------------------------ */
257 258
  OGRwkbGeometryType eGType =  wkbFlatten( OGR_G_GetGeometryType( hGeom ) );

259

260 261
  if ( eGType == wkbPolygon
       || eGType == wkbGeometryCollection
262 263 264 265 266 267 268 269 270 271 272
       || eGType == wkbMultiLineString
       || eGType == wkbMultiPolygon ) {
    if (eGType == wkbPolygon && outshp->type == MS_SHAPE_NULL)
      outshp->type = MS_SHAPE_POLYGON;

    /* Treat it as GeometryCollection */
    for (int iGeom=0; iGeom < OGR_G_GetGeometryCount( hGeom ); iGeom++ ) {
      if( ogrGeomLine( OGR_G_GetGeometryRef( hGeom, iGeom ),
                       outshp, bCloseRings ) == -1 )
        return -1;
    }
273
  }
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
  /* ------------------------------------------------------------------
   * OGRPoint and OGRMultiPoint
   * ------------------------------------------------------------------ */
  else if ( eGType == wkbPoint || eGType == wkbMultiPoint ) {
    /* Hummmm a point when we're drawing lines/polygons... just drop it! */
  }
  /* ------------------------------------------------------------------
   * OGRLinearRing/OGRLineString ... both are of type wkbLineString
   * ------------------------------------------------------------------ */
  else if ( eGType == wkbLineString ) {
    int       j, numpoints;
    lineObj   line= {0,NULL};
    double    dX, dY;

    if ((numpoints = OGR_G_GetPointCount( hGeom )) < 2)
      return 0;
290

291 292
    if (outshp->type == MS_SHAPE_NULL)
      outshp->type = MS_SHAPE_LINE;
293

294 295 296 297 298 299 300
    line.numpoints = 0;
    line.point = (pointObj *)malloc(sizeof(pointObj)*(numpoints+1));
    if(!line.point) {
      msSetError(MS_MEMERR, "Unable to allocate temporary point cache.",
                 "ogrGeomLine");
      return(-1);
    }
301

302 303 304 305
#if GDAL_VERSION_NUM >= 1900
    OGR_G_GetPoints(hGeom,
                    &(line.point[0].x), sizeof(pointObj),
                    &(line.point[0].y), sizeof(pointObj),
306 307 308
#ifdef USE_POINT_Z_M
                    &(line.point[0].z), sizeof(pointObj));
#else
309
                    NULL, 0);
310
#endif
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
#endif

    for(j=0; j<numpoints; j++) {
#if GDAL_VERSION_NUM < 1900
      dX = line.point[j].x = OGR_G_GetX( hGeom, j);
      dY = line.point[j].y = OGR_G_GetY( hGeom, j);
#else
      dX = line.point[j].x;
      dY = line.point[j].y;
#endif

      /* Keep track of shape bounds */
      if (j == 0 && outshp->numlines == 0) {
        outshp->bounds.minx = outshp->bounds.maxx = dX;
        outshp->bounds.miny = outshp->bounds.maxy = dY;
      } else {
        if (dX < outshp->bounds.minx)  outshp->bounds.minx = dX;
        if (dX > outshp->bounds.maxx)  outshp->bounds.maxx = dX;
        if (dY < outshp->bounds.miny)  outshp->bounds.miny = dY;
        if (dY > outshp->bounds.maxy)  outshp->bounds.maxy = dY;
331 332
      }

333 334 335 336 337 338 339 340
    }
    line.numpoints = numpoints;

    if (bCloseRings &&
        ( line.point[line.numpoints-1].x != line.point[0].x ||
          line.point[line.numpoints-1].y != line.point[0].y  ) ) {
      line.point[line.numpoints].x = line.point[0].x;
      line.point[line.numpoints].y = line.point[0].y;
341 342 343
#ifdef USE_POINT_Z_M
      line.point[line.numpoints].z = line.point[0].z;
#endif
344 345 346 347 348 349 350 351 352 353
      line.numpoints++;
    }

    msAddLineDirectly(outshp, &line);
  } else {
    msSetError(MS_OGRERR,
               "OGRGeometry type `%s' not supported.",
               "ogrGeomLine()",
               OGR_G_GetGeometryName( hGeom ) );
    return(-1);
354 355 356 357 358
  }

  return(0);
}

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
/**********************************************************************
 *                     ogrGetLinearGeometry()
 *
 * Fetch geometry from OGR feature. If using GDAL 2.0 or later, the geometry
 * might be of curve type, so linearize it.
 **********************************************************************/
static OGRGeometryH ogrGetLinearGeometry(OGRFeatureH hFeature)
{
#if GDAL_VERSION_MAJOR >= 2
    /* Convert in place and reassign to the feature */
    OGRGeometryH hGeom = OGR_F_StealGeometry(hFeature);
    if( hGeom != NULL )
    {
        hGeom = OGR_G_ForceTo(hGeom, OGR_GT_GetLinear(OGR_G_GetGeometryType(hGeom)), NULL);
        OGR_F_SetGeometryDirectly(hFeature, hGeom);
    }
    return hGeom;
#else
    return OGR_F_GetGeometryRef( hFeature );
#endif
}
380 381 382 383

/**********************************************************************
 *                     ogrConvertGeometry()
 *
384
 * Convert OGR geometry into a shape object doing the best possible
385 386 387 388 389 390
 * job to match OGR Geometry type and layer type.
 *
 * If layer type is incompatible with geometry, then shape is returned with
 * shape->type = MS_SHAPE_NULL
 **********************************************************************/
static int ogrConvertGeometry(OGRGeometryH hGeom, shapeObj *outshp,
391
                              enum MS_LAYER_TYPE layertype)
392
{
393 394 395
  /* ------------------------------------------------------------------
   * Process geometry according to layer type
   * ------------------------------------------------------------------ */
396 397
  int nStatus = MS_SUCCESS;

398 399 400
  if (hGeom == NULL) {
    // Empty geometry... this is not an error... we'll just skip it
    return MS_SUCCESS;
401 402
  }

403 404 405 406
  switch(layertype) {
      /* ------------------------------------------------------------------
       *      POINT layer - Any geometry can be converted to point/multipoint
       * ------------------------------------------------------------------ */
407
    case MS_LAYER_POINT:
408 409
      if(ogrGeomPoints(hGeom, outshp) == -1) {
        nStatus = MS_FAILURE; // Error message already produced.
410 411
      }
      break;
412 413 414
      /* ------------------------------------------------------------------
       *      LINE layer
       * ------------------------------------------------------------------ */
415
    case MS_LAYER_LINE:
416 417
      if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1) {
        nStatus = MS_FAILURE; // Error message already produced.
418 419
      }
      if (outshp->type != MS_SHAPE_LINE && outshp->type != MS_SHAPE_POLYGON)
420
        outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
421
      break;
422 423 424
      /* ------------------------------------------------------------------
       *      POLYGON layer
       * ------------------------------------------------------------------ */
425
    case MS_LAYER_POLYGON:
426 427
      if(ogrGeomLine(hGeom, outshp, MS_TRUE) == -1) {
        nStatus = MS_FAILURE; // Error message already produced.
428 429
      }
      if (outshp->type != MS_SHAPE_POLYGON)
430
        outshp->type = MS_SHAPE_NULL;  // Incompatible type for this layer
431
      break;
432
      /* ------------------------------------------------------------------
433
       *      Chart or Query layers - return real feature type
434
       * ------------------------------------------------------------------ */
435 436
    case MS_LAYER_CHART:
    case MS_LAYER_QUERY:
437
      switch( OGR_G_GetGeometryType( hGeom ) ) {
438 439 440 441
        case wkbPoint:
        case wkbPoint25D:
        case wkbMultiPoint:
        case wkbMultiPoint25D:
442 443
          if(ogrGeomPoints(hGeom, outshp) == -1) {
            nStatus = MS_FAILURE; // Error message already produced.
444 445 446 447 448
          }
          break;
        default:
          // Handle any non-point types as lines/polygons ... ogrGeomLine()
          // will decide the shape type
449 450
          if(ogrGeomLine(hGeom, outshp, MS_FALSE) == -1) {
            nStatus = MS_FAILURE; // Error message already produced.
451 452 453 454 455
          }
      }
      break;

    default:
456
      msSetError(MS_MISCERR, "Unknown or unsupported layer type.",
457 458 459 460 461 462 463 464 465 466
                 "msOGRLayerNextShape()");
      nStatus = MS_FAILURE;
  } /* switch layertype */

  return nStatus;
}

/**********************************************************************
 *                     msOGRGeometryToShape()
 *
467
 * Utility function to convert from OGR geometry to a mapserver shape
468 469 470 471 472
 * object.
 **********************************************************************/
int msOGRGeometryToShape(OGRGeometryH hGeometry, shapeObj *psShape,
                         OGRwkbGeometryType nType)
{
473 474 475 476 477 478 479
  if (hGeometry && psShape && nType > 0) {
    if (nType == wkbPoint || nType == wkbMultiPoint )
      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POINT);
    else if (nType == wkbLineString || nType == wkbMultiLineString)
      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_LINE);
    else if (nType == wkbPolygon || nType == wkbMultiPolygon)
      return ogrConvertGeometry(hGeometry, psShape,  MS_LAYER_POLYGON);
480
    else
481 482 483
      return MS_FAILURE;
  } else
    return MS_FAILURE;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
}


/* ==================================================================
 * Attributes handling functions
 * ================================================================== */

// Special field index codes for handling text string and angle coming from
// OGR style strings.
#define MSOGR_LABELNUMITEMS        21
#define MSOGR_LABELFONTNAMENAME    "OGR:LabelFont"
#define MSOGR_LABELFONTNAMEINDEX   -100
#define MSOGR_LABELSIZENAME        "OGR:LabelSize"
#define MSOGR_LABELSIZEINDEX       -101
#define MSOGR_LABELTEXTNAME        "OGR:LabelText"
#define MSOGR_LABELTEXTINDEX       -102
#define MSOGR_LABELANGLENAME       "OGR:LabelAngle"
#define MSOGR_LABELANGLEINDEX      -103
#define MSOGR_LABELFCOLORNAME      "OGR:LabelFColor"
#define MSOGR_LABELFCOLORINDEX     -104
#define MSOGR_LABELBCOLORNAME      "OGR:LabelBColor"
#define MSOGR_LABELBCOLORINDEX     -105
#define MSOGR_LABELPLACEMENTNAME   "OGR:LabelPlacement"
#define MSOGR_LABELPLACEMENTINDEX  -106
#define MSOGR_LABELANCHORNAME      "OGR:LabelAnchor"
#define MSOGR_LABELANCHORINDEX     -107
#define MSOGR_LABELDXNAME          "OGR:LabelDx"
#define MSOGR_LABELDXINDEX         -108
#define MSOGR_LABELDYNAME          "OGR:LabelDy"
#define MSOGR_LABELDYINDEX         -109
#define MSOGR_LABELPERPNAME        "OGR:LabelPerp"
#define MSOGR_LABELPERPINDEX       -110
#define MSOGR_LABELBOLDNAME        "OGR:LabelBold"
#define MSOGR_LABELBOLDINDEX       -111
#define MSOGR_LABELITALICNAME      "OGR:LabelItalic"
#define MSOGR_LABELITALICINDEX     -112
#define MSOGR_LABELUNDERLINENAME   "OGR:LabelUnderline"
#define MSOGR_LABELUNDERLINEINDEX  -113
#define MSOGR_LABELPRIORITYNAME    "OGR:LabelPriority"
#define MSOGR_LABELPRIORITYINDEX   -114
#define MSOGR_LABELSTRIKEOUTNAME   "OGR:LabelStrikeout"
#define MSOGR_LABELSTRIKEOUTINDEX  -115
#define MSOGR_LABELSTRETCHNAME     "OGR:LabelStretch"
#define MSOGR_LABELSTRETCHINDEX    -116
#define MSOGR_LABELADJHORNAME      "OGR:LabelAdjHor"
#define MSOGR_LABELADJHORINDEX     -117
#define MSOGR_LABELADJVERTNAME     "OGR:LabelAdjVert"
#define MSOGR_LABELADJVERTINDEX    -118
#define MSOGR_LABELHCOLORNAME      "OGR:LabelHColor"
#define MSOGR_LABELHCOLORINDEX     -119
#define MSOGR_LABELOCOLORNAME      "OGR:LabelOColor"
#define MSOGR_LABELOCOLORINDEX     -120
536 537 538 539 540 541 542 543 544 545 546 547 548
// Special codes for the OGR style parameters
#define MSOGR_LABELPARAMNAME       "OGR:LabelParam"
#define MSOGR_LABELPARAMNAMELEN    14
#define MSOGR_LABELPARAMINDEX      -500
#define MSOGR_BRUSHPARAMNAME       "OGR:BrushParam"
#define MSOGR_BRUSHPARAMNAMELEN    14
#define MSOGR_BRUSHPARAMINDEX      -600
#define MSOGR_PENPARAMNAME         "OGR:PenParam"
#define MSOGR_PENPARAMNAMELEN      12
#define MSOGR_PENPARAMINDEX        -700
#define MSOGR_SYMBOLPARAMNAME      "OGR:SymbolParam"
#define MSOGR_SYMBOLPARAMNAMELEN   15
#define MSOGR_SYMBOLPARAMINDEX     -800
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

/**********************************************************************
 *                     msOGRGetValues()
 *
 * Load selected item (i.e. field) values into a char array
 *
 * Some special attribute names are used to return some OGRFeature params
 * like for instance stuff encoded in the OGRStyleString.
 * For now the following pseudo-attribute names are supported:
 *  "OGR:TextString"  OGRFeatureStyle's text string if present
 *  "OGR:TextAngle"   OGRFeatureStyle's text angle, or 0 if not set
 **********************************************************************/
static char **msOGRGetValues(layerObj *layer, OGRFeatureH hFeature)
{
  char **values;
  const char *pszValue = NULL;
  int i;

567 568
  if(layer->numitems == 0)
    return(NULL);
569 570

  if(!layer->iteminfo)  // Should not happen... but just in case!
571 572
    if (msOGRLayerInitItemInfo(layer) != MS_SUCCESS)
      return NULL;
573

574
  if((values = (char **)malloc(sizeof(char *)*layer->numitems)) == NULL) {
575 576 577 578 579 580
    msSetError(MS_MEMERR, NULL, "msOGRGetValues()");
    return(NULL);
  }

  OGRStyleMgrH  hStyleMgr = NULL;
  OGRStyleToolH hLabelStyle = NULL;
581 582 583
  OGRStyleToolH hPenStyle = NULL;
  OGRStyleToolH hBrushStyle = NULL;
  OGRStyleToolH hSymbolStyle = NULL;
584

585 586
  int *itemindexes = (int*)layer->iteminfo;

587 588 589 590 591 592 593 594 595
  for(i=0; i<layer->numitems; i++) {
    if (itemindexes[i] >= 0) {
      // Extract regular attributes
      values[i] = msStrdup(OGR_F_GetFieldAsString( hFeature, itemindexes[i]));
    } else {
      // Handle special OGR attributes coming from StyleString
      if (!hStyleMgr) {
        hStyleMgr = OGR_SM_Create(NULL);
        OGR_SM_InitFromFeature(hStyleMgr, hFeature);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
        int numParts = OGR_SM_GetPartCount(hStyleMgr, NULL);
        for(int i=0; i<numParts; i++) {
          OGRStyleToolH hStylePart = OGR_SM_GetPart(hStyleMgr, i, NULL);
          if (hStylePart) {
            if (OGR_ST_GetType(hStylePart) == OGRSTCLabel && !hLabelStyle)
              hLabelStyle = hStylePart;
            else if (OGR_ST_GetType(hStylePart) == OGRSTCPen && !hPenStyle)
              hPenStyle = hStylePart;
            else if (OGR_ST_GetType(hStylePart) == OGRSTCBrush && !hBrushStyle)
              hBrushStyle = hStylePart;
            else if (OGR_ST_GetType(hStylePart) == OGRSTCSymbol && !hSymbolStyle)
              hSymbolStyle = hStylePart;
            else {
              OGR_ST_Destroy(hStylePart);
              hStylePart =  NULL;
            }
          }
          /* Setting up the size units according to msOGRLayerGetAutoStyle*/
          if (hStylePart && layer->map)
615 616
            OGR_ST_SetUnit(hStylePart, OGRSTUPixel, 
              layer->map->cellsize*layer->map->resolution/layer->map->defresolution*72.0*39.37);
617
        }
618 619 620 621 622 623 624 625
      }
      int bDefault;
      if (itemindexes[i] == MSOGR_LABELTEXTINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelTextString,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
626
        else
627 628
          values[i] = msStrdup(pszValue);

629
        if (layer->debug >= MS_DEBUGLEVEL_VVV)
630 631 632 633 634 635 636
          msDebug(MSOGR_LABELTEXTNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELANGLEINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelAngle,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
637
        else
638 639
          values[i] = msStrdup(pszValue);

640
        if (layer->debug >= MS_DEBUGLEVEL_VVV)
641 642 643 644 645 646 647
          msDebug(MSOGR_LABELANGLENAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELSIZEINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelSize,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
648
        else
649 650
          values[i] = msStrdup(pszValue);

651
        if (layer->debug >= MS_DEBUGLEVEL_VVV)
652 653 654 655 656 657 658
          msDebug(MSOGR_LABELSIZENAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELFCOLORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelFColor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("#000000");
659
        else
660
          values[i] = msStrdup(pszValue);
661 662

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
663 664 665 666 667 668 669
          msDebug(MSOGR_LABELFCOLORNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELFONTNAMEINDEX ) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelFontName,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("Arial");
670
        else
671
          values[i] = msStrdup(pszValue);
672 673

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
674 675 676 677 678 679 680
          msDebug(MSOGR_LABELFONTNAMENAME " =       \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELBCOLORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelBColor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("#000000");
681
        else
682
          values[i] = msStrdup(pszValue);
683 684

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
685 686 687 688 689 690 691
          msDebug(MSOGR_LABELBCOLORNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELPLACEMENTINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelPlacement,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
692
        else
693
          values[i] = msStrdup(pszValue);
694 695

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
696 697 698 699 700 701 702
          msDebug(MSOGR_LABELPLACEMENTNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELANCHORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelAnchor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
703
        else
704
          values[i] = msStrdup(pszValue);
705 706

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
707 708 709 710 711 712 713
          msDebug(MSOGR_LABELANCHORNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELDXINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelDx,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
714
        else
715
          values[i] = msStrdup(pszValue);
716 717

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
718 719 720 721 722 723 724
          msDebug(MSOGR_LABELDXNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELDYINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelDy,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
725
        else
726
          values[i] = msStrdup(pszValue);
727 728

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
729 730 731 732 733 734 735
          msDebug(MSOGR_LABELDYNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELPERPINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelPerp,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
736
        else
737
          values[i] = msStrdup(pszValue);
738 739

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
740 741 742 743 744 745 746
          msDebug(MSOGR_LABELPERPNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELBOLDINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelBold,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
747
        else
748
          values[i] = msStrdup(pszValue);
749 750

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
751 752 753 754 755 756 757
          msDebug(MSOGR_LABELBOLDNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELITALICINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelItalic,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
758
        else
759
          values[i] = msStrdup(pszValue);
760 761

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
762 763 764 765 766 767 768
          msDebug(MSOGR_LABELITALICNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELUNDERLINEINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelUnderline,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
769
        else
770 771
          values[i] = msStrdup(pszValue);

772
        if (layer->debug >= MS_DEBUGLEVEL_VVV)
773 774 775 776 777 778 779
          msDebug(MSOGR_LABELUNDERLINENAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELPRIORITYINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelPriority,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
780
        else
781
          values[i] = msStrdup(pszValue);
782 783

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
784 785 786 787 788 789 790
          msDebug(MSOGR_LABELPRIORITYNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELSTRIKEOUTINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelStrikeout,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
791
        else
792
          values[i] = msStrdup(pszValue);
793 794

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
795 796 797 798 799 800 801
          msDebug(MSOGR_LABELSTRIKEOUTNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELSTRETCHINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelStretch,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("0");
802
        else
803
          values[i] = msStrdup(pszValue);
804 805

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
806 807 808 809 810 811 812
          msDebug(MSOGR_LABELSTRETCHNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELADJHORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelAdjHor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
813
        else
814
          values[i] = msStrdup(pszValue);
815 816

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
817 818 819 820 821 822 823
          msDebug(MSOGR_LABELADJHORNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELADJVERTINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelAdjVert,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
824
        else
825
          values[i] = msStrdup(pszValue);
826 827

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
828 829 830 831 832 833 834
          msDebug(MSOGR_LABELADJVERTNAME " = \"%s\"\n", values[i]);
      } else if (itemindexes[i] == MSOGR_LABELHCOLORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelHColor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
835
        else
836
          values[i] = msStrdup(pszValue);
837 838

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
          msDebug(MSOGR_LABELHCOLORNAME " = \"%s\"\n", values[i]);
      }
#if GDAL_VERSION_NUM >= 1600
      else if (itemindexes[i] == MSOGR_LABELOCOLORINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               OGRSTLabelOColor,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
        else
          values[i] = msStrdup(pszValue);

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
          msDebug(MSOGR_LABELOCOLORNAME " = \"%s\"\n", values[i]);
      }
#endif /* GDAL_VERSION_NUM >= 1600 */
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
      else if (itemindexes[i] >= MSOGR_LABELPARAMINDEX) {
        if (hLabelStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hLabelStyle,
                                               itemindexes[i] - MSOGR_LABELPARAMINDEX,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
        else
          values[i] = msStrdup(pszValue);

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
          msDebug(MSOGR_LABELPARAMNAME " = \"%s\"\n", values[i]);
      }
      else if (itemindexes[i] >= MSOGR_BRUSHPARAMINDEX) {
        if (hBrushStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hBrushStyle,
                                               itemindexes[i] - MSOGR_BRUSHPARAMINDEX,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
        else
          values[i] = msStrdup(pszValue);

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
          msDebug(MSOGR_BRUSHPARAMNAME " = \"%s\"\n", values[i]);
      }
      else if (itemindexes[i] >= MSOGR_PENPARAMINDEX) {
        if (hPenStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hPenStyle,
                                               itemindexes[i] - MSOGR_PENPARAMINDEX,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
        else
          values[i] = msStrdup(pszValue);

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
          msDebug(MSOGR_PENPARAMNAME " = \"%s\"\n", values[i]);
      }
      else if (itemindexes[i] >= MSOGR_SYMBOLPARAMINDEX) {
        if (hSymbolStyle == NULL
            || ((pszValue = OGR_ST_GetParamStr(hSymbolStyle,
                                               itemindexes[i] - MSOGR_SYMBOLPARAMINDEX,
                                               &bDefault)) == NULL))
          values[i] = msStrdup("");
        else
          values[i] = msStrdup(pszValue);

        if (layer->debug >= MS_DEBUGLEVEL_VVV)
          msDebug(MSOGR_SYMBOLPARAMNAME " = \"%s\"\n", values[i]);
      }
903
      else {
904 905 906 907 908 909 910 911
        msFreeCharArray(values,i);

        OGR_SM_Destroy(hStyleMgr);
        OGR_ST_Destroy(hLabelStyle);
        OGR_ST_Destroy(hPenStyle);
        OGR_ST_Destroy(hBrushStyle);
        OGR_ST_Destroy(hSymbolStyle);

912 913
        msSetError(MS_OGRERR,"Invalid field index!?!","msOGRGetValues()");
        return(NULL);
914
      }
915 916 917 918 919
    }
  }

  OGR_SM_Destroy(hStyleMgr);
  OGR_ST_Destroy(hLabelStyle);
920 921 922
  OGR_ST_Destroy(hPenStyle);
  OGR_ST_Destroy(hBrushStyle);
  OGR_ST_Destroy(hSymbolStyle);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939

  return(values);
}

#endif  /* USE_OGR */

#if defined(USE_OGR) || defined(USE_GDAL)

/**********************************************************************
 *                     msOGRSpatialRef2ProjectionObj()
 *
 * Init a MapServer projectionObj using an OGRSpatialRef
 * Works only with PROJECTION AUTO
 *
 * Returns MS_SUCCESS/MS_FAILURE
 **********************************************************************/
static int msOGRSpatialRef2ProjectionObj(OGRSpatialReferenceH hSRS,
940
    projectionObj *proj, int debug_flag )
941 942
{
#ifdef USE_PROJ
943
  // First flush the "auto" name from the projargs[]...
944 945
  msFreeProjection( proj );

946 947 948 949
  if (hSRS == NULL || OSRIsLocal( hSRS ) ) {
    // Dataset had no set projection or is NonEarth (LOCAL_CS)...
    // Nothing else to do. Leave proj empty and no reprojection will happen!
    return MS_SUCCESS;
950 951 952 953 954 955
  }

  // Export OGR SRS to a PROJ4 string
  char *pszProj = NULL;

  if (OSRExportToProj4( hSRS, &pszProj ) != OGRERR_NONE ||
956 957 958 959 960
      pszProj == NULL || strlen(pszProj) == 0) {
    msSetError(MS_OGRERR, "Conversion from OGR SRS to PROJ4 failed.",
               "msOGRSpatialRef2ProjectionObj()");
    CPLFree(pszProj);
    return(MS_FAILURE);
961 962 963
  }

  if( debug_flag )
964
    msDebug( "AUTO = %s\n", pszProj );
965 966

  if( msLoadProjectionString( proj, pszProj ) != 0 )
967
    return MS_FAILURE;
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

  CPLFree(pszProj);
#endif

  return MS_SUCCESS;
}
#endif // defined(USE_OGR) || defined(USE_GDAL)

/**********************************************************************
 *                     msOGCWKT2ProjectionObj()
 *
 * Init a MapServer projectionObj using an OGC WKT definition.
 * Works only with PROJECTION AUTO
 *
 * Returns MS_SUCCESS/MS_FAILURE
 **********************************************************************/

985
int msOGCWKT2ProjectionObj( const char *pszWKT,
986 987 988 989 990 991
                            projectionObj *proj,
                            int debug_flag )

{
#if defined(USE_OGR) || defined(USE_GDAL)

992 993 994 995
  OGRSpatialReferenceH        hSRS;
  char      *pszAltWKT = (char *) pszWKT;
  OGRErr  eErr;
  int     ms_result;
996

997
  hSRS = OSRNewSpatialReference( NULL );
998

999 1000 1001 1002 1003 1004
  if( !EQUALN(pszWKT,"GEOGCS",6)
      && !EQUALN(pszWKT,"PROJCS",6)
      && !EQUALN(pszWKT,"LOCAL_CS",8) )
    eErr = OSRSetFromUserInput( hSRS, pszWKT );
  else
    eErr = OSRImportFromWkt( hSRS, &pszAltWKT );
1005

1006 1007 1008 1009 1010 1011 1012 1013
  if( eErr != OGRERR_NONE ) {
    OSRDestroySpatialReference( hSRS );
    msSetError(MS_OGRERR,
               "Ingestion of WKT string '%s' failed.",
               "msOGCWKT2ProjectionObj()",
               pszWKT );
    return MS_FAILURE;
  }
1014

1015
  ms_result = msOGRSpatialRef2ProjectionObj( hSRS, proj, debug_flag );
1016

1017 1018
  OSRDestroySpatialReference( hSRS );
  return ms_result;
1019
#else
1020 1021 1022 1023
  msSetError(MS_OGRERR,
             "Not implemented since neither OGR nor GDAL is enabled.",
             "msOGCWKT2ProjectionObj()");
  return MS_FAILURE;
1024 1025 1026 1027 1028 1029 1030 1031 1032
#endif
}

/**********************************************************************
 *                     msOGRFileOpen()
 *
 * Open an OGR connection, and initialize a msOGRFileInfo.
 **********************************************************************/

1033
#ifdef USE_OGR
1034
static int bOGRDriversRegistered = MS_FALSE;
1035
#endif
1036

1037
void msOGRInitialize(void)
1038 1039

{
1040
#ifdef USE_OGR
1041 1042 1043 1044 1045
  /* ------------------------------------------------------------------
   * Register OGR Drivers, only once per execution
   * ------------------------------------------------------------------ */
  if (!bOGRDriversRegistered) {
    ACQUIRE_OGR_LOCK;
1046

1047 1048
    OGRRegisterAll();
    CPLPushErrorHandler( CPLQuietErrorHandler );
1049

1050 1051 1052 1053 1054 1055
    /* ------------------------------------------------------------------
     * Pass config option GML_FIELDTYPES=ALWAYS_STRING to OGR so that all
     * GML attributes are returned as strings to MapServer. This is most efficient
     * and prevents problems with autodetection of some attribute types.
     * ------------------------------------------------------------------ */
    CPLSetConfigOption("GML_FIELDTYPES","ALWAYS_STRING");
1056

1057 1058 1059 1060
    bOGRDriversRegistered = MS_TRUE;

    RELEASE_OGR_LOCK;
  }
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
#endif /* USE_OGR */
}

/* ==================================================================
 * The following functions closely relate to the API called from
 * maplayer.c, but are intended to be used for the tileindex or direct
 * layer access.
 * ================================================================== */

#ifdef USE_OGR

/**********************************************************************
 *                     msOGRFileOpen()
 *
 * Open an OGR connection, and initialize a msOGRFileInfo.
 **********************************************************************/

static msOGRFileInfo *
1079
msOGRFileOpen(layerObj *layer, const char *connection )
1080 1081 1082 1083 1084

{
  char *conn_decrypted = NULL;

  msOGRInitialize();
1085

1086 1087 1088 1089 1090 1091 1092
  /* ------------------------------------------------------------------
   * Make sure any encrypted token in the connection string are decrypted
   * ------------------------------------------------------------------ */
  if (connection) {
    conn_decrypted = msDecryptStringTokens(layer->map, connection);
    if (conn_decrypted == NULL)
      return NULL;  /* An error should already have been reported */
1093 1094
  }

1095 1096 1097
  /* ------------------------------------------------------------------
   * Parse connection string into dataset name, and layer name.
   * ------------------------------------------------------------------ */
1098 1099
  char *pszDSName = NULL, *pszLayerDef = NULL;

1100 1101 1102 1103 1104 1105 1106
  if( conn_decrypted == NULL ) {
    /* we don't have anything */
  } else if( layer->data != NULL ) {
    pszDSName = CPLStrdup(conn_decrypted);
    pszLayerDef = CPLStrdup(layer->data);
  } else {
    char **papszTokens = NULL;
1107

1108
    papszTokens = CSLTokenizeStringComplex( conn_decrypted, ",", TRUE, FALSE );
1109

1110 1111 1112 1113
    if( CSLCount(papszTokens) > 0 )
      pszDSName = CPLStrdup( papszTokens[0] );
    if( CSLCount(papszTokens) > 1 )
      pszLayerDef = CPLStrdup( papszTokens[1] );
1114

1115
    CSLDestroy(papszTokens);
1116 1117 1118 1119 1120 1121 1122 1123
  }

  /* Get rid of decrypted connection string. We'll use the original (not
   * decrypted) string for debug and error messages in the rest of the code.
   */
  msFree(conn_decrypted);
  conn_decrypted = NULL;

1124 1125 1126 1127 1128 1129
  if( pszDSName == NULL ) {
    msSetError(MS_OGRERR,
               "Error parsing OGR connection information in layer `%s'",
               "msOGRFileOpen()",
               layer->name?layer->name:"(null)" );
    return NULL;
1130 1131 1132
  }

  if( pszLayerDef == NULL )
1133
    pszLayerDef = CPLStrdup("0");
1134

1135 1136 1137
  /* -------------------------------------------------------------------- */
  /*      Can we get an existing connection for this layer?               */
  /* -------------------------------------------------------------------- */
1138 1139 1140 1141
  OGRDataSourceH hDS;

  hDS = (OGRDataSourceH) msConnPoolRequest( layer );

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  /* -------------------------------------------------------------------- */
  /*      If not, open now, and register this connection with the         */
  /*      pool.                                                           */
  /* -------------------------------------------------------------------- */
  if( hDS == NULL ) {
    char szPath[MS_MAXPATHLEN] = "";
    const char *pszDSSelectedName = pszDSName;

    if( layer->debug )
      msDebug("msOGRFileOpen(%s)...\n", connection);

    CPLErrorReset();
    if (msTryBuildPath3(szPath, layer->map->mappath,
                        layer->map->shapepath, pszDSName) != NULL ||
        msTryBuildPath(szPath, layer->map->mappath, pszDSName) != NULL) {
      /* Use relative path */
      pszDSSelectedName = szPath;
    }
1160

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    if( layer->debug )
      msDebug("OGROPen(%s)\n", pszDSSelectedName);

    ACQUIRE_OGR_LOCK;
    hDS = OGROpen( pszDSSelectedName, MS_FALSE, NULL );
    RELEASE_OGR_LOCK;

    if( hDS == NULL ) {
      if( strlen(CPLGetLastErrorMsg()) == 0 )
        msSetError(MS_OGRERR,
                   "Open failed for OGR connection in layer `%s'.  "
                   "File not found or unsupported format.",
                   "msOGRFileOpen()",
                   layer->name?layer->name:"(null)" );
      else
        msSetError(MS_OGRERR,
                   "Open failed for OGR connection in layer `%s'.\n%s\n",
                   "msOGRFileOpen()",
                   layer->name?layer->name:"(null)",
                   CPLGetLastErrorMsg() );
      CPLFree( pszDSName );
      CPLFree( pszLayerDef );
      return NULL;
    }
1185

1186
    msConnPoolRegister( layer, hDS, msOGRCloseConnection );
1187
  }
1188

1189 1190 1191
  CPLFree( pszDSName );
  pszDSName = NULL;

1192 1193 1194 1195
  /* ------------------------------------------------------------------
   * Find the layer selected.
   * ------------------------------------------------------------------ */

1196 1197 1198 1199 1200
  int   nLayerIndex = 0;
  OGRLayerH     hLayer = NULL;

  int  iLayer;

1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  if( EQUALN(pszLayerDef,"SELECT ",7) ) {
    ACQUIRE_OGR_LOCK;
    hLayer = OGR_DS_ExecuteSQL( hDS, pszLayerDef, NULL, NULL );
    if( hLayer == NULL ) {
      msSetError(MS_OGRERR,
                 "ExecuteSQL(%s) failed.\n%s",
                 "msOGRFileOpen()",
                 pszLayerDef, CPLGetLastErrorMsg() );
      RELEASE_OGR_LOCK;
      msConnPoolRelease( layer, hDS );
      CPLFree( pszLayerDef );
      return NULL;
    }
    RELEASE_OGR_LOCK;
    nLayerIndex = -1;
1216
  }
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230

  for( iLayer = 0; hLayer == NULL && iLayer < OGR_DS_GetLayerCount(hDS); iLayer++ ) {
    hLayer = OGR_DS_GetLayer( hDS, iLayer );
    if( hLayer != NULL
#if GDAL_VERSION_NUM >= 1800
        && EQUAL(OGR_L_GetName(hLayer),pszLayerDef) )
#else
        && EQUAL(OGR_FD_GetName( OGR_L_GetLayerDefn(hLayer) ),pszLayerDef) )
#endif
    {
      nLayerIndex = iLayer;
      break;
    } else
      hLayer = NULL;
1231 1232
  }

1233 1234 1235 1236
  if( hLayer == NULL && (atoi(pszLayerDef) > 0 || EQUAL(pszLayerDef,"0")) ) {
    nLayerIndex = atoi(pszLayerDef);
    if( nLayerIndex <  OGR_DS_GetLayerCount(hDS) )
      hLayer = OGR_DS_GetLayer( hDS, nLayerIndex );
1237 1238
  }

1239 1240 1241 1242 1243 1244 1245
  if (hLayer == NULL) {
    msSetError(MS_OGRERR, "GetLayer(%s) failed for OGR connection `%s'.",
               "msOGRFileOpen()",
               pszLayerDef, connection );
    CPLFree( pszLayerDef );
    msConnPoolRelease( layer, hDS );
    return NULL;
1246 1247
  }

1248 1249 1250
  /* ------------------------------------------------------------------
   * OK... open succeded... alloc and fill msOGRFileInfo inside layer obj
   * ------------------------------------------------------------------ */
1251 1252 1253
  msOGRFileInfo *psInfo =(msOGRFileInfo*)CPLCalloc(1,sizeof(msOGRFileInfo));

  psInfo->pszFname = CPLStrdup(OGR_DS_GetName( hDS ));
1254
  psInfo->pszLayerDef = pszLayerDef;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  psInfo->nLayerIndex = nLayerIndex;
  psInfo->hDS = hDS;
  psInfo->hLayer = hLayer;

  psInfo->nTileId = 0;
  psInfo->poCurTile = NULL;
  psInfo->rect.minx = psInfo->rect.maxx = 0;
  psInfo->rect.miny = psInfo->rect.maxy = 0;
  psInfo->last_record_index_read = -1;

  return psInfo;
}

/************************************************************************/
/*                        msOGRCloseConnection()                        */
/*                                                                      */
/*      Callback for thread pool to actually release an OGR             */
/*      connection.                                                     */
/************************************************************************/

static void msOGRCloseConnection( void *conn_handle )

{
1278
  OGRDataSourceH hDS = (OGRDataSourceH) conn_handle;
1279

1280 1281 1282
  ACQUIRE_OGR_LOCK;
  OGR_DS_Destroy( hDS );
  RELEASE_OGR_LOCK;
1283 1284 1285 1286 1287
}

/**********************************************************************
 *                     msOGRFileClose()
 **********************************************************************/
1288
static int msOGRFileClose(layerObj *layer, msOGRFileInfo *psInfo )
1289 1290
{
  if (!psInfo)
1291
    return MS_SUCCESS;
1292 1293

  if( layer->debug )
1294 1295
    msDebug("msOGRFileClose(%s,%d).\n",
            psInfo->pszFname, psInfo->nLayerIndex);
1296 1297

  CPLFree(psInfo->pszFname);
1298
  CPLFree(psInfo->pszLayerDef);
1299 1300 1301

  ACQUIRE_OGR_LOCK;
  if (psInfo->hLastFeature)
1302
    OGR_F_Destroy( psInfo->hLastFeature );
1303 1304 1305

  /* If nLayerIndex == -1 then the layer is an SQL result ... free it */
  if( psInfo->nLayerIndex == -1 )
1306
    OGR_DS_ReleaseResultSet( psInfo->hDS, psInfo->hLayer );
1307 1308 1309 1310 1311 1312 1313 1314

  // Release (potentially close) the datasource connection.
  // Make sure we aren't holding the lock when the callback may need it.
  RELEASE_OGR_LOCK;
  msConnPoolRelease( layer, psInfo->hDS );

  // Free current tile if there is one.
  if( psInfo->poCurTile != NULL )
1315
    msOGRFileClose( layer, psInfo->poCurTile );
1316 1317 1318 1319 1320

  CPLFree(psInfo);

  return MS_SUCCESS;
}
1321
#endif /* USE_OGR */
1322

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
/************************************************************************/
/*                           msOGREscapeSQLParam                        */
/************************************************************************/
static char *msOGREscapeSQLParam(layerObj *layer, const char *pszString)
{
#ifdef USE_OGR
  char* pszEscapedStr =NULL;
  if(layer && pszString && strlen(pszString) > 0) {
    char* pszEscapedOGRStr =  CPLEscapeString(pszString, strlen(pszString),
                              CPLES_SQL );
    pszEscapedStr = msStrdup(pszEscapedOGRStr);
    CPLFree(pszEscapedOGRStr);
  }
  return pszEscapedStr;
#else
  /* ------------------------------------------------------------------
   * OGR Support not included...
   * ------------------------------------------------------------------ */

  msSetError(MS_MISCERR, "OGR support is not available.",
             "msOGREscapeSQLParam()");
  return NULL;

#endif /* USE_OGR */
}

1349 1350 1351
#ifdef USE_OGR

#if 0 /*left over code from filter translation development */
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
/**********************************************************************
 *                     msOGRTranslateMsExpressionToOGRSQL()
 *
 * Tries to translate a mapserver expression to OGR SQL, and also
 * try to extract spatial filter
 **********************************************************************/
static char* msOGRTranslateMsExpressionToOGRSQL(layerObj* layer,
                                          expressionObj* psFilter,
                                          rectObj* psRect)
{
    char* msSQLExpression = NULL;
    rectObj sBBOX;
    int sBBOXValid = MS_FALSE;
    tokenListNodeObjPtr node = NULL;
    char *stresc = NULL;
    char *snippet = NULL;
    const char* strtmpl = NULL;
    int bIsIntersectRectangle = MS_FALSE;

    node = psFilter->tokens;
    while (node != NULL) {      

      switch(node->token) {

        /* literal tokens */

        case MS_TOKEN_LITERAL_NUMBER:
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + 16);
          sprintf(snippet, "%lf", node->tokenval.dblval);
          msSQLExpression = msStringConcatenate(msSQLExpression, snippet);
          msFree(snippet);
          break;
        case MS_TOKEN_LITERAL_STRING:
          stresc = msOGREscapeSQLParam(layer, node->tokenval.strval);
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(stresc));
          sprintf(snippet, "'%s'", stresc);
          msSQLExpression = msStringConcatenate(msSQLExpression, snippet);
          msFree(snippet);
          msFree(stresc);
          break;

        case MS_TOKEN_BINDING_DOUBLE:
        case MS_TOKEN_BINDING_INTEGER:
        case MS_TOKEN_BINDING_STRING:
          if(node->token == MS_TOKEN_BINDING_STRING || node->next->token == MS_TOKEN_COMPARISON_RE || node->next->token == MS_TOKEN_COMPARISON_IRE)
            strtmpl = "CAST(%s AS CHARACTER)"; /* explicit cast necessary for certain operators */
          else
            strtmpl = "%s";
          stresc = msLayerEscapePropertyName(layer, node->tokenval.bindval.item);
          snippet = (char *) msSmallMalloc(strlen(strtmpl) + strlen(stresc));
          sprintf(snippet, strtmpl, stresc);
          msSQLExpression = msStringConcatenate(msSQLExpression, snippet);
          msFree(snippet);
          msFree(stresc);
          break;

    /* spatial comparison tokens */
        case MS_TOKEN_COMPARISON_INTERSECTS:
        {
          shapeObj* shape;
          if(node->next->token != '(') goto cleanup;
          if(node->next->next->token != MS_TOKEN_BINDING_SHAPE) goto cleanup;
          if(node->next->next->next->token != ',' ) goto cleanup;
          if(node->next->next->next->next->token != MS_TOKEN_LITERAL_SHAPE ) goto cleanup;
          if(node->next->next->next->next->next->token != ')' ) goto cleanup;
          if(node->next->next->next->next->next->next->token != MS_TOKEN_COMPARISON_EQ ) goto cleanup;
          if(node->next->next->next->next->next->next->next->token != MS_TOKEN_LITERAL_BOOLEAN ) goto cleanup;
          if(node->next->next->next->next->next->next->next->tokenval.dblval != MS_TRUE) goto cleanup;

          shape = node->next->next->next->next->tokenval.shpval;
          memcpy(&sBBOX, &(shape->bounds), sizeof(rectObj));
          sBBOXValid = TRUE;
          
          if( shape->type == MS_SHAPE_POLYGON &&
              shape->numlines == 1 &&
              shape->line[0].numpoints == 5 )
          {
              if( shape->line[0].point[0].x == shape->line[0].point[1].x &&
                  shape->line[0].point[0].y == shape->line[0].point[3].y &&
                  shape->line[0].point[2].x == shape->line[0].point[3].x &&
                  shape->line[0].point[1].y == shape->line[0].point[2].y &&
                  shape->line[0].point[0].x == shape->line[0].point[4].x &&
                  shape->line[0].point[0].y == shape->line[0].point[4].y )
              {
                  bIsIntersectRectangle = MS_TRUE;
              }
          }

          node = node->next->next->next->next->next->next->next;
          if( node && node->next && node->next->token == MS_TOKEN_LOGICAL_AND )
              node = node->next;

          break;
        }

        case MS_TOKEN_COMPARISON_EQ:
        case MS_TOKEN_COMPARISON_NE:
        case MS_TOKEN_COMPARISON_GT:
        case MS_TOKEN_COMPARISON_GE:
        case MS_TOKEN_COMPARISON_LT:
        case MS_TOKEN_COMPARISON_LE:
        case MS_TOKEN_LOGICAL_AND:
        case MS_TOKEN_LOGICAL_NOT:
        case MS_TOKEN_LOGICAL_OR:
        case '(':
        case ')':
            if( node->token == MS_TOKEN_LOGICAL_AND && node->next &&
                node->next->token == MS_TOKEN_COMPARISON_INTERSECTS )
                node = node->next;
            else
                msSQLExpression = msStringConcatenate(msSQLExpression, msExpressionTokenToString(node->token));
            break;

        default:
          goto cleanup;
          break;
        }

      node = node->next;
  }
  
  if( !sBBOXValid || bIsIntersectRectangle )
  {
      /* We can translate completely the filter as a OGR expression, */
      /* so no need for msEvalExpression() to do more work */

      if (layer->debug >= MS_DEBUGLEVEL_VVV)
            msDebug("msOGRTranslateMsExpressionToOGRSQL: filter can be evaluated completely on OGR side\n");

      msFree( layer->filter.native_string );
      layer->filter.native_string = msStrdup(msSQLExpression);
  }
  
  if( sBBOXValid )
  {
      psRect->minx = MS_MAX(psRect->minx, sBBOX.minx);
      psRect->miny = MS_MAX(psRect->miny, sBBOX.miny);
      psRect->maxx = MS_MIN(psRect->maxx, sBBOX.maxx);
      psRect->maxy = MS_MAX(psRect->maxy, sBBOX.maxy);
  }

  return msSQLExpression;

cleanup:
  msFree(msSQLExpression);
  return NULL;
}
1499
#endif //0
1500

1501 1502 1503 1504 1505 1506 1507 1508
/**********************************************************************
 *                     msOGRFileWhichShapes()
 *
 * Init OGR layer structs ready for calls to msOGRFileNextShape().
 *
 * Returns MS_SUCCESS/MS_FAILURE, or MS_DONE if no shape matching the
 * layer's FILTER overlaps the selected region.
 **********************************************************************/
1509
static int msOGRFileWhichShapes(layerObj *layer, rectObj rect, msOGRFileInfo *psInfo)
1510
{
1511
  if (psInfo == NULL || psInfo->hLayer == NULL) {
1512
    msSetError(MS_MISCERR, "Assertion failed: OGR layer not opened!!!", "msOGRFileWhichShapes()");
1513 1514
    return(MS_FAILURE);
  }
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
    
  char *pszOGRFilter = NULL;

  /*
  ** Build the OGR filter from two potential sources:
  **   1) the NATIVE_FILTER processing option
  **   2) a translated MapServer layer->filter (stored in layer->native_string)
  */
  if(msLayerGetProcessingKey(layer, "NATIVE_FILTER") != NULL) {
    pszOGRFilter = msStringConcatenate(pszOGRFilter, "(");
    pszOGRFilter = msStringConcatenate(pszOGRFilter, msLayerGetProcessingKey(layer, "NATIVE_FILTER"));
    pszOGRFilter = msStringConcatenate(pszOGRFilter, ")");
    if(layer->filter.native_string) {
      pszOGRFilter = msStringConcatenate(pszOGRFilter, "AND (");
      pszOGRFilter = msStringConcatenate(pszOGRFilter, layer->filter.native_string);
      pszOGRFilter = msStringConcatenate(pszOGRFilter, ")");
    }
  } else if(layer->filter.native_string) {
    pszOGRFilter = msStringConcatenate(pszOGRFilter, "(");
    pszOGRFilter = msStringConcatenate(pszOGRFilter, layer->filter.native_string);
    pszOGRFilter = msStringConcatenate(pszOGRFilter, ")");
  }

  /* apply sortBy */
  if( layer->sortBy.nProperties > 0 ) {
    char* strOrderBy;
    char* pszLayerDef = NULL;

    strOrderBy = msLayerBuildSQLOrderBy(layer);

    if( psInfo->nLayerIndex == -1 ) {
      pszLayerDef = msStrdup(psInfo->pszLayerDef);
      if( strcasestr(psInfo->pszLayerDef, " ORDER BY ") == NULL )
        pszLayerDef = msStringConcatenate(pszLayerDef, " ORDER BY ");
      else
        pszLayerDef = msStringConcatenate(pszLayerDef, ", ");
    } else {
      const char* pszGeometryColumn;
      int i;
      pszLayerDef = msStringConcatenate(pszLayerDef, "SELECT ");
      for(i = 0; i < layer->numitems; i++) {
        if( i > 0 )
          pszLayerDef = msStringConcatenate(pszLayerDef, ", ");
        pszLayerDef = msStringConcatenate(pszLayerDef, "\"");
        pszLayerDef = msStringConcatenate(pszLayerDef, layer->items[i]);
        pszLayerDef = msStringConcatenate(pszLayerDef, "\"");
      }

      pszLayerDef = msStringConcatenate(pszLayerDef, ", ");
      pszGeometryColumn = OGR_L_GetGeometryColumn(psInfo->hLayer);
      if( pszGeometryColumn != NULL && pszGeometryColumn[0] != '\0' ) {
        pszLayerDef = msStringConcatenate(pszLayerDef, "\"");
        pszLayerDef = msStringConcatenate(pszLayerDef, pszGeometryColumn);
        pszLayerDef = msStringConcatenate(pszLayerDef, "\"");
      } else {
        /* Add ", *" so that we still have an hope to get the geometry */
        pszLayerDef = msStringConcatenate(pszLayerDef, "*");
      }
      pszLayerDef = msStringConcatenate(pszLayerDef, " FROM \"");
      pszLayerDef = msStringConcatenate(pszLayerDef, OGR_FD_GetName(OGR_L_GetLayerDefn(psInfo->hLayer)));
      pszLayerDef = msStringConcatenate(pszLayerDef, "\"");
      if( pszOGRFilter != NULL ) {
        pszLayerDef = msStringConcatenate(pszLayerDef, " WHERE ");
        pszLayerDef = msStringConcatenate(pszLayerDef, pszOGRFilter);
        msFree(pszOGRFilter);
        pszOGRFilter = NULL;
      }
      pszLayerDef = msStringConcatenate(pszLayerDef, " ORDER BY ");
    }

    pszLayerDef = msStringConcatenate(pszLayerDef, strOrderBy);
    msFree(strOrderBy);
    strOrderBy = NULL;

    if( layer->debug )
      msDebug("msOGRFileWhichShapes: SQL = %s.\n", pszLayerDef);

    /* If nLayerIndex == -1 then the layer is an SQL result ... free it */
    if( psInfo->nLayerIndex == -1 )
      OGR_DS_ReleaseResultSet( psInfo->hDS, psInfo->hLayer );
    psInfo->nLayerIndex = -1;

    ACQUIRE_OGR_LOCK;
    psInfo->hLayer = OGR_DS_ExecuteSQL( psInfo->hDS, pszLayerDef, NULL, NULL );
    RELEASE_OGR_LOCK;
    if( psInfo->hLayer == NULL ) {
      msSetError(MS_OGRERR, "ExecuteSQL(%s) failed.\n%s", "msOGRFileWhichShapes()", pszLayerDef, CPLGetLastErrorMsg());
      msFree(pszLayerDef);
      msFree(pszOGRFilter);
      return MS_FAILURE;
    }
    msFree(pszLayerDef);
  } /* end sort-by */

1609

1610 1611 1612 1613 1614 1615 1616 1617
  /* ------------------------------------------------------------------
   * Set Spatial filter... this may result in no features being returned
   * if layer does not overlap current view.
   *
   * __TODO__ We should return MS_DONE if no shape overlaps the selected
   * region and matches the layer's FILTER expression, but there is currently
   * no _efficient_ way to do that with OGR.
   * ------------------------------------------------------------------ */
1618 1619
  ACQUIRE_OGR_LOCK;

1620 1621
  if (rect.minx == rect.maxx && rect.miny == rect.maxy) {
    OGRGeometryH hSpatialFilterPoint = OGR_G_CreateGeometry( wkbPoint );
1622

1623 1624 1625 1626 1627
    OGR_G_SetPoint_2D( hSpatialFilterPoint, 0, rect.minx, rect.miny );    
    OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPoint );
    OGR_G_DestroyGeometry( hSpatialFilterPoint );
  } else if (rect.minx == rect.maxx || rect.miny == rect.maxy) {
    OGRGeometryH hSpatialFilterLine = OGR_G_CreateGeometry( wkbLineString );
1628

1629 1630 1631 1632 1633 1634 1635
    OGR_G_AddPoint_2D( hSpatialFilterLine, rect.minx, rect.miny );
    OGR_G_AddPoint_2D( hSpatialFilterLine, rect.maxx, rect.maxy );
    OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterLine );
    OGR_G_DestroyGeometry( hSpatialFilterLine );
  } else {
    OGRGeometryH hSpatialFilterPolygon = OGR_G_CreateGeometry( wkbPolygon );
    OGRGeometryH hRing = OGR_G_CreateGeometry( wkbLinearRing );
1636

1637 1638 1639 1640 1641 1642 1643 1644
    OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
    OGR_G_AddPoint_2D( hRing, rect.maxx, rect.miny);
    OGR_G_AddPoint_2D( hRing, rect.maxx, rect.maxy);
    OGR_G_AddPoint_2D( hRing, rect.minx, rect.maxy);
    OGR_G_AddPoint_2D( hRing, rect.minx, rect.miny);
    OGR_G_AddGeometryDirectly( hSpatialFilterPolygon, hRing );
    OGR_L_SetSpatialFilter( psInfo->hLayer, hSpatialFilterPolygon );
    OGR_G_DestroyGeometry( hSpatialFilterPolygon );
1645
  }
1646 1647 1648 1649

  psInfo->rect = rect;

  if (layer->debug >= MS_DEBUGLEVEL_VVV)
1650
    msDebug("msOGRFileWhichShapes: Setting spatial filter to %f %f %f %f\n", rect.minx, rect.miny, rect.maxx, rect.maxy );
1651 1652 1653 1654 1655 1656

  /* ------------------------------------------------------------------
   * Apply an attribute filter if we have one prefixed with a WHERE
   * keyword in the filter string.  Otherwise, ensure the attribute
   * filter is clear.
   * ------------------------------------------------------------------ */
1657 1658 1659 1660 1661 1662
  
  if( pszOGRFilter != NULL ) {

    if (layer->debug >= MS_DEBUGLEVEL_VVV)
      msDebug("msOGRFileWhichShapes: Setting attribute filter to %s\n", pszOGRFilter );

1663
    CPLErrorReset();
1664 1665
    if( OGR_L_SetAttributeFilter( psInfo->hLayer, pszOGRFilter ) != OGRERR_NONE ) {
      msSetError(MS_OGRERR, "SetAttributeFilter(%s) failed on layer %s.\n%s", "msOGRFileWhichShapes()", layer->filter.string+6, layer->name?layer->name:"(null)", CPLGetLastErrorMsg() );
1666
      RELEASE_OGR_LOCK;
1667
      msFree(pszOGRFilter);
1668 1669
      return MS_FAILURE;
    }
1670
    msFree(pszOGRFilter);
1671 1672
  } else
    OGR_L_SetAttributeFilter( psInfo->hLayer, NULL );
1673

1674 1675 1676
  /* ------------------------------------------------------------------
   * Reset current feature pointer
   * ------------------------------------------------------------------ */
1677 1678 1679 1680 1681 1682 1683 1684
  OGR_L_ResetReading( psInfo->hLayer );
  psInfo->last_record_index_read = -1;

  RELEASE_OGR_LOCK;

  return MS_SUCCESS;
}

1685 1686 1687 1688
/**********************************************************************
 *                     msOGRPassThroughFieldDefinitions()
 *
 * Pass the field definitions through to the layer metadata in the
1689
 * "gml_[item]_{type,width,precision}" set of metadata items for
1690 1691 1692
 * defining fields.
 **********************************************************************/

1693
static void
1694 1695 1696
msOGRPassThroughFieldDefinitions( layerObj *layer, msOGRFileInfo *psInfo )

{
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
  OGRFeatureDefnH hDefn = OGR_L_GetLayerDefn( psInfo->hLayer );
  int numitems, i;

  numitems = OGR_FD_GetFieldCount( hDefn );

  for(i=0; i<numitems; i++) {
    OGRFieldDefnH hField = OGR_FD_GetFieldDefn( hDefn, i );
    char md_item_name[256];
    char gml_width[32], gml_precision[32];
    const char *gml_type = NULL;
    const char *item = OGR_Fld_GetNameRef( hField );

    gml_width[0] = '\0';
    gml_precision[0] = '\0';

    switch( OGR_Fld_GetType( hField ) ) {
      case OFTInteger:
        gml_type = "Integer";
        if( OGR_Fld_GetWidth( hField) > 0 )
          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
        break;

1719 1720 1721 1722 1723 1724 1725 1726
#if GDAL_VERSION_MAJOR >= 2
      case OFTInteger64:
        gml_type = "Long";
        if( OGR_Fld_GetWidth( hField) > 0 )
          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
        break;
#endif

1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
      case OFTReal:
        gml_type = "Real";
        if( OGR_Fld_GetWidth( hField) > 0 )
          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
        if( OGR_Fld_GetPrecision( hField ) > 0 )
          sprintf( gml_precision, "%d", OGR_Fld_GetPrecision( hField) );
        break;

      case OFTString:
        gml_type = "Character";
        if( OGR_Fld_GetWidth( hField) > 0 )
          sprintf( gml_width, "%d", OGR_Fld_GetWidth( hField) );
        break;

      case OFTDate:
      case OFTTime:
      case OFTDateTime:
        gml_type = "Date";
        break;
1746

1747 1748 1749 1750
      default:
        gml_type = "Character";
        break;
    }