mapows.c 97.1 KB
Newer Older
1
/******************************************************************************
2
 * $Id$
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
 *
 * Project:  MapServer
 * Purpose:  OGC Web Services (WMS, WFS) support functions
 * Author:   Daniel Morissette, DM Solutions Group (morissette@dmsolutions.ca)
 *
 ******************************************************************************
 * Copyright (c) 1996-2005 Regents of the University of Minnesota.
 *
 * 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
 * The above copyright notice and this permission notice shall be included in
19 20 21 22 23 24 25 26 27 28 29 30 31
 * all copies of this Software or works derived from this Software.
 *
 * 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
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ****************************************************************************/

#include "mapserver.h"
#include "maptime.h"
32
#include "maptemplate.h"
33
#include "mapows.h"
34

35 36 37 38 39 40
#if defined(USE_LIBXML2)
#include "maplibxml2.h"
#elif defined(USE_GDAL)
#include "cpl_minixml.h"
#include "cpl_error.h"
#endif
41
#include "mapowscommon.h"
42

43
#include <ctype.h> /* isalnum() */
44
#include <stdarg.h>
45 46
#include <assert.h>

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83


/*
** msOWSInitRequestObj() initializes an owsRequestObj; i.e: sets
** all internal pointers to NULL.
*/
static void msOWSInitRequestObj(owsRequestObj *ows_request)
{
  ows_request->numlayers = 0;
  ows_request->enabled_layers = NULL;

  ows_request->service = NULL;
  ows_request->version = NULL;
  ows_request->request = NULL;
  ows_request->document = NULL;
}

/*
** msOWSClearRequestObj() releases all resources associated with an
** owsRequestObj.
*/
static void msOWSClearRequestObj(owsRequestObj *ows_request)
{
  msFree(ows_request->enabled_layers);
  msFree(ows_request->service);
  msFree(ows_request->version);
  msFree(ows_request->request);
  if(ows_request->document) {
#if defined(USE_LIBXML2)
    xmlFreeDoc(ows_request->document);
    xmlCleanupParser();
#elif defined(USE_GDAL)
    CPLDestroyXMLNode(ows_request->document);
#endif
  }
}

84
#if defined(USE_LIBXML2) && LIBXML_VERSION < 20900
85
static int bExternalEntityAsked = MS_FALSE;
86 87 88 89
static xmlParserInputPtr  dummyEntityLoader(const char * URL, 
                                           const char * ID, 
                                           xmlParserCtxtPtr context )
{
90
    bExternalEntityAsked = MS_TRUE;
91 92 93 94
    return NULL;
}
#endif

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
/*
** msOWSPreParseRequest() parses a cgiRequestObj either with GET/KVP
** or with POST/XML. Only SERVICE, VERSION (or WMTVER) and REQUEST are
** being determined, all WxS (or SOS) specific parameters are parsed
** within the according handler.
** The results are saved within an owsRequestObj. If the request was
** transmitted with POST/XML, either the document (if compiled with
** libxml2) or the root CPLXMLNode is saved to the ows_request->document
** field.
** Returns MS_SUCCESS upon success, MS_FAILURE if severe errors occurred
** or MS_DONE, if the service could not be determined.
*/
static int msOWSPreParseRequest(cgiRequestObj *request,
                                owsRequestObj *ows_request)
{
  /* decide if KVP or XML */
111 112
  if (request->type == MS_GET_REQUEST || (request->type == MS_POST_REQUEST 
    && request->contenttype && strncmp(request->contenttype, "application/x-www-form-urlencoded", strlen("application/x-www-form-urlencoded")) == 0)) {
113 114 115
    int i;
    /* parse KVP parameters service, version and request */
    for (i = 0; i < request->NumParams; ++i) {
116 117
      if (ows_request->service == NULL &&
          EQUAL(request->ParamNames[i], "SERVICE")) {
118
        ows_request->service = msStrdup(request->ParamValues[i]);
119 120 121
      } else if (ows_request->version == NULL &&
                 (EQUAL(request->ParamNames[i], "VERSION")
                 || EQUAL(request->ParamNames[i], "WMTVER"))) { /* for WMS */
122
        ows_request->version = msStrdup(request->ParamValues[i]);
123 124
      } else if (ows_request->request == NULL &&
                 EQUAL(request->ParamNames[i], "REQUEST")) {
125 126 127 128 129 130 131 132 133 134 135
        ows_request->request = msStrdup(request->ParamValues[i]);
      }

      /* stop if we have all necessary parameters */
      if(ows_request->service && ows_request->version && ows_request->request) {
        break;
      }
    }
  } else if (request->type == MS_POST_REQUEST) {
#if defined(USE_LIBXML2)
    xmlNodePtr root = NULL;
136 137 138
#if LIBXML_VERSION < 20900
    xmlExternalEntityLoader oldExternalEntityLoader;
#endif
139 140 141 142 143 144 145 146 147
#elif defined(USE_GDAL)
    CPLXMLNode *temp;
#endif
    if (!request->postrequest || !strlen(request->postrequest)) {
      msSetError(MS_OWSERR, "POST request is empty.",
                 "msOWSPreParseRequest()");
      return MS_FAILURE;
    }
#if defined(USE_LIBXML2)
148 149 150 151
#if LIBXML_VERSION < 20900
    oldExternalEntityLoader = xmlGetExternalEntityLoader();
    /* to avoid  XML External Entity vulnerability with libxml2 < 2.9 */
    xmlSetExternalEntityLoader (dummyEntityLoader); 
152
    bExternalEntityAsked = MS_FALSE;
153
#endif
154 155 156
    /* parse to DOM-Structure with libxml2 and get the root element */
    ows_request->document = xmlParseMemory(request->postrequest,
                                           strlen(request->postrequest));
157 158 159 160 161 162 163 164 165
#if LIBXML_VERSION < 20900
    xmlSetExternalEntityLoader (oldExternalEntityLoader); 
    if( bExternalEntityAsked )
    {
        msSetError(MS_OWSERR, "XML parsing error: %s",
                 "msOWSPreParseRequest()", "External entity fetch");
        return MS_FAILURE;
    }
#endif
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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    if (ows_request->document == NULL
        || (root = xmlDocGetRootElement(ows_request->document)) == NULL) {
      xmlErrorPtr error = xmlGetLastError();
      msSetError(MS_OWSERR, "XML parsing error: %s",
                 "msOWSPreParseRequest()", error->message);
      return MS_FAILURE;
    }

    /* Get service, version and request from root */
    ows_request->service = (char *) xmlGetProp(root, BAD_CAST "service");
    ows_request->version = (char *) xmlGetProp(root, BAD_CAST "version");
    ows_request->request = msStrdup((char *) root->name);

#elif defined(USE_GDAL)
    /* parse with CPLXML */
    ows_request->document = CPLParseXMLString(request->postrequest);
    if (ows_request->document == NULL) {
      msSetError(MS_OWSERR, "XML parsing error: %s",
                 "msOWSPreParseRequest()", CPLGetLastErrorMsg());
      return MS_FAILURE;
    }

    /* remove all namespaces */
    CPLStripXMLNamespace(ows_request->document, NULL, 1);
    for (temp = ows_request->document;
         temp != NULL;
         temp = temp->psNext) {

      if (temp->eType == CXT_Element) {
        const char *service, *version;
        ows_request->request = msStrdup(temp->pszValue);

        if ((service = CPLGetXMLValue(temp, "service", NULL)) != NULL) {
          ows_request->service = msStrdup(service);
        }
        if ((version = CPLGetXMLValue(temp, "version", NULL)) != NULL) {
          ows_request->version = msStrdup(version);
        }
        continue;
      }
    }
#else
    /* could not parse XML since no parser was compiled */
    msSetError(MS_OWSERR, "Could not parse the POST XML since MapServer"
               "was not compiled with libxml2 or GDAL.",
               "msOWSPreParseRequest()");
    return MS_FAILURE;
#endif /* defined(USE_LIBXML2) */
  } else {
    msSetError(MS_OWSERR, "Unknown request method. Use either GET or POST.",
               "msOWSPreParseRequest()");
    return MS_FAILURE;
  }

  /* certain WMS requests do not require the service parameter */
  /* see: http://trac.osgeo.org/mapserver/ticket/2531          */
  if (ows_request->service == NULL
      && ows_request->request != NULL) {
    if (EQUAL(ows_request->request, "GetMap")
        || EQUAL(ows_request->request, "GetFeatureInfo")) {
      ows_request->service = msStrdup("WMS");
    } else { /* service could not be determined */
      return MS_DONE;
    }
  }

  return MS_SUCCESS;
}
234 235 236 237 238 239 240

/*
** msOWSDispatch() is the entry point for any OWS request (WMS, WFS, ...)
** - If this is a valid request then it is processed and MS_SUCCESS is returned
**   on success, or MS_FAILURE on failure.
** - If force_ows_mode is true then an exception will be produced if the
**   request is not recognized as a valid request.
241 242
** - If force_ows_mode is false and this does not appear to be a valid OWS
**   request then MS_DONE is returned and MapServer is expected to process
243 244
**   this as a regular MapServer (traditional CGI) request.
*/
245
int msOWSDispatch(mapObj *map, cgiRequestObj *request, int ows_mode)
246
{
247 248
  int status = MS_DONE, force_ows_mode = 0;
  owsRequestObj ows_request;
249

250 251 252
  if (!request) {
    return status;
  }
253

254
  force_ows_mode = (ows_mode == OWS || ows_mode == WFS);
255

256 257 258 259 260 261 262 263 264 265 266
  msOWSInitRequestObj(&ows_request);
  switch(msOWSPreParseRequest(request, &ows_request)) {
    case MS_FAILURE: /* a severe error occurred */
      return MS_FAILURE;
    case MS_DONE:
      /* OWS Service could not be determined              */
      /* continue for now                                 */
      status = MS_DONE;
  }

  if (ows_request.service == NULL) {
267 268 269 270 271
    if (ows_request.request && EQUAL(ows_request.request, "GetMetadata")) {
      status = msMetadataDispatch(map, request, &ows_request);
      msOWSClearRequestObj(&ows_request);
      return status;
    }
272 273 274 275 276 277 278
#ifdef USE_WFS_SVR
    if( msOWSLookupMetadata(&(map->web.metadata), "FO", "cite_wfs2") != NULL ) {
      status = msWFSException(map, "service", MS_OWS_ERROR_MISSING_PARAMETER_VALUE, NULL );
    }
    else
#endif

279 280 281 282 283 284 285 286
    /* exit if service is not set */
    if(force_ows_mode) {
      msSetError( MS_MISCERR,
                  "OWS Common exception: exceptionCode=MissingParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter missing.",
                  "msOWSDispatch()");
      status = MS_FAILURE;
    } else {
      status = MS_DONE;
287
    }
288 289 290
  } else if (EQUAL(ows_request.service, "WMS")) {
#ifdef USE_WMS_SVR
    status = msWMSDispatch(map, request, &ows_request, MS_FALSE);
291
#else
292 293 294
    msSetError( MS_WMSERR,
                "SERVICE=WMS requested, but WMS support not configured in MapServer.",
                "msOWSDispatch()" );
295
#endif
296
  } else if (EQUAL(ows_request.service, "WFS")) {
297
#ifdef USE_WFS_SVR
298
    status = msWFSDispatch(map, request, &ows_request, (ows_mode == WFS));
299
#else
300 301 302
    msSetError( MS_WFSERR,
                "SERVICE=WFS requested, but WFS support not configured in MapServer.",
                "msOWSDispatch()" );
303
#endif
304
  } else if (EQUAL(ows_request.service, "WCS")) {
305
#ifdef USE_WCS_SVR
306
    status = msWCSDispatch(map, request, &ows_request);
307
#else
308 309 310
    msSetError( MS_WCSERR,
                "SERVICE=WCS requested, but WCS support not configured in MapServer.",
                "msOWSDispatch()" );
311
#endif
312
  } else if (EQUAL(ows_request.service, "SOS")) {
313
#ifdef USE_SOS_SVR
314
    status = msSOSDispatch(map, request, &ows_request);
315
#else
316 317 318
    msSetError( MS_SOSERR,
                "SERVICE=SOS requested, but SOS support not configured in MapServer.",
                "msOWSDispatch()" );
319
#endif
320 321 322 323 324 325
  } else if(force_ows_mode) {
    msSetError( MS_MISCERR,
                "OWS Common exception: exceptionCode=InvalidParameterValue, locator=SERVICE, ExceptionText=SERVICE parameter value invalid.",
                "msOWSDispatch()");
    status = MS_FAILURE;
  }
326

327 328
  msOWSClearRequestObj(&ows_request);
  return status;
329 330
}

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 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 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 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
/*
** msOWSIpParse()
**
** Parse the IP address or range into a binary array.
** Supports ipv4 and ipv6 addresses
** Ranges can be specified using the CIDR notation (ie: 192.100.100.0/24)
**
** Returns the parsed of the IP (4 or 16).
*/
int msOWSIpParse(const char* ip, unsigned char* ip1, unsigned char* mask)
{
  int len = 0, masklen, seps;
  
  if (msCountChars((char*)ip, '.') == 3) {
    /* ipv4 */
    unsigned char* val = ip1;
    len = 1;
    masklen = 32;
    *val = 0;
    while (*ip) {
      if (*ip >= '0' && *ip <= '9')
        (*val) = 10 * (*val) + (*ip - '0');
      else if (*ip == '.') {
        ++val;
        *val = 0;
        ++len;
      }
      else if (*ip == '/')
      {
        masklen = atoi(ip+1);
        if (masklen > 32)
          masklen = 32;
        break;
      }
      else 
        break;
      ++ip;
    }
    if (len != 4)
      return 0;
    /* write mask */
    if (mask) {
      memset(mask, 0, len);
      val = mask;
      while (masklen) {
        if (masklen >= 8) {
          *val = 0xff;
          masklen -= 8;
        }
        else {
          *val = - ((unsigned char)pow(2, 8 - masklen));
          break;
        }
        ++val;
      }
    }
  }
  else if ((seps = msCountChars((char*)ip, ':')) > 1 && seps < 8) {
    /* ipv6 */
    unsigned short* val = (unsigned short*)ip1;
    len = 2;
    masklen = 128;
    *val = 0;
    while (*ip) {
      if (*ip >= '0' && *ip <= '9')
        (*val) = 16 * (*val) + (*ip - '0');
      else if (*ip >= 'a' && *ip <= 'f')
        (*val) = 16 * (*val) + (*ip - 'a' + 10);
      else if (*ip >= 'A' && *ip <= 'F')
        (*val) = 16 * (*val) + (*ip - 'A' + 10);
      else if (*ip == ':') {
        ++ip;
        ++val;
        len += 2;
        *val = 0;
        if (*ip == ':') {
          /* insert 0 values */
          while (seps <= 7) {
            ++val;
            len += 2;
            *val = 0;
            ++seps;
          }
        }
        else
          continue;
      }
      else if (*ip == '/')
      {
        masklen = atoi(ip+1);
        if (masklen > 128)
          masklen = 128;
        break;
      }
      else
        break;
      ++ip;
    }
    if (len != 16)
      return 0;
    /* write mask */
    if (mask) {
      memset(mask, 0, len);
      val = (unsigned short*)mask;
      while (masklen) {
        if (masklen >= 16) {
          *val = 0xffff;
          masklen -= 16;
        }
        else {
          *val = - ((unsigned short)pow(2, 16 - masklen));
          break;
        }
        ++val;
      }
    }
  }

  return len;
}

/*
** msOWSIpInList()
**
** Check if an ip is in a space separated list of IP addresses/ranges.
** Supports ipv4 and ipv6 addresses
** Ranges can be specified using the CIDR notation (ie: 192.100.100.0/24)
**
** Returns MS_TRUE if the IP is found.
*/
int msOWSIpInList(const char *ip_list, const char* ip)
{
  int i, j, numips, iplen;
  unsigned char ip1[16];
  unsigned char ip2[16];
  unsigned char mask[16];
  char** ips;

  /* Parse input IP */
  iplen = msOWSIpParse(ip, (unsigned char*)&ip1, NULL);
  if (iplen != 4 && iplen != 16) /* ipv4 or ipv6 */
    return MS_FALSE;

  ips = msStringSplit(ip_list, ' ', &numips);
  if (ips) {
    for (i = 0; i < numips; i++) {
      if (msOWSIpParse(ips[i], (unsigned char*)&ip2, (unsigned char*)&mask) == iplen)
      {
        for (j = 0; j < iplen; j++) {
          if ((ip1[j] & mask[j]) != (ip2[j] & mask[j]))
            break;
        }
        if (j == iplen) {
          msFreeCharArray(ips, numips);
          return MS_TRUE; /* match found */
        }
      }
    }
    msFreeCharArray(ips, numips);
  }

  return MS_FALSE;
}

/*
** msOWSIpDisabled()
**
** Check if an ip is in a list specified in the metadata section.
**
** Returns MS_TRUE if the IP is found.
*/
int msOWSIpInMetadata(const char *ip_list, const char* ip)
{
  FILE *stream;
  char buffer[MS_BUFFER_LENGTH];
  int found = MS_FALSE;
  
  if (strncasecmp(ip_list, "file:", 5) == 0) {
    stream = fopen(ip_list + 5, "r");
    if(stream) {
      found = MS_FALSE;
      while(fgets(buffer, MS_BUFFER_LENGTH, stream)) {
        if(msOWSIpInList(buffer, ip)) {
          found = MS_TRUE;
          break;
        }
      }
      fclose(stream);
    }  
  }
  else {
    if(msOWSIpInList(ip_list, ip))
      found = MS_TRUE;
  }  
  return found;
}

/*
** msOWSIpDisabled()
**
** Check if the layers are enabled or disabled by IP list.
**
** 'namespaces' is a string with a letter for each namespace to lookup
** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
** If namespaces is NULL then this function just does a regular metadata
** lookup.
**
** Returns the disabled flag.
*/
int msOWSIpDisabled(hashTableObj *metadata, const char *namespaces, const char* ip)
{
  const char *ip_list;
  int disabled = MS_FALSE;

  if (!ip)
    return MS_FALSE; /* no endpoint ip */

  ip_list = msOWSLookupMetadata(metadata, namespaces, "allowed_ip_list");
  if (!ip_list)
    ip_list = msOWSLookupMetadata(metadata, "O", "allowed_ip_list");

  if (ip_list) {
    disabled = MS_TRUE;
    if (msOWSIpInMetadata(ip_list, ip))
      disabled = MS_FALSE;
  }

  ip_list = msOWSLookupMetadata(metadata, namespaces, "denied_ip_list");
  if (!ip_list)
    ip_list = msOWSLookupMetadata(metadata, "O", "denied_ip_list");

  if (ip_list && msOWSIpInMetadata(ip_list, ip))
    disabled = MS_TRUE;

  return disabled;
}

568 569 570 571 572 573 574 575 576 577
/*
** msOWSRequestIsEnabled()
**
** Check if a layer is visible for a specific OWS request.
**
** 'namespaces' is a string with a letter for each namespace to lookup in
** the order they should be looked up. e.g. "MO" to lookup wms_ and ows_ If
** namespaces is NULL then this function just does a regular metadata
** lookup. If check_all_layers is set to MS_TRUE, the function will check
** all layers to see if the request is enable. (returns as soon as one is found) */
578
int msOWSRequestIsEnabled(mapObj *map, layerObj *layer,
579 580
                          const char *namespaces, const char *request, int check_all_layers)
{
581 582
  int disabled = MS_FALSE; /* explicitly disabled flag */
  const char *enable_request;
583
  const char *remote_ip;
584 585 586 587

  if (request == NULL)
    return MS_FALSE;

588 589
  remote_ip = getenv("REMOTE_ADDR");

590 591 592 593 594 595 596 597 598 599 600
  /* First, we check in the layer metadata */
  if (layer && check_all_layers == MS_FALSE) {
    enable_request = msOWSLookupMetadata(&layer->metadata, namespaces, "enable_request");
    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
      return MS_TRUE;
    if (disabled) return MS_FALSE;

    enable_request = msOWSLookupMetadata(&layer->metadata, "O", "enable_request");
    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
      return MS_TRUE;
    if (disabled) return MS_FALSE;
601 602 603

    if (msOWSIpDisabled(&layer->metadata, namespaces, remote_ip))
      return MS_FALSE;
604 605
  }

606
  if (map && (check_all_layers == MS_FALSE || map->numlayers == 0)) {
607 608 609 610 611
    /* then we check in the map metadata */
    enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
      return MS_TRUE;
    if (disabled) return MS_FALSE;
612

613 614 615 616
    enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
    if (msOWSParseRequestMetadata(enable_request, request, &disabled))
      return MS_TRUE;
    if (disabled) return MS_FALSE;
617 618 619

    if (msOWSIpDisabled(&map->web.metadata, namespaces, remote_ip))
      return MS_FALSE;
620 621
  }

622
  if (map && check_all_layers == MS_TRUE) {
623 624 625 626 627 628 629
    int i, globally_enabled = MS_FALSE;
    enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
    globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);

    if (!globally_enabled && !disabled) {
      enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
      globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
630 631
    }

632 633 634
    if (globally_enabled && msOWSIpDisabled(&map->web.metadata, namespaces, remote_ip))
      globally_enabled = MS_FALSE;

635 636 637 638 639
    /* Check all layers */
    for(i=0; i<map->numlayers; i++) {
      int result = MS_FALSE;
      layerObj *lp;
      lp = (GET_LAYER(map, i));
640

641 642 643 644 645 646 647 648 649 650 651 652
      enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
      result = msOWSParseRequestMetadata(enable_request, request, &disabled);
      if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */

      if (!result && !disabled) { /* if the request has not been found in the wms metadata, */
        /* check the ows namespace  */

        enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
        result = msOWSParseRequestMetadata(enable_request, request, &disabled);
        if (!result && disabled) continue;
      }

653 654 655
      if (msOWSIpDisabled(&lp->metadata, namespaces, remote_ip))
        continue;

656 657
      if (result || (!disabled && globally_enabled))
        return MS_TRUE;
658
    }
659 660 661

    if (!disabled && globally_enabled)
        return MS_TRUE;
662
  }
663

664
  return MS_FALSE;
665 666 667 668 669 670 671
}

/*
** msOWSRequestLayersEnabled()
**
** Check if the layers are visible for a specific OWS request.
**
672
** 'namespaces' is a string with a letter for each namespace to lookup
673 674 675 676 677 678
** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
** If namespaces is NULL then this function just does a regular metadata
** lookup.
**
** Generates an array of the layer ids enabled.
*/
679
void msOWSRequestLayersEnabled(mapObj *map, const char *namespaces,
680 681
                               const char *request, owsRequestObj *ows_request)
{
682 683 684
  int disabled = MS_FALSE; /* explicitly disabled flag */
  int globally_enabled = MS_FALSE;
  const char *enable_request;
685
  const char *remote_ip;
686

687 688
  if (ows_request->numlayers > 0)
    msFree(ows_request->enabled_layers);
689

690 691
  ows_request->numlayers = 0;
  ows_request->enabled_layers = NULL;
692

693 694 695
  if (request == NULL || (map == NULL) || (map->numlayers <= 0))
    return;

696 697
  remote_ip = getenv("REMOTE_ADDR");

698 699 700 701 702
  enable_request = msOWSLookupMetadata(&map->web.metadata, namespaces, "enable_request");
  globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);

  if (!globally_enabled && !disabled) {
    enable_request = msOWSLookupMetadata(&map->web.metadata, "O", "enable_request");
703
    globally_enabled = msOWSParseRequestMetadata(enable_request, request, &disabled);
704
  }
705

706 707 708
  if (globally_enabled && msOWSIpDisabled(&map->web.metadata, namespaces, remote_ip))
      globally_enabled = MS_FALSE;

709 710
  if (map->numlayers) {
    int i, layers_size = map->numlayers; /* for most of cases, this will be relatively small */
711

712
    ows_request->enabled_layers = (int*)msSmallMalloc(sizeof(int)*layers_size);
713

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    for(i=0; i<map->numlayers; i++) {
      int result = MS_FALSE;
      layerObj *lp;
      lp = (GET_LAYER(map, i));

      enable_request = msOWSLookupMetadata(&lp->metadata, namespaces, "enable_request");
      result = msOWSParseRequestMetadata(enable_request, request, &disabled);
      if (!result && disabled) continue; /* if the request has been explicitly set to disabled, continue */

      if (!result && !disabled) { /* if the request has not been found in the wms metadata, */
        /* check the ows namespace  */

        enable_request = msOWSLookupMetadata(&lp->metadata, "O", "enable_request");
        result = msOWSParseRequestMetadata(enable_request, request, &disabled);
        if (!result && disabled) continue;
      }

731 732 733
      if (msOWSIpDisabled(&lp->metadata, namespaces, remote_ip))
          continue;

734 735 736 737 738 739 740 741 742
      if (result || (!disabled && globally_enabled)) {
        ows_request->enabled_layers[ows_request->numlayers] = lp->index;
        ows_request->numlayers++;
      }
    }

    if (ows_request->numlayers == 0) {
      msFree(ows_request->enabled_layers);
      ows_request->enabled_layers = NULL;
743
    }
744
  }
745 746
}

747 748
/* msOWSParseRequestMetadata
 *
749 750 751 752 753
 * This function parse a enable_request metadata string and check if the
 * given request is present and enabled.
 */
int msOWSParseRequestMetadata(const char *metadata, const char *request, int *disabled)
{
754 755 756 757 758 759 760
  char requestBuffer[32];
  int wordFlag = MS_FALSE;
  int disableFlag = MS_FALSE;
  int allFlag = MS_FALSE;
  char *bufferPtr, *ptr = NULL;
  int i;
  size_t len = 0;
761

762
  *disabled = MS_FALSE;
763

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
  if (metadata == NULL)
    return MS_FALSE;

  ptr = (char*)metadata;
  len = strlen(ptr);
  requestBuffer[0] = '\0';
  bufferPtr = requestBuffer;

  for (i=0; i<=len; ++i,++ptr) {

    if (!wordFlag && isspace(*ptr))
      continue;

    wordFlag = MS_TRUE;

    if (*ptr == '!') {
      disableFlag = MS_TRUE;
      continue;
    } else if ( (*ptr == ' ') || (*ptr != '\0' && ptr[1] == '\0')) { /* end of word */
      if (ptr[1] == '\0' && *ptr != ' ') {
        *bufferPtr = *ptr;
        ++bufferPtr;
      }

      *bufferPtr = '\0';
      if (strcasecmp(request, requestBuffer) == 0) {
        *disabled =  MS_TRUE; /* explicitly found, will stop the process in msOWSRequestIsEnabled() */
        return (disableFlag ? MS_FALSE:MS_TRUE);
      } else {
        if (strcmp("*", requestBuffer) == 0) { /* check if we read the all flag */
          if (disableFlag)
            *disabled =  MS_TRUE;
          allFlag = disableFlag ? MS_FALSE:MS_TRUE;
797
        }
798 799 800 801 802 803 804 805
        /* reset flags */
        wordFlag = MS_FALSE;
        disableFlag = MS_FALSE;
        bufferPtr = requestBuffer;
      }
    } else {
      *bufferPtr = *ptr;
      ++bufferPtr;
806
    }
807 808 809
  }

  return allFlag;
810 811
}

812 813 814 815 816
/*
** msOWSLookupMetadata()
**
** Attempts to lookup a given metadata name in multiple OWS namespaces.
**
817
** 'namespaces' is a string with a letter for each namespace to lookup
818 819 820 821
** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
** If namespaces is NULL then this function just does a regular metadata
** lookup.
*/
822
const char *msOWSLookupMetadata(hashTableObj *metadata,
823 824
                                const char *namespaces, const char *name)
{
825
  const char *value = NULL;
826

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  if (namespaces == NULL) {
    value = msLookupHashTable(metadata, (char*)name);
  } else {
    char buf[100] = "ows_";

    strlcpy(buf+4, name, 96);

    while (value == NULL && *namespaces != '\0') {
      switch (*namespaces) {
        case 'O':         /* ows_... */
          buf[0] = 'o';
          buf[1] = 'w';
          buf[2] = 's';
          break;
        case 'M':         /* wms_... */
          buf[0] = 'w';
          buf[1] = 'm';
          buf[2] = 's';
          break;
        case 'F':         /* wfs_... */
          buf[0] = 'w';
          buf[1] = 'f';
          buf[2] = 's';
          break;
        case 'C':         /* wcs_... */
          buf[0] = 'w';
          buf[1] = 'c';
          buf[2] = 's';
          break;
        case 'G':         /* gml_... */
          buf[0] = 'g';
          buf[1] = 'm';
          buf[2] = 'l';
          break;
        case 'S':         /* sos_... */
          buf[0] = 's';
          buf[1] = 'o';
          buf[2] = 's';
          break;
        default:
          /* We should never get here unless an invalid code (typo) is */
          /* present in the code, but since this happened before... */
          msSetError(MS_WMSERR,
                     "Unsupported metadata namespace code (%c).",
                     "msOWSLookupMetadata()", *namespaces );
          assert(MS_FALSE);
          return NULL;
      }

      value = msLookupHashTable(metadata, buf);
      namespaces++;
878
    }
879
  }
880

881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  return value;
}


/*
** msOWSLookupMetadataWithLanguage()
**
** Attempts to lookup a given metadata name in multiple OWS namespaces
** for a specific language.
*/
const char *msOWSLookupMetadataWithLanguage(hashTableObj *metadata,
    const char *namespaces, const char *name, const char* validated_language)
{
  const char *value = NULL;

  if ( name && validated_language ) {
897 898
    size_t bufferSize = strlen(name)+strlen(validated_language)+2;
    char *name2 = (char *) msSmallMalloc( bufferSize );
899 900
    snprintf(name2, bufferSize, "%s.%s", name, validated_language);
    value = msOWSLookupMetadata(metadata, namespaces, name2);
901
    free(name2);
902 903
  }

904
  if ( name && !value ) {
905 906 907 908 909
    value = msOWSLookupMetadata(metadata, namespaces, name);
  }


  return value;
910 911 912 913 914 915 916
}

/*
** msOWSLookupMetadata2()
**
** Attempts to lookup a given metadata name in multiple hashTables, and
** in multiple OWS namespaces within each. First searches the primary
917
** table and if no result is found, attempts the search using the
918 919
** secondary (fallback) table.
**
920
** 'namespaces' is a string with a letter for each namespace to lookup
921 922 923 924 925
** in the order they should be looked up. e.g. "MO" to lookup wms_ and ows_
** If namespaces is NULL then this function just does a regular metadata
** lookup.
*/
const char *msOWSLookupMetadata2(hashTableObj *pri,
926 927 928
                                 hashTableObj *sec,
                                 const char *namespaces,
                                 const char *name)
929
{
930
  const char *result;
931

932 933 934 935 936 937
  if ((result = msOWSLookupMetadata(pri, namespaces, name)) == NULL) {
    /* Try the secondary table */
    result = msOWSLookupMetadata(sec, namespaces, name);
  }

  return result;
938 939 940
}


941 942 943 944 945
/* msOWSParseVersionString()
**
** Parse a version string in the format "a.b.c" or "a.b" and return an
** integer in the format 0x0a0b0c suitable for regular integer comparisons.
**
946
** Returns one of OWS_VERSION_NOTSET or OWS_VERSION_BADFORMAT if version
947 948 949 950
** could not be parsed.
*/
int msOWSParseVersionString(const char *pszVersion)
{
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
  char **digits = NULL;
  int numDigits = 0;

  if (pszVersion) {
    int nVersion = 0;
    digits = msStringSplit(pszVersion, '.', &numDigits);
    if (digits == NULL || numDigits < 2 || numDigits > 3) {
      msSetError(MS_OWSERR,
                 "Invalid version (%s). Version must be in the "
                 "format 'x.y' or 'x.y.z'",
                 "msOWSParseVersionString()", pszVersion);
      if (digits)
        msFreeCharArray(digits, numDigits);
      return OWS_VERSION_BADFORMAT;
    }
966

967 968 969 970
    nVersion = atoi(digits[0])*0x010000;
    nVersion += atoi(digits[1])*0x0100;
    if (numDigits > 2)
      nVersion += atoi(digits[2]);
971

972
    msFreeCharArray(digits, numDigits);
973

974 975
    return nVersion;
  }
976

977
  return OWS_VERSION_NOTSET;
978 979 980 981 982 983 984 985 986 987 988 989 990
}

/* msOWSGetVersionString()
**
** Returns a OWS version string in the format a.b.c from the integer
** version value passed as argument (0x0a0b0c)
**
** Fills in the pszBuffer and returns a reference to it. Recommended buffer
** size is OWS_VERSION_MAXLEN chars.
*/
const char *msOWSGetVersionString(int nVersion, char *pszBuffer)
{

991 992 993
  if (pszBuffer)
    snprintf(pszBuffer, OWS_VERSION_MAXLEN-1, "%d.%d.%d",
             (nVersion/0x10000)%0x100, (nVersion/0x100)%0x100, nVersion%0x100);
994

995
  return pszBuffer;
996 997 998
}


999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
#if defined(USE_WMS_SVR) || defined (USE_WFS_SVR) || defined (USE_WCS_SVR) || defined(USE_SOS_SVR) || defined(USE_WMS_LYR) || defined(USE_WFS_LYR)

#if !defined(USE_PROJ)
#error "PROJ.4 is required for WMS, WFS, WCS and SOS Server Support."
#endif

/*
** msRenameLayer()
*/
static int msRenameLayer(layerObj *lp, int count)
{
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  char *newname;
  newname = (char*)malloc((strlen(lp->name)+5)*sizeof(char));
  if (!newname) {
    msSetError(MS_MEMERR, NULL, "msRenameLayer()");
    return MS_FAILURE;
  }
  sprintf(newname, "%s_%2.2d", lp->name, count);
  free(lp->name);
  lp->name = newname;

  return MS_SUCCESS;
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
}

/*
** msOWSMakeAllLayersUnique()
*/
int msOWSMakeAllLayersUnique(mapObj *map)
{
  int i, j;

  /* Make sure all layers in the map file have valid and unique names */
1031 1032 1033 1034 1035
  for(i=0; i<map->numlayers; i++) {
    int count=1;
    for(j=i+1; j<map->numlayers; j++) {
      if (GET_LAYER(map, i)->name == NULL || GET_LAYER(map, j)->name == NULL) {
        continue;
1036
      }
1037 1038 1039
      if (strcasecmp(GET_LAYER(map, i)->name, GET_LAYER(map, j)->name) == 0 &&
          msRenameLayer((GET_LAYER(map, j)), ++count) != MS_SUCCESS) {
        return MS_FAILURE;
1040
      }
1041 1042 1043 1044 1045 1046
    }

    /* Don't forget to rename the first layer if duplicates were found */
    if (count > 1 && msRenameLayer((GET_LAYER(map, i)), 1) != MS_SUCCESS) {
      return MS_FAILURE;
    }
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
  }
  return MS_SUCCESS;
}

/*
** msOWSNegotiateVersion()
**
** returns the most suitable version an OWS is to support given a client
** version parameter.
**
** supported_versions must be ordered from highest to lowest
**
** Returns a version integer of the supported version
**
*/

1063
int msOWSNegotiateVersion(int requested_version, const int supported_versions[], int num_supported_versions)
1064
{
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  int i;

  /* if version is not set return highest version */
  if (! requested_version)
    return supported_versions[0];

  /* if the requested version is lower than the lowest version return the lowest version  */
  if (requested_version < supported_versions[num_supported_versions-1])
    return supported_versions[num_supported_versions-1];

  /* return the first entry that's lower than or equal to the requested version */
  for (i = 0; i < num_supported_versions; i++) {
    if (supported_versions[i] <= requested_version)
      return supported_versions[i];
  }

  return requested_version;
}

/*
** msOWSTerminateOnlineResource()
**
** Append trailing "?" or "&" to an onlineresource URL if it doesn't have
** one already. The returned string is then ready to append GET parameters
** to it.
**
** Returns a newly allocated string that should be freed by the caller or
** NULL in case of error.
*/
char * msOWSTerminateOnlineResource(const char *src_url)
{
1096 1097
  char *online_resource = NULL;
  size_t buffer_size = 0;
1098

1099 1100
  if (src_url == NULL)
    return NULL;
1101

1102 1103 1104 1105 1106 1107 1108
  buffer_size = strlen(src_url)+2;
  online_resource = (char*) malloc(buffer_size);

  if (online_resource == NULL) {
    msSetError(MS_MEMERR, NULL, "msOWSTerminateOnlineResource()");
    return NULL;
  }
1109

1110
  strlcpy(online_resource, src_url, buffer_size);
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120
  /* Append trailing '?' or '&' if missing. */
  if (strchr(online_resource, '?') == NULL)
    strlcat(online_resource, "?", buffer_size);
  else {
    char *c;
    c = online_resource+strlen(online_resource)-1;
    if (*c != '?' && *c != '&')
      strlcpy(c+1, "&", buffer_size-strlen(online_resource));
  }
1121

1122
  return online_resource;
1123 1124 1125 1126 1127
}

/*
** msOWSGetOnlineResource()
**
1128
** Return the online resource for this service.  First try to lookup
1129 1130 1131 1132 1133
** specified metadata, and if not found then try to build the URL ourselves.
**
** Returns a newly allocated string that should be freed by the caller or
** NULL in case of error.
*/
1134
char * msOWSGetOnlineResource(mapObj *map, const char *namespaces, const char *metadata_name,
1135 1136
                              cgiRequestObj *req)
{
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
  const char *value;
  char *online_resource = NULL;

  /* We need this script's URL, including hostname. */
  /* Default to use the value of the "onlineresource" metadata, and if not */
  /* set then build it: "http://$(SERVER_NAME):$(SERVER_PORT)$(SCRIPT_NAME)?" */
  /* (+append the map=... param if it was explicitly passed in QUERY_STRING) */
  /*  */
  if ((value = msOWSLookupMetadata(&(map->web.metadata), namespaces, metadata_name))) {
    online_resource = msOWSTerminateOnlineResource(value);
  } else {
    if ((online_resource = msBuildOnlineResource(map, req)) == NULL) {
      msSetError(MS_CGIERR, "Impossible to establish server URL.  Please set \"%s\" metadata.", "msOWSGetOnlineResource()", metadata_name);
      return NULL;
1151
    }
1152
  }
1153

1154
  return online_resource;
1155 1156 1157
}


1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
/*
** msOWSGetOnlineResource()
**
** Return the online resource for this service and add language parameter.
**
** Returns a newly allocated string that should be freed by the caller or
** NULL in case of error.
*/
char * msOWSGetOnlineResource2(mapObj *map, const char *namespaces, const char *metadata_name,
                               cgiRequestObj *req, const char* validated_language)
{
  char *online_resource = msOWSGetOnlineResource(map, namespaces, metadata_name, req);

  if ( online_resource && validated_language ) {
    /* online_resource is already terminated, so we can simply add language=...& */
    /* but first we need to make sure that online_resource has enough capacity */
    online_resource = (char *)msSmallRealloc(online_resource, strlen(online_resource) + strlen(validated_language) +  11);
    strcat(online_resource, "language=");
    strcat(online_resource, validated_language);
    strcat(online_resource, "&");
  }

  return online_resource;
}

1183 1184
/* msOWSGetSchemasLocation()
**
1185 1186
** schemas location is the root of the web tree where all WFS-related
** schemas can be found on this server.  These URLs must exist in order
1187 1188 1189 1190 1191 1192 1193
** to validate xml.
**
** Use value of "ows_schemas_location" metadata, if not set then
** return ".." as a default
*/
const char *msOWSGetSchemasLocation(mapObj *map)
{
1194
  const char *schemas_location;
1195

1196 1197 1198 1199
  schemas_location = msLookupHashTable(&(map->web.metadata),
                                       "ows_schemas_location");
  if (schemas_location == NULL)
    schemas_location = OWS_DEFAULT_SCHEMAS_LOCATION;
1200

1201
  return schemas_location;
1202 1203
}

1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
/* msOWSGetInspireSchemasLocation()
**
** schemas location is the root of the web tree where all Inspire-related
** schemas can be found on this server.  These URLs must exist in order
** to validate xml.
**
** Use value of "inspire_schemas_location" metadata
*/
const char *msOWSGetInspireSchemasLocation(mapObj *map)
{
  const char *schemas_location;

  schemas_location = msLookupHashTable(&(map->web.metadata),
                                       "inspire_schemas_location");
  if (schemas_location == NULL)
    schemas_location = "http://inspire.ec.europa.eu/schemas";

  return schemas_location;
}

1224 1225 1226 1227 1228 1229 1230 1231 1232
/* msOWSGetLanguage()
**
** returns the language via MAP/WEB/METADATA/ows_language
**
** Use value of "ows_language" metadata, if not set then
** return "undefined" as a default
*/
const char *msOWSGetLanguage(mapObj *map, const char *context)
{
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
  const char *language;

  /* if this is an exception, MapServer always returns Exception
     messages in en-US
  */
  if (strcmp(context,"exception") == 0) {
    language = MS_ERROR_LANGUAGE;
  }
  /* if not, fetch language from mapfile metadata */
  else {
    language = msLookupHashTable(&(map->web.metadata), "ows_language");
1244

1245 1246
    if (language == NULL) {
      language = "undefined";
1247
    }
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
  }
  return language;
}

/* msOWSGetLanguageList
**
** Returns the list of languages that this service supports
**
** Use value of "languages" metadata (comma-separated list), or NULL if not set
**
** Returns a malloced char** of length numitems which must be freed
** by the caller, or NULL (with numitems = 0)
*/
char **msOWSGetLanguageList(mapObj *map, const char *namespaces, int *numitems)
{

  const char *languages = NULL;

  languages = msOWSLookupMetadata(&(map->web.metadata), namespaces, "languages");
  if (languages && strlen(languages) > 0) {
    return msStringSplit(languages, ',', numitems);
  } else {
    *numitems = 0;
    return NULL;
  }
}

/* msOWSGetLanguageFromList
**
** Returns a language according to the language requested by the client
**
** If the requested language is in the languages metadata then use it,
** otherwise ignore it and use the defaul language, which is the first entry in
** the languages metadata list. Calling with a NULL requested_langauge
** therefore returns this default language. If the language metadata list is
** not defined then the language is set to NULL.
**
** Returns a malloced char* which must be freed by the caller, or NULL
*/
char *msOWSGetLanguageFromList(mapObj *map, const char *namespaces, const char *requested_language)
{
  int num_items = 0;
  char **languages = msOWSGetLanguageList(map, namespaces, &num_items);
  char *language = NULL;

  if( languages && num_items > 0 ) {
    if ( !requested_language || !msStringInArray( requested_language, languages, num_items) ) {
      language = msStrdup(languages[0]);
    } else {
      language = msStrdup(requested_language);
    }
  }
  msFreeCharArray(languages, num_items);
1301

1302 1303 1304
  return language;
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344

/* msOWSLanguageNegotiation
**
** Returns a language according to the accepted languages requested by the client
**
** Returns a malloced char* which must be freed by the caller, or NULL
*/
char *msOWSLanguageNegotiation(mapObj *map, const char *namespaces, char **accept_languages, int num_accept_languages)
{
  int num_languages = 0;
  char **languages = NULL;
  char *result_language = NULL;

  languages = msOWSGetLanguageList(map, namespaces, &num_languages);

  if (languages && num_languages > 0) {
    int i;
    for (i = 0; i < num_accept_languages; ++i) {
      const char *accept_language = accept_languages[i];

      /* '*' means any language */
      if (EQUAL(accept_language, "*")) {
        result_language = msStrdup(languages[0]);
        break;
      } else if (msStringInArray(accept_language, languages, num_languages)) {
        result_language = msStrdup(accept_language);
        break;
      }
    }

    if (result_language == NULL) {
      result_language = msStrdup(languages[0]);
    }
  }

  msFreeCharArray(languages, num_languages);
  return result_language;
}


1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
/* msOWSPrintInspireCommonExtendedCapabilities
**
** Output INSPIRE common extended capabilities items to stream
** The currently supported items are metadata and languages
**
** tag_name is the name (including ns prefix) of the tag to include the whole
** extended capabilities block in
**
** service is currently included for future compatibility when differing
** extended capabilities elements are included for different service types
**
** Returns a status code; MS_NOERR if all ok, action_if_not_found otherwise
*/
int msOWSPrintInspireCommonExtendedCapabilities(FILE *stream, mapObj *map, const char *namespaces,
1359 1360
    int action_if_not_found, const char *tag_name, const char* tag_ns,
    const char *validated_language, const OWSServiceType service)
1361 1362 1363 1364 1365
{

  int metadataStatus = 0;
  int languageStatus = 0;

1366 1367 1368 1369
  if( tag_ns )
    msIO_fprintf(stream, "  <%s %s>\n", tag_name, tag_ns);
  else
    msIO_fprintf(stream, "  <%s>\n", tag_name);
1370

1371
  metadataStatus = msOWSPrintInspireCommonMetadata(stream, map, namespaces, action_if_not_found, service);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
  languageStatus = msOWSPrintInspireCommonLanguages(stream, map, namespaces, action_if_not_found, validated_language);

  msIO_fprintf(stream, "  </%s>\n", tag_name);

  return (metadataStatus != MS_NOERR) ? metadataStatus : languageStatus;
}

/* msOWSPrintInspireCommonMetadata
**
** Output INSPIRE common metadata items to a stream
**
** Returns a status code; MS_NOERR if all OK, action_if_not_found otherwise
*/
int msOWSPrintInspireCommonMetadata(FILE *stream, mapObj *map, const char *namespaces,
1386
                                    int action_if_not_found, const OWSServiceType service)
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
{

  int status = MS_NOERR;
  const char *inspire_capabilities = NULL;

  inspire_capabilities = msOWSLookupMetadata(&(map->web.metadata), namespaces, "inspire_capabilities");

  if(!inspire_capabilities) {
    if (OWS_WARN == action_if_not_found) {
      msIO_fprintf(stream, "<!-- WARNING: missing metadata entry for 'inspire_capabilities', one of 'embed' and 'url' must be supplied. -->\n");
    }
    return action_if_not_found;
  }
  if (strcasecmp("url",inspire_capabilities) == 0) {
    if ( msOWSLookupMetadata(&(map->web.metadata), namespaces, "inspire_metadataurl_href") != NULL ) {
      msIO_fprintf(stream, "    <inspire_common:MetadataUrl xsi:type=\"inspire_common:resourceLocatorType\">\n");
      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadataurl_href", OWS_WARN, "      <inspire_common:URL>%s</inspire_common:URL>\n", "");
      msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadataurl_format", OWS_WARN, "      <inspire_common:MediaType>%s</inspire_common:MediaType>\n", "");
      msIO_fprintf(stream, "    </inspire_common:MetadataUrl>\n");
    } else {
      status = action_if_not_found;
      if (OWS_WARN == action_if_not_found) {
        msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), "inspire_metadataurl_href");
1410 1411
      }
    }
1412
  } else if (strcasecmp("embed",inspire_capabilities) == 0) {
1413
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_resourcelocator", OWS_WARN, "    <inspire_common:ResourceLocator>\n      <inspire_common:URL>%s</inspire_common:URL>\n    </inspire_common:ResourceLocator>\n", NULL);
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    msIO_fprintf(stream,"    <inspire_common:ResourceType>service</inspire_common:ResourceType>\n");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_temporal_reference", OWS_WARN, "    <inspire_common:TemporalReference>\n      <inspire_common:DateOfLastRevision>%s</inspire_common:DateOfLastRevision>\n    </inspire_common:TemporalReference>\n", "");
    msIO_fprintf(stream, "    <inspire_common:Conformity>\n");
    msIO_fprintf(stream, "      <inspire_common:Specification>\n");
    msIO_fprintf(stream, "        <inspire_common:Title>-</inspire_common:Title>\n");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_temporal_reference", OWS_NOERR, "        <inspire_common:DateOfLastRevision>%s</inspire_common:DateOfLastRevision>\n", "");
    msIO_fprintf(stream, "      </inspire_common:Specification>\n");
    msIO_fprintf(stream, "      <inspire_common:Degree>notEvaluated</inspire_common:Degree>\n");
    msIO_fprintf(stream, "    </inspire_common:Conformity>\n");
    msIO_fprintf(stream, "    <inspire_common:MetadataPointOfContact>\n");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_mpoc_name", OWS_WARN, "      <inspire_common:OrganisationName>%s</inspire_common:OrganisationName>\n", "");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_mpoc_email", OWS_WARN, "      <inspire_common:EmailAddress>%s</inspire_common:EmailAddress>\n", "");
    msIO_fprintf(stream, "    </inspire_common:MetadataPointOfContact>\n");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_metadatadate", OWS_WARN, "      <inspire_common:MetadataDate>%s</inspire_common:MetadataDate>\n", "");
1428
    if( service == OWS_WFS || service == OWS_WCS )
1429 1430 1431 1432
        msIO_fprintf(stream,"    <inspire_common:SpatialDataServiceType>download</inspire_common:SpatialDataServiceType>\n");
    else
        msIO_fprintf(stream,"    <inspire_common:SpatialDataServiceType>view</inspire_common:SpatialDataServiceType>\n");
    msOWSPrintEncodeMetadata(stream, &(map->web.metadata), namespaces, "inspire_keyword", OWS_WARN, "    <inspire_common:MandatoryKeyword>\n      <inspire_common:KeywordValue>%s</inspire_common:KeywordValue>\n    </inspire_common:MandatoryKeyword>\n", "");
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
  } else {
    status = action_if_not_found;
    if (OWS_WARN == action_if_not_found) {
      msIO_fprintf(stream, "<!-- WARNING: invalid value '%s' for 'inspire_capabilities', only 'embed' and 'url' are supported. -->\n", inspire_capabilities);
    }
  }

  return status;
}

/* msOWSPrintInspireCommonLanguages
**
** Output INSPIRE supported languages block to stream
**
** Returns a status code; MS_NOERR if all OK; action_if_not_found otherwise
*/
int msOWSPrintInspireCommonLanguages(FILE *stream, mapObj *map, const char *namespaces,
                                     int action_if_not_found, const char *validated_language)
{
  char *buffer = NULL; /* temp variable for malloced strings that will need freeing */
  int status = MS_NOERR;

  char *default_language = msOWSGetLanguageFromList(map, namespaces, NULL);

  if(validated_language && default_language) {
    msIO_fprintf(stream, "    <inspire_common:SupportedLanguages>\n");
    msIO_fprintf(stream, "      <inspire_common:DefaultLanguage><inspire_common:Language>%s"
                 "</inspire_common:Language></inspire_common:DefaultLanguage>\n",
                 buffer = msEncodeHTMLEntities(default_language));
    msFree(buffer);
    
    /* append _exclude to our default_language*/
    default_language = msSmallRealloc(default_language,strlen(default_language)+strlen("_exclude")+1);
    strcat(default_language,"_exclude");

    msOWSPrintEncodeMetadataList(stream, &(map->web.metadata), namespaces, "languages", NULL, NULL,
                                 "      <inspire_common:SupportedLanguage><inspire_common:Language>%s"
                                 "</inspire_common:Language></inspire_common:SupportedLanguage>\n", default_language);
    msIO_fprintf(stream, "    </inspire_common:SupportedLanguages>\n");
    msIO_fprintf(stream, "    <inspire_common:ResponseLanguage><inspire_common:Language>%s"
                 "</inspire_common:Language></inspire_common:ResponseLanguage>\n", validated_language);
  } else {
    status = action_if_not_found;
    if (OWS_WARN == action_if_not_found) {
      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), "languages");
    }
  }

  msFree(default_language);

  return status;
1484 1485 1486 1487 1488
}

/*
** msOWSPrintMetadata()
**
1489 1490 1491
** Attempt to output a capability item.  If corresponding metadata is not
** found then one of a number of predefined actions will be taken.
** If a default value is provided and metadata is absent then the
1492 1493 1494
** default will be used.
*/

1495 1496 1497 1498
int msOWSPrintMetadata(FILE *stream, hashTableObj *metadata,
                       const char *namespaces, const char *name,
                       int action_if_not_found, const char *format,
                       const char *default_value)
1499
{
1500 1501
  const char *value = NULL;
  int status = MS_NOERR;
1502

1503 1504 1505 1506 1507 1508
  if((value = msOWSLookupMetadata(metadata, namespaces, name)) != NULL) {
    msIO_fprintf(stream, format, value);
  } else {
    if (action_if_not_found == OWS_WARN) {
      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
      status = action_if_not_found;
1509 1510
    }

1511 1512 1513
    if (default_value)
      msIO_fprintf(stream, format, default_value);
  }
1514

1515
  return status;
1516 1517 1518 1519 1520 1521
}


/*
** msOWSPrintEncodeMetadata()
**
1522 1523 1524
** Attempt to output a capability item.  If corresponding metadata is not
** found then one of a number of predefined actions will be taken.
** If a default value is provided and metadata is absent then the
1525 1526 1527 1528
** default will be used.
** Also encode the value with msEncodeHTMLEntities.
*/

1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
int msOWSPrintEncodeMetadata(FILE *stream, hashTableObj *metadata,
                             const char *namespaces, const char *name,
                             int action_if_not_found,
                             const char *format, const char *default_value)
{
  return msOWSPrintEncodeMetadata2(stream, metadata, namespaces, name, action_if_not_found, format, default_value, NULL);
}


/*
** msOWSPrintEncodeMetadata2()
**
** Attempt to output a capability item in the requested language.
** Fallback using no language parameter.
*/
int msOWSPrintEncodeMetadata2(FILE *stream, hashTableObj *metadata,
                              const char *namespaces, const char *name,
                              int action_if_not_found,
                              const char *format, const char *default_value,
                              const char *validated_language)
1549
{
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561
  const char *value;
  char * pszEncodedValue=NULL;
  int status = MS_NOERR;

  if((value = msOWSLookupMetadataWithLanguage(metadata, namespaces, name, validated_language))) {
    pszEncodedValue = msEncodeHTMLEntities(value);
    msIO_fprintf(stream, format, pszEncodedValue);
    free(pszEncodedValue);
  } else {
    if (action_if_not_found == OWS_WARN) {
      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name, (validated_language?".":""), (validated_language?validated_language:""));
      status = action_if_not_found;
1562 1563
    }

1564 1565 1566 1567
    if (default_value) {
      pszEncodedValue = msEncodeHTMLEntities(default_value);
      msIO_fprintf(stream, format, default_value);
      free(pszEncodedValue);
1568
    }
1569
  }
1570

1571
  return status;
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
}


/*
** msOWSGetEncodeMetadata()
**
** Equivalent to msOWSPrintEncodeMetadata. Returns en encoded value of the
** metadata or the default value.
** Caller should free the returned string.
*/
1582 1583
char *msOWSGetEncodeMetadata(hashTableObj *metadata,
                             const char *namespaces, const char *name,
1584 1585
                             const char *default_value)
{
1586 1587 1588 1589 1590 1591
  const char *value;
  char * pszEncodedValue=NULL;
  if((value = msOWSLookupMetadata(metadata, namespaces, name)))
    pszEncodedValue = msEncodeHTMLEntities(value);
  else if (default_value)
    pszEncodedValue = msEncodeHTMLEntities(default_value);
1592

1593
  return pszEncodedValue;
1594
}
1595

1596 1597 1598 1599

/*
** msOWSPrintValidateMetadata()
**
1600 1601 1602
** Attempt to output a capability item.  If corresponding metadata is not
** found then one of a number of predefined actions will be taken.
** If a default value is provided and metadata is absent then the
1603 1604 1605 1606
** default will be used.
** Also validate the value with msIsXMLTagValid.
*/

1607 1608 1609 1610
int msOWSPrintValidateMetadata(FILE *stream, hashTableObj *metadata,
                               const char *namespaces, const char *name,
                               int action_if_not_found,
                               const char *format, const char *default_value)
1611
{
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
  const char *value;
  int status = MS_NOERR;

  if((value = msOWSLookupMetadata(metadata, namespaces, name))) {
    if(msIsXMLTagValid(value) == MS_FALSE)
      msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid in a "
                   "XML tag context. -->\n", value);
    msIO_fprintf(stream, format, value);
  } else {
    if (action_if_not_found == OWS_WARN) {
      msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
      status = action_if_not_found;
1624 1625
    }

1626 1627 1628 1629 1630
    if (default_value) {
      if(msIsXMLTagValid(default_value) == MS_FALSE)
        msIO_fprintf(stream, "<!-- WARNING: The value '%s' is not valid "
                     "in a XML tag context. -->\n", default_value);
      msIO_fprintf(stream, format, default_value);
1631
    }
1632
  }
1633

1634
  return status;
1635 1636 1637 1638 1639
}

/*
** msOWSPrintGroupMetadata()
**
1640 1641 1642
** Attempt to output a capability item.  If corresponding metadata is not
** found then one of a number of predefined actions will be taken.
** If a default value is provided and metadata is absent then the
1643 1644
** default will be used.
*/
1645 1646 1647 1648 1649 1650 1651
int msOWSPrintGroupMetadata(FILE *stream, mapObj *map, char* pszGroupName,
                            const char *namespaces, const char *name,
                            int action_if_not_found,
                            const char *format, const char *default_value)
{
  return msOWSPrintGroupMetadata2(stream, map, pszGroupName, namespaces, name, action_if_not_found, format, default_value, NULL);
}
1652

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
/*
** msOWSPrintGroupMetadata2()
**
** Attempt to output a capability item in the requested language.
** Fallback using no language parameter.
*/
int msOWSPrintGroupMetadata2(FILE *stream, mapObj *map, char* pszGroupName,
                             const char *namespaces, const char *name,
                             int action_if_not_found,
                             const char *format, const char *default_value,
                             const char *validated_language)
1664
{
1665 1666 1667 1668
  const char *value;
  char *encoded;
  int status = MS_NOERR;
  int i;
1669

1670 1671 1672 1673 1674 1675 1676 1677
  for (i=0; i<map->numlayers; i++) {
    if (GET_LAYER(map, i)->group && (strcmp(GET_LAYER(map, i)->group, pszGroupName) == 0) && &(GET_LAYER(map, i)->metadata)) {
      if((value = msOWSLookupMetadataWithLanguage(&(GET_LAYER(map, i)->metadata), namespaces, name, validated_language))) {
        encoded = msEncodeHTMLEntities(value);
        msIO_fprintf(stream, format, encoded);
        msFree(encoded);
        return status;
      }
1678
    }
1679
  }
1680

1681 1682 1683 1684
  if (action_if_not_found == OWS_WARN) {
    msIO_fprintf(stream, "<!-- WARNING: Mandatory metadata '%s%s' was missing in this context. -->\n", (namespaces?"..._":""), name);
    status = action_if_not_found;
  }
1685

1686 1687 1688 1689 1690 1691 1692
  if (default_value) {
    encoded = msEncodeHTMLEntities(default_value);
    msIO_fprintf(stream, format, encoded);
    msFree(encoded);
  }

  return status;
1693 1694 1695 1696
}

/* msOWSPrintURLType()
**
1697 1698
** Attempt to output a URL item in capabilties.  If corresponding metadata
** is not found then one of a number of predefined actions will be taken.
1699 1700 1701
** Since it's a capability item, five metadata will be used to populate the
** XML elements.
**
1702 1703
** The 'name' argument is the basename of the metadata items relating to this
** URL type and the suffixes _type, _width, _height, _format and _href will
1704
** be appended to the name in the metadata search.
1705
** e.g. passing name=metadataurl will result in the following medata entries
1706 1707 1708 1709 1710 1711
** being used:
**    ows_metadataurl_type
**    ows_metadataurl_format
**    ows_metadataurl_href
**    ... (width and height are unused for metadata)
**
1712
** As for all the msOWSPrint*() functions, the namespace argument specifies
1713 1714
** which prefix (ows_, wms_, wcs_, etc.) is used for the metadata names above.
**
1715
** Then the final string will be built from
1716 1717 1718
** the tag_name and the five metadata. The template is:
** <tag_name%type%width%height%format>%href</tag_name>
**
1719
** For example the width format will usually be " width=\"%s\"".
1720 1721
** An extern format will be "> <Format>%s</Format"
**
1722 1723
** Another template template may be used, but it needs to contains 5 %s,
** otherwise leave it to NULL. If tag_format is used then you don't need the
1724 1725 1726 1727
** tag_name and the tabspace.
**
** Note that all values will be HTML-encoded.
**/
1728 1729 1730 1731 1732
int msOWSPrintURLType(FILE *stream, hashTableObj *metadata,
                      const char *namespaces, const char *name,
                      int action_if_not_found, const char *tag_format,
                      const char *tag_name, const char *type_format,
                      const char *width_format, const char *height_format,
1733
                      const char *urlfrmt_format, const char *href_format,
1734 1735 1736 1737 1738
                      int type_is_mandatory, int width_is_mandatory,
                      int height_is_mandatory, int format_is_mandatory,
                      int href_is_mandatory, const char *default_type,
                      const char *default_width, const char *default_height,
                      const char *default_urlfrmt, const char *default_href,
1739 1740
                      const char *tabspace)
{
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756
  const char *value;
  char *metadata_name;
  size_t buffer_size = 0, buffer_size_tmp = 0;
  char *encoded;
  int status = MS_NOERR;
  char *type=NULL, *width=NULL, *height=NULL, *urlfrmt=NULL, *href=NULL;

  buffer_size = strlen(name)+10;
  metadata_name = (char*)malloc(buffer_size);

  /* Get type */
  if(type_format != NULL) {
    snprintf(metadata_name, buffer_size, "%s_type", name);
    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
    if(value != NULL) {
      encoded = msEncodeHTMLEntities(value);
1757
      buffer_size_tmp = strlen(type_format)+strlen(encoded)+1;
1758 1759 1760
      type = (char*)malloc(buffer_size_tmp);
      snprintf(type, buffer_size_tmp, type_format, encoded);
      msFree(encoded);
1761
    }
1762
  }
1763

1764 1765 1766 1767 1768 1769
  /* Get width */
  if(width_format != NULL) {
    snprintf(metadata_name, buffer_size, "%s_width", name);
    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
    if(value != NULL) {
      encoded = msEncodeHTMLEntities(value);
1770
      buffer_size_tmp = strlen(width_format)+strlen(encoded)+1;
1771 1772 1773
      width = (char*)malloc(buffer_size_tmp);
      snprintf(width, buffer_size_tmp, width_format, encoded);
      msFree(encoded);
1774
    }
1775
  }
1776

1777 1778 1779 1780 1781 1782
  /* Get height */
  if(height_format != NULL) {
    snprintf(metadata_name, buffer_size, "%s_height", name);
    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
    if(value != NULL) {
      encoded = msEncodeHTMLEntities(value);
1783
      buffer_size_tmp = strlen(height_format)+strlen(encoded)+1;
1784 1785 1786
      height = (char*)malloc(buffer_size_tmp);
      snprintf(height, buffer_size_tmp, height_format, encoded);
      msFree(encoded);
1787
    }
1788
  }
1789

1790 1791 1792 1793 1794 1795
  /* Get format */
  if(urlfrmt_format != NULL) {
    snprintf(metadata_name, buffer_size, "%s_format", name);
    value = msOWSLookupMetadata(metadata, namespaces, metadata_name);
    if(value != NULL) {
      encoded = msEncodeHTMLEntities(value);
1796
      buffer_size_tmp = strlen(urlfrmt_format)+strlen(encoded)+1;