int KmlRenderer::closeNewLayer(imageObj *img, layerObj *layer)
{
  flushPlacemark();

  xmlAddChild(DocNode, LayerNode);

  if(Items) {
    msFreeCharArray(Items, NumItems);
    Items = NULL;
    NumItems = 0;
  }

  if (pszLayerDescMetadata)
    pszLayerDescMetadata = NULL;
  if (pszLayerNameAttributeMetadata)
    pszLayerNameAttributeMetadata = NULL;

  if (papszLayerIncludeItems && nIncludeItems>0)
    msFreeCharArray(papszLayerIncludeItems, nIncludeItems);
  papszLayerIncludeItems=NULL;

  if (papszLayerExcludeItems && nExcludeItems>0)
    msFreeCharArray(papszLayerExcludeItems, nExcludeItems);
  papszLayerExcludeItems=NULL;

  return MS_SUCCESS;
}
Exemple #2
0
int msValidateTimeValue(char *timestring, const char *timeextent)
{
    char **atimes =  NULL;
    int i, numtimes=0;

    /* we need to validate the time passsed in the request */
    /* against the time extent defined */

    if (!timestring || !timeextent)
      return MS_FALSE;

   
    /* parse the time string. We support descrete times (eg 2004-09-21), */
    /* multiple times (2004-09-21, 2004-09-22, ...) */
    /* and range(s) (2004-09-21/2004-09-25, 2004-09-27/2004-09-29) */
    if (strstr(timestring, ",") == NULL &&
        strstr(timestring, "/") == NULL) /* discrete time */
    {
        return _msValidateTime(timestring,  timeextent);
        
    }
    else
    {
        atimes = msStringSplit (timestring, ',', &numtimes);
        if (numtimes >=1) /* multiple times */
        {

            if (strstr(atimes[0], "/") == NULL) /* multiple descrete times */
            {
                for (i=0; i<numtimes; i++)
                {
                    if (_msValidateTime(atimes[i], timeextent) == MS_FALSE)
                    {
                        msFreeCharArray(atimes, numtimes);
                        return MS_FALSE;
                    }
                }
                msFreeCharArray(atimes, numtimes);
                return MS_TRUE;
            }
            else /* multiple ranges */
            {
                for (i=0; i<numtimes; i++)
                {
                    if (_msValidateTime(atimes[i], timeextent) == MS_FALSE)
                    {
                        msFreeCharArray(atimes, numtimes);
                        return MS_FALSE;
                    }
                     
                 }
                 msFreeCharArray(atimes, numtimes);
                 return MS_TRUE;
            }
            
        }

    }
    return MS_FALSE;
}
static int FTLParseEpsgString(char *pszEpsg, projectionObj *psProj)
{
    int nStatus = MS_FALSE;
    int nTokens = 0;
    char **tokens = NULL;
    int nEpsgTmp=0;

#ifdef USE_PROJ
    if (pszEpsg && psProj)
    {
        nTokens = 0;
        tokens = msStringSplit(pszEpsg,'#', &nTokens);
        if (tokens && nTokens == 2)
        {
            char szTmp[32];
            sprintf(szTmp, "init=epsg:%s",tokens[1]);
            msInitProjection(psProj);
            if (msLoadProjectionString(psProj, szTmp) == 0)
              nStatus = MS_TRUE;
        }
        else if (tokens &&  nTokens == 1)
        {
            if (tokens)
              msFreeCharArray(tokens, nTokens);
            nTokens = 0;

            tokens = msStringSplit(pszEpsg,':', &nTokens);
            nEpsgTmp = -1;
            if (tokens &&  nTokens == 1)
            {
                nEpsgTmp = atoi(tokens[0]);
                
            }
            else if (tokens &&  nTokens == 2)
            {
                nEpsgTmp = atoi(tokens[1]);
            }
            if (nEpsgTmp > 0)
            {
                char szTmp[32];
                sprintf(szTmp, "init=epsg:%d",nEpsgTmp);
                msInitProjection(psProj);
                if (msLoadProjectionString(psProj, szTmp) == 0)
                  nStatus = MS_TRUE;
            }
        }
        if (tokens)
          msFreeCharArray(tokens, nTokens);
    }
#endif
    return nStatus;
}
Exemple #4
0
static int BuildFeatureAttributes(layerObj* layer, msClusterLayerInfo* layerinfo, shapeObj* shape)
{
  char** values;
  int i;
  int* itemindexes = layer->iteminfo;

  if (layer->numitems == layerinfo->srcLayer.numitems)
    return MS_SUCCESS; /* we don't have custom attributes, no need to reconstruct the array */

  values = msSmallMalloc(sizeof(char*) * (layer->numitems));

  for (i = 0; i < layer->numitems; i++) {
    if (itemindexes[i] == MSCLUSTER_FEATURECOUNTINDEX) {
      values[i] = NULL; /* not yet assigned */
    } else if (itemindexes[i] == MSCLUSTER_GROUPINDEX) {
      values[i] = NULL; /* not yet assigned */
    } else if (shape->values[itemindexes[i]])
      values[i] = msStrdup(shape->values[itemindexes[i]]);
    else
      values[i] = msStrdup("");
  }

  if (shape->values)
    msFreeCharArray(shape->values, shape->numvalues);

  shape->values = values;
  shape->numvalues = layer->numitems;

  return MS_SUCCESS;
}
Exemple #5
0
void msFreeCgiObj(cgiRequestObj *request)
{
  msFreeCharArray(request->ParamNames, request->NumParams);
  msFreeCharArray(request->ParamValues, request->NumParams);
  request->ParamNames = NULL;
  request->ParamValues = NULL;
  request->NumParams = 0;
  request->type = -1;
  msFree(request->contenttype);
  msFree(request->postrequest);
  msFree(request->httpcookiedata);
  request->contenttype = NULL;
  request->postrequest = NULL;
  request->httpcookiedata = NULL;

  msFree(request);
}
Exemple #6
0
void msGetOutputFormatMimeListWMS( mapObj *map, char **mime_list, int max_mime )
{
    int mime_count = 0, i,j;
    const char *format_list = NULL;
    char **tokens = NULL;
    int numtokens = 0;
    outputFormatObj *format;
    msApplyDefaultOutputFormats(map);
    format_list = msOWSLookupMetadata(&(map->web.metadata), "M","getmap_formatlist");
    if ( format_list && strlen(format_list) > 0)
      tokens = msStringSplit(format_list,  ',', &numtokens);

    if (tokens && numtokens > 0)
    {
        for(j = 0; j < numtokens; j++ )
        {
            format = msSelectOutputFormat(map, tokens[j]);
            if (format != NULL)
            {
                mime_list[mime_count++] = format->mimetype;
            }
        }
        msFreeCharArray(tokens, numtokens);
    }
    else
    {
        for( i = 0; i < map->numoutputformats && mime_count < max_mime; i++ )
        {
            int  j;
        
            if( map->outputformatlist[i]->mimetype == NULL )
              continue;

            for( j = 0; j < mime_count; j++ )
            {
                if( strcasecmp(mime_list[j],
                               map->outputformatlist[i]->mimetype) == 0 )
                  break;
            }

            if( j == mime_count && map->outputformatlist[i]->driver &&
               (
#ifdef USE_GD
                strncasecmp(map->outputformatlist[i]->driver, "GD/", 3)==0 ||
#endif
                strncasecmp(map->outputformatlist[i]->driver, "GDAL/", 5)==0 ||
                strncasecmp(map->outputformatlist[i]->driver, "AGG/", 4)==0 ||
                strcasecmp(map->outputformatlist[i]->driver, "CAIRO/SVG")==0 ||
                strcasecmp(map->outputformatlist[i]->driver, "CAIRO/PDF")==0 ||
                strcasecmp(map->outputformatlist[i]->driver, "kml")==0 ||
                strcasecmp(map->outputformatlist[i]->driver, "kmz")==0))
              mime_list[mime_count++] = map->outputformatlist[i]->mimetype;
        }
    }
    if( mime_count < max_mime )
        mime_list[mime_count] = NULL;
}
char *FLTGetFeatureIdCommonExpression(FilterEncodingNode *psFilterNode, layerObj *lp)
{
  char *pszExpression = NULL;
  int nTokens = 0, i=0, bString=0;
  char **tokens = NULL;
  const char *pszAttribute=NULL;

#if defined(USE_WMS_SVR) || defined(USE_WFS_SVR) || defined(USE_WCS_SVR) || defined(USE_SOS_SVR)
  if (psFilterNode->pszValue) {
    pszAttribute = msOWSLookupMetadata(&(lp->metadata), "OFG", "featureid");
    if (pszAttribute) {
      tokens = msStringSplit(psFilterNode->pszValue,',', &nTokens);
      if (tokens && nTokens > 0) {
        for (i=0; i<nTokens; i++) {
          char *pszTmp = NULL;
          int bufferSize = 0;
          const char* pszId = tokens[i];
          const char* pszDot = strchr(pszId, '.');
          if( pszDot )
            pszId = pszDot + 1;

          if (i == 0) {
            if(FLTIsNumeric(pszId) == MS_FALSE)
              bString = 1;
          }

          if (bString) {
            bufferSize = 11+strlen(pszId)+strlen(pszAttribute)+1;
            pszTmp = (char *)msSmallMalloc(bufferSize);
            snprintf(pszTmp, bufferSize, "(\"[%s]\" ==\"%s\")" , pszAttribute, pszId);
          } else {
            bufferSize = 8+strlen(pszId)+strlen(pszAttribute)+1;
            pszTmp = (char *)msSmallMalloc(bufferSize);
            snprintf(pszTmp, bufferSize, "([%s] == %s)" , pszAttribute, pszId);
          }

          if (pszExpression != NULL)
            pszExpression = msStringConcatenate(pszExpression, " OR ");
          else
            pszExpression = msStringConcatenate(pszExpression, "(");
          pszExpression = msStringConcatenate(pszExpression, pszTmp);
          msFree(pszTmp);
        }

        msFreeCharArray(tokens, nTokens);
      }
    }

    /* opening and closing brackets are needed for mapserver expressions */
    if (pszExpression)
      pszExpression = msStringConcatenate(pszExpression, ")");
  }
#endif

  return pszExpression;
}
Exemple #8
0
void msFreeShape(shapeObj *shape)
{
  int c;

  for (c= 0; c < shape->numlines; c++)
    free(shape->line[c].point);
  free(shape->line);

  if(shape->values) msFreeCharArray(shape->values, shape->numvalues);
  if(shape->text) free(shape->text);

  msInitShape(shape); // now reset
}
Exemple #9
0
int agg2RenderBitmapGlyphs(imageObj *img, double x, double y, labelStyleObj *style, char *text)
{
  typedef mapserver::glyph_raster_bin<color_type> glyph_gen;
  int size = MS_NINT(style->size);
  if(size<0 || size>4) {
    msSetError(MS_RENDERERERR,"invalid bitmap font size", "agg2RenderBitmapGlyphs()");
    return MS_FAILURE;
  }
  AGG2Renderer *r = AGG_RENDERER(img);
  glyph_gen glyph(0);
  mapserver::renderer_raster_htext_solid<renderer_base, glyph_gen> rt(r->m_renderer_base, glyph);
  glyph.font(rasterfonts[size]);
  int numlines=0;
  char **lines;
  /*masking out the out-of-range character codes*/
  int len;
  int cc_start = rasterfonts[size][2];
  int cc_end = cc_start + rasterfonts[size][3];
  if(msCountChars(text,'\n')) {
    if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
      return(-1);
  } else {
    lines = &text;
    numlines = 1;
  }
  y -= glyph.base_line();
  for(int n=0; n<numlines; n++) {
    len = strlen(lines[n]);
    for (int i = 0; i < len; i++)
      if (lines[n][i] < cc_start || lines[n][i] > cc_end)
        lines[n][i] = '.';
    if(style->outlinewidth > 0) {
      rt.color(aggColor(style->outlinecolor));
      for(int i=-1; i<=1; i++) {
        for(int j=-1; j<=1; j++) {
          if(i||j) {
            rt.render_text(x+i, y+j, lines[n], true);
          }
        }
      }
    }
    assert(style->color);
    rt.color(aggColor(style->color));
    rt.render_text(x, y, lines[n], true);
    y += glyph.height();
  }
  if(*lines != text)
    msFreeCharArray(lines, numlines);
  return MS_SUCCESS;
  return MS_SUCCESS;
}
Exemple #10
0
static projectionObj* msGetProjectNormalized( const projectionObj* p )
{
  int i;
  char* pszNewProj4Def;
  projectionObj* pnew;

  pnew = (projectionObj*)msSmallMalloc(sizeof(projectionObj));
  msInitProjection(pnew);
  msCopyProjection(pnew, (projectionObj*)p);

  if(p->proj == NULL )
      return pnew;

  /* Normalize definition so that msProjectDiffers() works better */
  pszNewProj4Def = pj_get_def( p->proj, 0 );
  msFreeCharArray(pnew->args, pnew->numargs);
  pnew->args = msStringSplit(pszNewProj4Def,'+', &pnew->numargs);
  for(i = 0; i < pnew->numargs; i++)
  {
      /* Remove trailing space */
      if( strlen(pnew->args[i]) > 0 && pnew->args[i][strlen(pnew->args[i])-1] == ' ' )
          pnew->args[i][strlen(pnew->args[i])-1] = '\0';
      /* Remove spurious no_defs or init= */
      if( strcmp(pnew->args[i], "no_defs") == 0 ||
          strncmp(pnew->args[i], "init=", 5) == 0 )
      {
          if( i < pnew->numargs - 1 )
          {
              msFree(pnew->args[i]);
              memmove(pnew->args + i, pnew->args + i + 1,
                      sizeof(char*) * (pnew->numargs - 1 -i ));
          }
          pnew->numargs --;
          i --;
          continue;
      }
  }
  /* Sort the strings so they can be compared */
  qsort(pnew->args, pnew->numargs, sizeof(char*), msProjectSortString);
  /*{
      fprintf(stderr, "'%s' =\n", pszNewProj4Def);
      for(i = 0; i < p->numargs; i++)
          fprintf(stderr, "'%s' ", p->args[i]);
      fprintf(stderr, "\n");
  }*/
  pj_dalloc(pszNewProj4Def);
  
  return pnew;
}
int renderBitmapGlyphsGD(imageObj *img, double x, double y, labelStyleObj *style, char *text)
{
    int size = MS_NINT(style->size);
    gdFontPtr fontPtr;
    gdImagePtr ip;
    int numlines=0,t;
    char **lines;
    if(!(ip = MS_IMAGE_GET_GDIMAGEPTR(img))) return MS_FAILURE;
    if(size<0 || size>4 || (fontPtr = msGetBitmapFont(size))==NULL) {
        msSetError(MS_RENDERERERR,"invalid bitmap font size", "renderBitmapGlyphsGD()");
        return MS_FAILURE;
    }

    SETPEN(ip, style->color);
    SETPEN(ip, style->outlinecolor);

    if(msCountChars(text,'\n')) {
        if((lines = msStringSplit((const char*)text, '\n', &(numlines))) == NULL)
            return(-1);
    } else {
        lines = &text;
        numlines = 1;
    }

    y -= fontPtr->h;
    for(t=0; t<numlines; t++) {
        if(style->outlinewidth > 0) {
            gdImageString(ip, fontPtr, x, y-1,   (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x, y+1,   (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x+1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x-1, y,   (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x+1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x+1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x-1, y-1, (unsigned char *) lines[t], style->outlinecolor->pen);
            gdImageString(ip, fontPtr, x-1, y+1, (unsigned char *) lines[t], style->outlinecolor->pen);
        }
        if(style->color->pen != -1) {
            gdImageString(ip, fontPtr, x, y, (unsigned char *) lines[t], style->color->pen);
        }

        y += fontPtr->h; /* shift down */
    }


    if(lines != &text)
        msFreeCharArray(lines, numlines);
    return MS_SUCCESS;
}
Exemple #12
0
int msCSVJoinClose(joinObj *join) 
{ 
  int i;
  msCSVJoinInfo *joininfo = join->joininfo;

  if(!joininfo) return(MS_SUCCESS); /* already closed */

  for(i=0; i<joininfo->numrows; i++)
    msFreeCharArray(joininfo->rows[i], join->numitems);
  free(joininfo->rows);
  if(joininfo->target) free(joininfo->target);
  free(joininfo);
  joininfo = NULL;

  return(MS_SUCCESS);
}
Exemple #13
0
void msFreeOutputFormat( outputFormatObj *format )

{
    if( format == NULL )
        return;
    if(MS_RENDERER_PLUGIN(format) && format->vtable) {
       format->vtable->cleanup(MS_RENDERER_CACHE(format->vtable));
       free( format->vtable );
    }
    msFree( format->name );
    msFree( format->mimetype );
    msFree( format->driver );
    msFree( format->extension );
    msFreeCharArray( format->formatoptions, format->numformatoptions );
    msFree( format );
}
Exemple #14
0
int msDBFJoinNext(joinObj *join) 
{
  int i, n;
  msDBFJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
    msSetError(MS_JOINERR, "Join connection has not be created.", "msDBFJoinNext()"); 
    return(MS_FAILURE);
  }

  if(!joininfo->target) {
    msSetError(MS_JOINERR, "No target specified, run msDBFJoinPrepare() first.", "msDBFJoinNext()");
    return(MS_FAILURE);
  }

  /* clear any old data */
  if(join->values) { 
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  n = msDBFGetRecordCount(joininfo->hDBF);
    
  for(i=joininfo->nextrecord; i<n; i++) { /* find a match */
    if(strcmp(joininfo->target, msDBFReadStringAttribute(joininfo->hDBF, i, joininfo->toindex)) == 0) break;
  }  
    
  if(i == n) { /* unable to do the join */
    if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
      msSetError(MS_MEMERR, NULL, "msDBFJoinNext()");
      return(MS_FAILURE);
    }
    for(i=0; i<join->numitems; i++)
      join->values[i] = msStrdup("\0"); /* intialize to zero length strings */

    joininfo->nextrecord = n;
    return(MS_DONE);
  }
    
  if((join->values = msDBFGetValues(joininfo->hDBF,i)) == NULL) 
    return(MS_FAILURE);

  joininfo->nextrecord = i+1; /* so we know where to start looking next time through */

  return(MS_SUCCESS);
}
Exemple #15
0
void msSetLimitedPattersToUse(char *patternstring)
{
    int *limitedpatternindice = NULL;
    int numpatterns=0, i=0, j=0, ntmp=0;
    char **patterns = NULL;

    limitedpatternindice = (int *)msSmallMalloc(sizeof(int)*MS_NUMTIMEFORMATS);
    
    /* free previous setting */
    msUnsetLimitedPatternToUse();

    if (patternstring)
    {
        patterns = msStringSplit(patternstring, ',', &ntmp);
        if (patterns && ntmp >= 1)
        {
            
            for (i=0; i<ntmp; i++)
            {
                for (j=0; j<MS_NUMTIMEFORMATS; j++)
                {
                    if (strcasecmp( ms_timeFormats[j].userformat, patterns[i]) ==0)
                    {
                        limitedpatternindice[numpatterns] = j;
                        numpatterns++;
                        break;
                    }
                }
            }
            
            msFreeCharArray(patterns, ntmp);
        }
    }

    if (numpatterns > 0)
    {
        ms_limited_pattern = (int *)msSmallMalloc(sizeof(int)*numpatterns);
        for (i=0; i<numpatterns; i++)
          ms_limited_pattern[i] = limitedpatternindice[i];

        ms_num_limited_pattern = numpatterns;
        free (limitedpatternindice);
    }
                                            
}
Exemple #16
0
int msCSVJoinNext(joinObj *join) 
{
  int i,j;
  msCSVJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
    msSetError(MS_JOINERR, "Join connection has not be created.", "msCSVJoinNext()"); 
    return(MS_FAILURE);
  }

  /* clear any old data */
  if(join->values) { 
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  for(i=joininfo->nextrow; i<joininfo->numrows; i++) { /* find a match     */
    if(strcmp(joininfo->target, joininfo->rows[i][joininfo->toindex]) == 0) break;
  }  

  if((join->values = (char ** )malloc(sizeof(char *)*join->numitems)) == NULL) {
    msSetError(MS_MEMERR, NULL, "msCSVJoinNext()");
    return(MS_FAILURE);
  }
  
  if(i == joininfo->numrows) { /* unable to do the join     */
    for(j=0; j<join->numitems; j++)
      join->values[j] = msStrdup("\0"); /* intialize to zero length strings */

    joininfo->nextrow = joininfo->numrows;
    return(MS_DONE);
  } 

  for(j=0; j<join->numitems; j++)
    join->values[j] = msStrdup(joininfo->rows[i][j]);

  joininfo->nextrow = i+1; /* so we know where to start looking next time through */

  return(MS_SUCCESS);
}
char *FLTGetIsBetweenComparisonCommonExpresssion(FilterEncodingNode *psFilterNode, layerObj *lp)
{
  const size_t bufferSize = 1024;
  char szBuffer[1024];
  char **aszBounds = NULL;
  int nBounds = 0;
  int bString=0;
  int bDateTime = 0;
  char *pszExpression=NULL, *pszTmpEscaped;

  if (!psFilterNode || !(strcasecmp(psFilterNode->pszValue, "PropertyIsBetween") == 0))
    return NULL;

  if (psFilterNode->psLeftNode == NULL || psFilterNode->psRightNode == NULL )
    return NULL;

  /* -------------------------------------------------------------------- */
  /*      Get the bounds value which are stored like boundmin;boundmax    */
  /* -------------------------------------------------------------------- */
  aszBounds = msStringSplit(psFilterNode->psRightNode->pszValue, ';', &nBounds);
  if (nBounds != 2) {
    msFreeCharArray(aszBounds, nBounds);
    return NULL;
  }

  /* -------------------------------------------------------------------- */
  /*      check if the value is a numeric value or alphanumeric. If it    */
  /*      is alphanumeric, add quotes around attribute and values.        */
  /* -------------------------------------------------------------------- */
  bString = 0;
  if (aszBounds[0]) {
    const char* pszType;
    snprintf(szBuffer,  bufferSize, "%s_type",  psFilterNode->psLeftNode->pszValue);
    pszType = msOWSLookupMetadata(&(lp->metadata), "OFG", szBuffer);
    if (pszType != NULL && (strcasecmp(pszType, "Character") == 0))
      bString = 1;
    else if (pszType != NULL && (strcasecmp(pszType, "Date") == 0))
      bDateTime = 1;
    else if (FLTIsNumeric(aszBounds[0]) == MS_FALSE)
      bString = 1;
  }
  if (!bString && !bDateTime) {
    if (aszBounds[1]) {
      if (FLTIsNumeric(aszBounds[1]) == MS_FALSE)
        bString = 1;
    }
  }

  /* -------------------------------------------------------------------- */
  /*      build expresssion.                                              */
  /* -------------------------------------------------------------------- */
  /* attribute */
  if (bString)
    sprintf(szBuffer, "%s", "(\"[");
  else
    sprintf(szBuffer, "%s", "([");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);
  
  pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);

  if (bString)
    sprintf(szBuffer, "%s", "]\" ");
  else
    sprintf(szBuffer, "%s", "] ");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  sprintf(szBuffer, "%s", " >= ");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  if (bString) {
    pszExpression = msStringConcatenate(pszExpression, "\"");
  }
  else if (bDateTime) {
    pszExpression = msStringConcatenate(pszExpression, "`");
  }

  pszTmpEscaped = msStringEscape(aszBounds[0]);
  snprintf(szBuffer, bufferSize, "%s", pszTmpEscaped);
  if(pszTmpEscaped != aszBounds[0] ) msFree(pszTmpEscaped);
  pszExpression = msStringConcatenate(pszExpression, szBuffer);
  if (bString) {
    pszExpression = msStringConcatenate(pszExpression, "\"");
  }
  else if (bDateTime) {
    pszExpression = msStringConcatenate(pszExpression, "`");
  }

  sprintf(szBuffer, "%s", " AND ");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  if (bString)
    sprintf(szBuffer, "%s", " \"[");
  else
    sprintf(szBuffer, "%s", " [");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  /* attribute */
  pszExpression = msStringConcatenate(pszExpression, psFilterNode->psLeftNode->pszValue);

  if (bString)
    sprintf(szBuffer, "%s", "]\" ");
  else
    sprintf(szBuffer, "%s", "] ");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  sprintf(szBuffer, "%s", " <= ");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);
  if (bString) {
    pszExpression = msStringConcatenate(pszExpression, "\"");
  }
  else if (bDateTime) {
    pszExpression = msStringConcatenate(pszExpression, "`");
  }
  pszTmpEscaped = msStringEscape(aszBounds[1]);
  snprintf(szBuffer, bufferSize, "%s", pszTmpEscaped);
  if (pszTmpEscaped != aszBounds[1]) msFree(pszTmpEscaped);
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  if (bString) {
    pszExpression = msStringConcatenate(pszExpression, "\"");
  }
  else if (bDateTime) {
    pszExpression = msStringConcatenate(pszExpression, "`");
  }
  sprintf(szBuffer, "%s", ")");
  pszExpression = msStringConcatenate(pszExpression, szBuffer);

  msFreeCharArray(aszBounds, nBounds);

  return pszExpression;
}
Exemple #18
0
static xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws)
{
    rectObj ext;
   
    xmlNodePtr psRootNode, psNode;
    const char *value    = NULL;
    const char *encoding = NULL;
    char *encoded=NULL;
    char *valueToFree;
    char **tokens;
    int n=0,i=0;      

    encoding = msOWSLookupMetadata(&(map->web.metadata), "FO", "encoding");
    if (!encoding)
      encoding = "ISO-8859-1";

    psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");

    /*if there is an encoding using it on some of the items*/
    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Name", lp->name, encoding);


    if (lp->name && strlen(lp->name) > 0 &&
        (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
      xmlAddSibling(psNode,
                    xmlNewComment(BAD_CAST "WARNING: The layer name '%s' might contain spaces or "
                                  "invalid characters or may start with a number. This could lead to potential problems"));
   
    value = msOWSLookupMetadata(&(lp->metadata), "FO", "title");
    if (!value)
      value =(const char*)lp->name;

    psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Title", value, encoding);

 
    value = msOWSLookupMetadata(&(lp->metadata), "FO", "abstract");
    if (value)
      psNode = msOWSCommonxmlNewChildEncoded(psRootNode, NULL, "Abstract", value, encoding);



    value = msOWSLookupMetadata(&(lp->metadata), "FO", "keywordlist");

    if (value)
    {
	if (encoding)
	  encoded = msGetEncodedString(value, encoding);
        else
          encoded = msGetEncodedString(value, "ISO-8859-1");

        msLibXml2GenerateList(
            xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
            NULL, "Keyword", encoded, ',' );
	msFree(encoded);
    }
      /*support DefaultSRS and OtherSRS*/
    valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
    if (!valueToFree)
      valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);

    if (valueToFree)
    {
        tokens = msStringSplit(valueToFree, ' ', &n);
        if (tokens && n > 0)
        {
            psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
            for (i=1; i<n; i++)
              psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);

            msFreeCharArray(tokens, n);
        }
    }
    else
      xmlAddSibling(psNode,
                    xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));

    free(valueToFree);
    valueToFree = NULL;

    /*TODO: adevertize only gml3?*/
    psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
    xmlAddChild(psRootNode, psNode);

    {
        char *formats_list = msWFSGetOutputFormatList( map, lp, "1.1.0" );
        int iformat, n;
        char **tokens;

        n = 0;
        tokens = msStringSplit(formats_list, ',', &n);

        for( iformat = 0; iformat < n; iformat++ )
            xmlNewChild(psNode, NULL, BAD_CAST "Format", 
                        BAD_CAST tokens[iformat] );
        msFree( formats_list );
        msFreeCharArray( tokens, n );
    }
  
    /*bbox*/
    if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS)
    {   
        /*convert to latlong*/
        if (lp->projection.numargs > 0)
        {
            if (!pj_is_latlong(&lp->projection.proj))
              msProjectRect(&lp->projection, NULL, &ext);
        }
        else if (map->projection.numargs > 0 && !pj_is_latlong(&map->projection.proj))
          msProjectRect(&map->projection, NULL, &ext);

        xmlAddChild(psRootNode,
                    msOWSCommonWGS84BoundingBox( psNsOws, 2,
                                                 ext.minx, ext.miny,
                                                 ext.maxx, ext.maxy));
    }
    else
    {
        xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
        xmlAddSibling(psNode,
                      xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
    }

    value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");

    if (value)
    {
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");

        if (!value)
          value = msStrdup("text/html"); /* default */

        xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");

        if (!value)
          value = msStrdup("FGDC"); /* default */

        xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
    }

    return psRootNode;
}
Exemple #19
0
int msPOSTGRESQLJoinNext(joinObj *join) {
    msPOSTGRESQLJoinInfo *joininfo = join->joininfo;
    int i, length, row_count;
    char *sql, *columns;

    /* We need a connection, and a join value. */
    if(!joininfo || !joininfo->conn) {
        msSetError(MS_JOINERR, "Join has not been connected.\n", 
                "msPOSTGRESQLJoinNext()");
        return MS_FAILURE;
    }

    if(!joininfo->from_value) {
        msSetError(MS_JOINERR, "Join has not been prepared.\n", 
                "msPOSTGRESQLJoinNext()");
        return MS_FAILURE;
    }

    /* Free the previous results. */
    if(join->values) {
        msFreeCharArray(join->values, join->numitems);
        join->values = NULL;
    }

    /* We only need to execute the query if no results exist. */
    if(!joininfo->query_result) {
        /* Write the list of column names. */
        length = 0;
        for(i = 0; i < join->numitems; i++) {
            length += 8 + strlen(join->items[i]) + 2;
        }
        
        columns = (char *)malloc(length);
        if(!columns) {
            msSetError(MS_MEMERR, "Failure to malloc.\n", 
                    "msPOSTGRESQLJoinNext()");
            return MS_FAILURE;
        }
        
        strcpy(columns, "");
        for(i = 0; i < join->numitems; i++) {
            strcat(columns, "\"");
            strcat(columns, join->items[i]);
            strcat(columns, "\"::text");
            if(i != join->numitems - 1) {
                strcat(columns, ", ");
            }
        }

        /* Create the query string. */
        sql = (char *)malloc(24 + strlen(columns) + strlen(join->table) + 
                strlen(join->to) + strlen(joininfo->from_value));
        if(!sql) {
            msSetError(MS_MEMERR, "Failure to malloc.\n", 
                    "msPOSTGRESQLJoinNext()");
            return MS_FAILURE;
        }
        sprintf(sql, "SELECT %s FROM %s WHERE %s = '%s'", columns, join->table, join->to, joininfo->from_value);
        if(joininfo->layer_debug) {
            msDebug("msPOSTGRESQLJoinNext(): executing %s.\n", sql);
        }

        free(columns);

        joininfo->query_result = PQexec(joininfo->conn, sql);
        
        if(!joininfo->query_result || 
            PQresultStatus(joininfo->query_result) != PGRES_TUPLES_OK) {
            msSetError(MS_QUERYERR, "Error executing queri %s: %s\n",
                    "msPOSTGRESQLJoinNext()", sql, 
                    PQerrorMessage(joininfo->conn));
            if(joininfo->query_result) {
                PQclear(joininfo->query_result);
                joininfo->query_result = NULL;
            }
            free(sql);
            return MS_FAILURE;
        }
        free(sql);
    }
    row_count = PQntuples(joininfo->query_result);

    /* see if we're done processing this set */
    if(joininfo->row_num >= row_count) {
        return(MS_DONE);
    }
    if(joininfo->layer_debug) {
        msDebug("msPOSTGRESQLJoinNext(): fetching row %d.\n", 
                joininfo->row_num);
    }

    /* Copy the resulting values into the joinObj. */
    join->values = (char **)malloc(sizeof(char *) * join->numitems);
    for(i = 0; i < join->numitems; i++) {
        join->values[i] = msStrdup(PQgetvalue(
                joininfo->query_result, joininfo->row_num, i));
    }

    joininfo->row_num++;

    return MS_SUCCESS;
}
Exemple #20
0
xmlNodePtr msWFSDumpLayer11(mapObj *map, layerObj *lp, xmlNsPtr psNsOws,
                            int nWFSVersion, const char* validate_language)
{
  rectObj ext;

  xmlNodePtr psRootNode, psNode;
  const char *value    = NULL;
  char *valueToFree;
  char **tokens;
  int n=0,i=0;

  psRootNode = xmlNewNode(NULL, BAD_CAST "FeatureType");

  /* add namespace to layer name */
  value = msOWSLookupMetadata(&(map->web.metadata), "FO", "namespace_prefix");

  /* FIXME? Should probably be applied to WFS 1.1 as well, but the addition */
  /* of the prefix can be disruptive for clients */
  if( value == NULL && nWFSVersion >= OWS_2_0_0 )
      value = MS_DEFAULT_NAMESPACE_PREFIX;

  if(value) {
    n = strlen(value)+strlen(lp->name)+1+1;
    valueToFree = (char *) msSmallMalloc(sizeof(char*)*n);
    snprintf(valueToFree, n, "%s%s%s", (value ? value : ""), (value ? ":" : ""), lp->name);

    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Name", BAD_CAST valueToFree);
    msFree(valueToFree);
  } else {
    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Name", BAD_CAST lp->name);
  }

  if (lp->name && strlen(lp->name) > 0 &&
      (msIsXMLTagValid(lp->name) == MS_FALSE || isdigit(lp->name[0])))
  {
    char szTmp[512];
    snprintf(szTmp, sizeof(szTmp),
             "WARNING: The layer name '%s' might contain spaces or "
             "invalid characters or may start with a number. This could lead to potential problems",
             lp->name);
    xmlAddSibling(psNode, xmlNewComment(BAD_CAST szTmp));
  }

  value = msOWSLookupMetadataWithLanguage(&(lp->metadata), "FO", "title", validate_language);
  if (!value)
    value =(const char*)lp->name;

  psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Title", BAD_CAST value);


  value = msOWSLookupMetadataWithLanguage(&(lp->metadata), "FO", "abstract", validate_language);
  if (value)
    psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "Abstract", BAD_CAST value);



  value = msOWSLookupMetadataWithLanguage(&(lp->metadata), "FO", "keywordlist", validate_language);

  if(value)
    msLibXml2GenerateList(
        xmlNewChild(psRootNode, psNsOws, BAD_CAST "Keywords", NULL),
        NULL, "Keyword", value, ',' );

  /*support DefaultSRS and OtherSRS*/
  valueToFree = msOWSGetProjURN(&(map->projection),&(map->web.metadata),"FO",MS_FALSE);
  if (!valueToFree)
    valueToFree = msOWSGetProjURN(&(lp->projection), &(lp->metadata), "FO", MS_FALSE);

  if (valueToFree) {
    tokens = msStringSplit(valueToFree, ' ', &n);
    if (tokens && n > 0) {
      if( nWFSVersion == OWS_1_1_0 )
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultSRS", BAD_CAST tokens[0]);
      else
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "DefaultCRS", BAD_CAST tokens[0]);
      for (i=1; i<n; i++)
      {
        if( nWFSVersion == OWS_1_1_0 )
          psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherSRS", BAD_CAST tokens[i]);
        else
          psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "OtherCRS", BAD_CAST tokens[i]);
      }

      msFreeCharArray(tokens, n);
    }
  } else
    xmlAddSibling(psNode,
                  xmlNewComment(BAD_CAST "WARNING: Mandatory mapfile parameter: (at least one of) MAP.PROJECTION, LAYER.PROJECTION or wfs/ows_srs metadata was missing in this context."));

  free(valueToFree);
  valueToFree = NULL;

  /*TODO: adevertize only gml3?*/
  psNode = xmlNewNode(NULL, BAD_CAST "OutputFormats");
  xmlAddChild(psRootNode, psNode);

  {
    char *formats_list = msWFSGetOutputFormatList( map, lp, nWFSVersion );
    int iformat, n;
    char **tokens;

    n = 0;
    tokens = msStringSplit(formats_list, ',', &n);

    for( iformat = 0; iformat < n; iformat++ )
      xmlNewChild(psNode, NULL, BAD_CAST "Format",
                  BAD_CAST tokens[iformat] );
    msFree( formats_list );
    msFreeCharArray( tokens, n );
  }

  /*bbox*/
  if (msOWSGetLayerExtent(map, lp, "FO", &ext) == MS_SUCCESS) {
    /*convert to latlong*/
    if (lp->projection.numargs > 0)
      msOWSProjectToWGS84(&lp->projection, &ext);
    else
      msOWSProjectToWGS84(&map->projection, &ext);

    xmlAddChild(psRootNode,
                msOWSCommonWGS84BoundingBox( psNsOws, 2,
                    ext.minx, ext.miny,
                    ext.maxx, ext.maxy));
  } else {
    xmlNewChild(psRootNode, psNsOws, BAD_CAST "WGS84BoundingBox", NULL);
    xmlAddSibling(psNode,
                  xmlNewComment(BAD_CAST "WARNING: Optional WGS84BoundingBox could not be established for this layer.  Consider setting the EXTENT in the LAYER object, or wfs_extent metadata. Also check that your data exists in the DATA statement"));
  }

  value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_href");

  if (value) {
    if( nWFSVersion >= OWS_2_0_0 )
    {
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", NULL);
        xmlNewProp(psNode, BAD_CAST "xlink:href", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_about");
        if( value != NULL )
            xmlNewProp(psNode, BAD_CAST "about", BAD_CAST value);
    }
    else
    {
        psNode = xmlNewChild(psRootNode, NULL, BAD_CAST "MetadataURL", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_format");

        if (!value)
            value = msStrdup("text/html"); /* default */

        xmlNewProp(psNode, BAD_CAST "format", BAD_CAST value);

        value = msOWSLookupMetadata(&(lp->metadata), "FO", "metadataurl_type");

        if (!value)
            value = msStrdup("FGDC"); /* default */

        xmlNewProp(psNode, BAD_CAST "type", BAD_CAST value);
    }
  }

  return psRootNode;
}
Exemple #21
0
int msMySQLJoinNext(joinObj *join) 
{
#ifndef USE_MYSQL
  msSetError(MS_QUERYERR, "MySQL support not available (compile with --with-mysql)", "msMySQLJoinNext()");
  return(MS_FAILURE);
#else
  int i, n;
	char qbuf[4000];
  msMySQLJoinInfo *joininfo = join->joininfo;

  if(!joininfo) {
    msSetError(MS_JOINERR, "Join connection has not be created.", "msMySQLJoinNext()"); 
    return(MS_FAILURE);
  }

  if(!joininfo->target) {
    msSetError(MS_JOINERR, "No target specified, run msMySQLJoinPrepare() first.", "msMySQLJoinNext()");
    return(MS_FAILURE);
  }

  /* clear any old data */
  if(join->values) { 
    msFreeCharArray(join->values, join->numitems);
    join->values = NULL;
  }

  n = joininfo->rows;
    
/* for(i=joininfo->nextrecord; i<n; i++) { // find a match */
/* if(strcmp(joininfo->target, msMySQLReadStringAttribute(joininfo->conn, i, joininfo->toindex)) == 0) break; */
/* }   */
   	snprintf(qbuf, sizeof(qbuf), "SELECT * FROM %s WHERE %s = %s", join->table, joininfo->tocolumn, joininfo->target); 
		MYDEBUG printf("%s<BR>\n", qbuf);
   	if ((joininfo->qresult = msMySQLQuery(qbuf, joininfo->conn))) /* There were some rows found, write 'em out for debug */
		{
	  		int numrows = mysql_affected_rows(joininfo->conn);
	  		int numfields = mysql_field_count(joininfo->conn);
				MYDEBUG printf("%d rows<br>\n", numrows);
        if (numrows > 0)
        {
            MYSQL_ROW row = mysql_fetch_row(joininfo->qresult);
						for(i=0; i<numfields; i++){
            	MYDEBUG printf("%s,",row[i]);
						}
           	MYDEBUG printf("<BR>\n");
						free(join->values);
						if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
							msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
							return(MS_FAILURE);
						}
						for(i=0; i<join->numitems; i++){
/* join->values[i] = msStrdup("\0"); */ /* intialize to zero length strings */
							join->values[i] = msStrdup(row[i]); /* intialize to zero length strings */
				/* rows = atoi(row[0]); */
						}
				}	else {
						if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
							msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
							return(MS_FAILURE);
						}
						for(i=0; i<join->numitems; i++)
							join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */

						return(MS_DONE);
				} 
		} else {
  		msSetError(MS_QUERYERR, "Query error (%s)", "msMySQLJoinNext()", qbuf);
			return(MS_FAILURE);
		}

#ifdef __NOTDEF__
  if(i == n) { /* unable to do the join */
    if((join->values = (char **)malloc(sizeof(char *)*join->numitems)) == NULL) {
      msSetError(MS_MEMERR, NULL, "msMySQLJoinNext()");
      return(MS_FAILURE);
    }
    for(i=0; i<join->numitems; i++)
      join->values[i] = msStrdup("\0"); /* intialize to zero length strings  */

    joininfo->nextrecord = n;
    return(MS_DONE);
  }
    
  if((join->values = msMySQLGetValues(joininfo->conn,i)) == NULL) 
    return(MS_FAILURE);

  joininfo->nextrecord = i+1; /* so we know where to start looking next time through */
#endif /* __NOTDEF__ */

  return(MS_SUCCESS);
#endif
}
Exemple #22
0
int main(int argc, char *argv[])
{
  int i,j,k;

  mapObj    	   *map=NULL;
  imageObj         *image = NULL;
     
  char **layers=NULL;
  int num_layers=0;

  int layer_found=0;

  char *outfile=NULL; /* no -o sends image to STDOUT */

  int iterations = 1;
  int draws = 0;

  for(i=1;i<argc;i++) { 
    if (strcmp(argv[i],"-c") == 0) { /* user specified number of draws */
      iterations = atoi(argv[i+1]);
      printf("We will draw %d times...\n", iterations);
      continue;
    }

    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
    {
        int debug_level = atoi(argv[++i]);

        msSetGlobalDebugLevel(debug_level);

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);

        continue;
    }
    
  }
  
  for(draws=0; draws<iterations; draws++) {

  struct mstimeval requeststarttime, requestendtime;

  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) 
      msGettimeofday(&requeststarttime, NULL);
      
  if(argc > 1 && strcmp(argv[1], "-v") == 0) {
    printf("%s\n", msGetVersion());
    exit(0);
  }

  /* ---- check the number of arguments, return syntax if not correct ---- */
  if( argc < 3 ) {
    fprintf(stdout, "\nPurpose: convert a mapfile to an image\n\n");
    fprintf(stdout,
            "Syntax: shp2img -m mapfile [-o image] [-e minx miny maxx maxy] [-s sizex sizey]\n"
            "               [-l \"layer1 [layers2...]\"] [-i format]\n"
            "               [-all_debug n] [-map_debug n] [-layer_debug n] [-p n] [-c n] [-d layername datavalue]\n");


    fprintf(stdout,"  -m mapfile: Map file to operate on - required\n" );
    fprintf(stdout,"  -i format: Override the IMAGETYPE value to pick output format\n" );
    fprintf(stdout,"  -o image: output filename (stdout if not provided)\n");
    fprintf(stdout,"  -e minx miny maxx maxy: extents to render\n");
    fprintf(stdout,"  -s sizex sizey: output image size\n");
    fprintf(stdout,"  -l layers: layers / groups to enable - make sure they are quoted and space seperated if more than one listed\n" );
    fprintf(stdout,"  -all_debug n: Set debug level for map and all layers\n" );
    fprintf(stdout,"  -map_debug n: Set map debug level\n" );
    fprintf(stdout,"  -layer_debug layer_name n: Set layer debug level\n" );
    fprintf(stdout,"  -c n: draw map n number of times\n" );
    fprintf(stdout,"  -p n: pause for n seconds after reading the map\n" );
    fprintf(stdout,"  -d layername datavalue: change DATA value for layer\n" );


    exit(0);
  }

  if ( msSetup() != MS_SUCCESS )
  {
      msWriteError(stderr);
      exit(1);
  }
 
  /* Use MS_ERRORFILE and MS_DEBUGLEVEL env vars if set */
  if ( msDebugInitFromEnv() != MS_SUCCESS )
  {
      msWriteError(stderr);
      msCleanup(0);
      exit(1);
  }

  for(i=1;i<argc;i++) { /* Step though the user arguments, 1st to find map file */
 
    if(strcmp(argv[i],"-m") == 0) {
      map = msLoadMap(argv[i+1], NULL);
      if(!map) {
	msWriteError(stderr);
        msCleanup(0);
	exit(1);
      }
      msApplyDefaultSubstitutions(map);
    }
  }

  if(!map) {
    fprintf(stderr, "Mapfile (-m) option not specified.\n");
    msCleanup(0);
    exit(1);
  }


  for(i=1;i<argc;i++) { /* Step though the user arguments */

    if(strcmp(argv[i],"-m") == 0) { /* skip it */
      i+=1;
    }

    if(strcmp(argv[i],"-p") == 0) {
        int pause_length = atoi(argv[i+1]);
        time_t start_time = time(NULL);

        printf( "Start pause of %d seconds.\n", pause_length );
        while( time(NULL) < start_time + pause_length ) {}
        printf( "Done pause.\n" );
            
        i+=1;
    }

    if(strcmp(argv[i],"-o") == 0) { /* load the output image filename */
      outfile = argv[i+1];
      i+=1;
    }
    
    if(strcmp(argv[i],"-i") == 0) { 
      outputFormatObj *format;

      format = msSelectOutputFormat( map, argv[i+1] );

      if( format == NULL )
          printf( "No such OUTPUTFORMAT as %s.\n", argv[i+1] );
      else
      {
          msFree( (char *) map->imagetype );
          map->imagetype = msStrdup( argv[i+1] );
          msApplyOutputFormat( &(map->outputformat), format, 
                               map->transparent, map->interlace, 
                               map->imagequality );
      }
      i+=1;
    }

    if(strcmp(argv[i],"-d") == 0) { /* swap layer data */
      for(j=0; j<map->numlayers; j++) {
	 if(strcmp(GET_LAYER(map, j)->name, argv[i+1]) == 0) {
	   free(GET_LAYER(map, j)->data);
	   GET_LAYER(map, j)->data = msStrdup(argv[i+2]);
	   break;
	 }
      }
      i+=2;
    }

    if(strcmp(argv[i], "-all_debug") == 0 && i < argc-1 ) /* global debug */
    {
        int debug_level = atoi(argv[++i]);

        /* msSetGlobalDebugLevel() already called. Just need to force debug
         * level in map and all layers
         */
        map->debug = debug_level;
        for(j=0; j<map->numlayers; j++) {
            GET_LAYER(map, j)->debug = debug_level;
        }

    }
    
    if(strcmp(argv[i], "-map_debug") == 0 && i < argc-1 ) /* debug */
    {
        map->debug = atoi(argv[++i]);

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);
    }
    
    if(strcmp(argv[i], "-layer_debug") == 0 && i < argc-1 ) /* debug */
    {
        const char *layer_name = argv[++i];
        int debug_level = atoi(argv[++i]);
        int got_layer = 0;

        for(j=0; j<map->numlayers; j++) {
            if(strcmp(GET_LAYER(map, j)->name,layer_name) == 0 ) {
                GET_LAYER(map, j)->debug = debug_level;
                got_layer = 1;
            }
        }
        if( !got_layer )
            fprintf( stderr, 
                     " Did not find layer '%s' from -layer_debug switch.\n", 
                     layer_name );

        /* Send output to stderr by default */ 
        if (msGetErrorFile() == NULL)
            msSetErrorFile("stderr", NULL);
    }
    
    if(strcmp(argv[i],"-e") == 0) { /* change extent */
        if( argc <= i+4 ) {
            fprintf( stderr, 
                     "Argument -e needs 4 space separated numbers as argument.\n" ); 
            msCleanup(0);
            exit(1);
        }
      map->extent.minx = atof(argv[i+1]);
      map->extent.miny = atof(argv[i+2]);
      map->extent.maxx = atof(argv[i+3]);
      map->extent.maxy = atof(argv[i+4]);
      i+=4;
    }

    if (strcmp(argv[i], "-s") == 0) {
      msMapSetSize(map, atoi(argv[i+1]), atoi(argv[i+2]));
      i+=2;
    }    

    if(strcmp(argv[i],"-l") == 0) { /* load layer list */
      layers = msStringSplit(argv[i+1], ' ', &(num_layers));

      for(j=0; j<num_layers; j++) { /* loop over -l */
          layer_found=0;
          for(k=0; k<map->numlayers; k++) {
              if((GET_LAYER(map, k)->name && strcasecmp(GET_LAYER(map, k)->name, layers[j]) == 0) || (GET_LAYER(map, k)->group && strcasecmp(GET_LAYER(map, k)->group, layers[j]) == 0)) {
                  layer_found = 1;
                  break;
              }
          }
          if (layer_found==0) {
              fprintf(stderr, "Layer (-l) \"%s\" not found\n", layers[j]);
              msCleanup(0);
              exit(1);
          }
      }

      for(j=0; j<map->numlayers; j++) {
          if(GET_LAYER(map, j)->status == MS_DEFAULT)
              continue;
          else {
              GET_LAYER(map, j)->status = MS_OFF;
              for(k=0; k<num_layers; k++) {
                  if((GET_LAYER(map, j)->name && strcasecmp(GET_LAYER(map, j)->name, layers[k]) == 0) ||
                     (GET_LAYER(map, j)->group && strcasecmp(GET_LAYER(map, j)->group, layers[k]) == 0)) {
                      GET_LAYER(map, j)->status = MS_ON;
                      break;
                  }
              }
          }
      }

      msFreeCharArray(layers, num_layers);

      i+=1;
     }
  }
  
  image = msDrawMap(map, MS_FALSE);

  if(!image) {
    msWriteError(stderr);

    msFreeMap(map);
    msCleanup(0);
    exit(1);
  }

  if( msSaveImage(map, image, outfile) != MS_SUCCESS ) {
    msWriteError(stderr);
  }

  msFreeImage(image);
  msFreeMap(map);

  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
    msGettimeofday(&requestendtime, NULL);
    msDebug("shp2img total time: %.3fs\n", 
            (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
            (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
  }

  msCleanup(0);

} /*   for(draws=0; draws<iterations; draws++) { */
  return(0);
} /* ---- END Main Routine ---- */
Exemple #23
0
int main(int argc, char *argv[])
{
  int iArg;
  int sendheaders = MS_TRUE;
  struct mstimeval execstarttime, execendtime;
  struct mstimeval requeststarttime, requestendtime;
  mapservObj* mapserv = NULL;

  /* -------------------------------------------------------------------- */
  /*      Initialize mapserver.  This sets up threads, GD and GEOS as     */
  /*      well as using MS_ERRORFILE and MS_DEBUGLEVEL env vars if set.   */
  /* -------------------------------------------------------------------- */
  if( msSetup() != MS_SUCCESS ) {
    msCGIWriteError(mapserv);
    msCleanup(0);
    exit(0);
  }

  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING)
    msGettimeofday(&execstarttime, NULL);

  /* -------------------------------------------------------------------- */
  /*      Process arguments.  In normal use as a cgi-bin there are no     */
  /*      commandline switches, but we provide a few for test/debug       */
  /*      purposes, and to query the version info.                        */
  /* -------------------------------------------------------------------- */
  for( iArg = 1; iArg < argc; iArg++ ) {
    /* Keep only "-v", "-nh" and "QUERY_STRING=..." enabled by default.
     * The others will require an explicit -DMS_ENABLE_CGI_CL_DEBUG_ARGS
     * at compile time.
     */
    if( strcmp(argv[iArg],"-v") == 0 ) {
      printf("%s\n", msGetVersion());
      fflush(stdout);
      exit(0);
    } else if(strcmp(argv[iArg], "-nh") == 0) {
      sendheaders = MS_FALSE;
    } else if( strncmp(argv[iArg], "QUERY_STRING=", 13) == 0 ) {
      /* Debugging hook... pass "QUERY_STRING=..." on the command-line */
      putenv( "REQUEST_METHOD=GET" );
      putenv( argv[iArg] );
    }
#ifdef MS_ENABLE_CGI_CL_DEBUG_ARGS
    else if( iArg < argc-1 && strcmp(argv[iArg], "-tmpbase") == 0) {
      msForceTmpFileBase( argv[++iArg] );
    } else if( iArg < argc-1 && strcmp(argv[iArg], "-t") == 0) {
      char **tokens;
      int numtokens=0;

      if((tokens=msTokenizeMap(argv[iArg+1], &numtokens)) != NULL) {
        int i;
        for(i=0; i<numtokens; i++)
          printf("%s\n", tokens[i]);
        msFreeCharArray(tokens, numtokens);
      } else {
        msCGIWriteError(mapserv);
      }

      exit(0);
    } else if( strncmp(argv[iArg], "MS_ERRORFILE=", 13) == 0 ) {
      msSetErrorFile( argv[iArg] + 13, NULL );
    } else if( strncmp(argv[iArg], "MS_DEBUGLEVEL=", 14) == 0) {
      msSetGlobalDebugLevel( atoi(argv[iArg] + 14) );
    }
#endif /* MS_ENABLE_CGI_CL_DEBUG_ARGS */
    else {
      /* we don't produce a usage message as some web servers pass junk arguments */
    }
  }

  /* -------------------------------------------------------------------- */
  /*      Setup cleanup magic, mainly for FastCGI case.                   */
  /* -------------------------------------------------------------------- */
#ifndef WIN32
  signal( SIGUSR1, msCleanupOnSignal );
  signal( SIGTERM, msCleanupOnSignal );
#endif

#ifdef USE_FASTCGI
  msIO_installFastCGIRedirect();

#ifdef WIN32
  atexit( msCleanupOnExit );
#endif

  /* In FastCGI case we loop accepting multiple requests.  In normal CGI */
  /* use we only accept and process one request.  */
  while( FCGI_Accept() >= 0 ) {
#endif /* def USE_FASTCGI */

    /* -------------------------------------------------------------------- */
    /*      Process a request.                                              */
    /* -------------------------------------------------------------------- */
    mapserv = msAllocMapServObj();
    mapserv->sendheaders = sendheaders; /* override the default if necessary (via command line -nh switch) */

    mapserv->request->NumParams = loadParams(mapserv->request, NULL, NULL, 0, NULL);
    if( mapserv->request->NumParams == -1 ) {
      msCGIWriteError(mapserv);
      goto end_request;
    }

    mapserv->map = msCGILoadMap(mapserv);
    if(!mapserv->map) {
      msCGIWriteError(mapserv);
      goto end_request;
    }

    if( mapserv->map->debug >= MS_DEBUGLEVEL_TUNING)
      msGettimeofday(&requeststarttime, NULL);

#ifdef USE_FASTCGI
    if( mapserv->map->debug ) {
      static int nRequestCounter = 1;

      msDebug( "CGI Request %d on process %d\n", nRequestCounter, getpid() );
      nRequestCounter++;
    }
#endif




    if(msCGIDispatchRequest(mapserv) != MS_SUCCESS) {
      msCGIWriteError(mapserv);
      goto end_request;
    }


end_request:
    if(mapserv) {
      if(mapserv->map && mapserv->map->debug >= MS_DEBUGLEVEL_TUNING) {
        msGettimeofday(&requestendtime, NULL);
        msDebug("mapserv request processing time (msLoadMap not incl.): %.3fs\n",
                (requestendtime.tv_sec+requestendtime.tv_usec/1.0e6)-
                (requeststarttime.tv_sec+requeststarttime.tv_usec/1.0e6) );
      }
      msCGIWriteLog(mapserv,MS_FALSE);
      msFreeMapServObj(mapserv);
    }
#ifdef USE_FASTCGI
    /* FCGI_ --- return to top of loop */
    msResetErrorList();
    continue;
  } /* end fastcgi loop */
#endif

  /* normal case, processing is complete */
  if(msGetGlobalDebugLevel() >= MS_DEBUGLEVEL_TUNING) {
    msGettimeofday(&execendtime, NULL);
    msDebug("mapserv total execution time: %.3fs\n",
            (execendtime.tv_sec+execendtime.tv_usec/1.0e6)-
            (execstarttime.tv_sec+execstarttime.tv_usec/1.0e6) );
  }
  msCleanup(0);

#ifdef _WIN32
  /* flush pending writes to stdout */
  fflush(stdout);
#endif

  exit( 0 );
}
Exemple #24
0
int _msValidateTime(const char *timestring,  const char *timeextent)
{
  int numelements, numextents, i, numranges;
  struct tm  tmtimestart, tmtimeend, tmstart, tmend;
  char **atimerange = NULL, **atimeelements= NULL, **atimeextents=NULL;

  if (!timestring || !timeextent)
    return MS_FALSE;

  if (strlen(timestring) <= 0 ||
      strlen(timeextent) <= 0)
    return MS_FALSE;


  /* we first need to parse the timesting that is passed
     so that we can determine if it is a descrete time
     or a range */

  numelements = 0;
  atimeelements = msStringSplit (timestring, '/', &numelements);
  msTimeInit(&tmtimestart);
  msTimeInit(&tmtimeend);

  if (numelements == 1) { /*descrete time*/
    /*start end end times are the same*/
    if (msParseTime(timestring, &tmtimestart) != MS_TRUE) {
      msFreeCharArray(atimeelements, numelements);
      return  MS_FALSE;
    }
    if (msParseTime(timestring, &tmtimeend) != MS_TRUE) {
      msFreeCharArray(atimeelements, numelements);
      return  MS_FALSE;
    }
  } else if (numelements >=2) { /*range */
    if (msParseTime(atimeelements[0], &tmtimestart) != MS_TRUE) {
      msFreeCharArray(atimeelements, numelements);
      return  MS_FALSE;
    }
    if (msParseTime(atimeelements[1], &tmtimeend) != MS_TRUE) {
      msFreeCharArray(atimeelements, numelements);
      return  MS_FALSE;
    }
  }

  msFreeCharArray(atimeelements, numelements);


  /* Now parse the time extent. Extents can be
    -  one range (2004-09-21/2004-09-25/resolution)
    -  multiple rages 2004-09-21/2004-09-25/res1,2004-09-21/2004-09-25/res2
    - one value 2004-09-21
    - mutiple values 2004-09-21,2004-09-22,2004-09-23
  */

  numextents = 0;
  atimeextents = msStringSplit (timeextent, ',', &numextents);
  if (numextents <= 0) {
    msFreeCharArray(atimeextents, numextents);
    return MS_FALSE;
  }

  /*the time timestring should at be valid in one of the extents
    defined */

  for (i=0; i<numextents; i++) {
    /* build time structure for the extents */
    msTimeInit(&tmstart);
    msTimeInit(&tmend);

    numranges = 0;
    atimerange = msStringSplit (atimeextents[i], '/', &numranges);
    /* - one value 2004-09-21 */
    if (numranges == 1) {
      /*time tested can either be descrete or a range */

      if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
          msParseTime(atimerange[0], &tmend) == MS_TRUE &&
          msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
          msTimeCompare(&tmend, &tmtimeend) >= 0) {
        msFreeCharArray(atimerange, numranges);
        msFreeCharArray(atimeextents, numextents);
        return MS_TRUE;
      }
    }
    /*2004-09-21/2004-09-25/res1*/
    else if (numranges >= 2) {
      if (msParseTime(atimerange[0], &tmstart) == MS_TRUE &&
          msParseTime(atimerange[1], &tmend) == MS_TRUE &&
          msTimeCompare(&tmstart, &tmtimestart) <= 0 &&
          msTimeCompare(&tmend, &tmtimeend) >= 0) {
        msFreeCharArray(atimerange, numranges);
        msFreeCharArray(atimeextents, numextents);
        return MS_TRUE;
      }
    }
    msFreeCharArray(atimerange, numranges);


  }
  msFreeCharArray(atimeextents, numextents);
  return MS_FALSE;

}
Exemple #25
0
int msWFSLayerWhichShapes(layerObj *lp, rectObj rect, int isQuery)
{
#ifdef USE_WFS_LYR
  msWFSLayerInfo *psInfo;
  int status = MS_SUCCESS;
  const char *pszTmp;
  FILE *fp;

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


  psInfo =(msWFSLayerInfo*)lp->wfslayerinfo;

  if (psInfo == NULL) {
    msSetError(MS_WFSCONNERR, "Assertion failed: WFS layer not opened!!!",
               "msWFSLayerWhichShapes()");
    return(MS_FAILURE);
  }

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

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

    ext.minx = atof(tokens[0]);
    ext.miny = atof(tokens[1]);
    ext.maxx = atof(tokens[2]);
    ext.maxy = atof(tokens[3]);

    msFreeCharArray(tokens, n);

    /* Reproject latlonboundingbox to the selected SRS for the layer and */
    /* check if it overlaps the bbox that we calculated for the request */

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


  /* ------------------------------------------------------------------
   * __TODO__ If new bbox differs from current one then we should
   * invalidate current GML file in cache
   * ------------------------------------------------------------------ */
  psInfo->rect = rect;


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

    msHTTPInitRequestObj(asReqInfo, 2);

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

    /* Cleanup */
    msHTTPFreeRequestObj(asReqInfo, numReq);

  }

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

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

  /* ------------------------------------------------------------------
   * Check that file is really GML... it could be an exception, or just junk.
   * ------------------------------------------------------------------ */
  if ((fp = fopen(psInfo->pszGMLFilename, "r")) != NULL) {
    char szHeader[2000];
    int  nBytes = 0;

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

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

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

    }
    if ( strstr(szHeader, "<WFS_Exception>") ||
         strstr(szHeader, "<ServiceExceptionReport>") ) {
      msOWSProcessException(lp, psInfo->pszGMLFilename,
                            MS_WFSCONNERR, "msWFSLayerWhichShapes()" );
      return MS_FAILURE;
    } else if ( strstr(szHeader,"opengis.net/gml") &&
                strstr(szHeader,"featureMember>") == NULL ) {
      /* This looks like valid GML, but contains 0 features. */
      return MS_DONE;
    } else if ( strstr(szHeader,"opengis.net/gml") == NULL ||
                strstr(szHeader,"featureMember>") == NULL ) {
      /* This is probably just junk. */
      msSetError(MS_WFSCONNERR,
                 "WFS request produced unexpected output (junk?) for layer %s.",
                 "msWFSLayerWhichShapes()",
                 lp->name?lp->name:"(null)");
      return(MS_FAILURE);
    }

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


  /* ------------------------------------------------------------------
   * Open GML file using OGR.
   * ------------------------------------------------------------------ */
  if ((status = msOGRLayerOpen(lp, psInfo->pszGMLFilename)) != MS_SUCCESS)
    return status;

  status = msOGRLayerWhichShapes(lp, rect, isQuery);

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

  return status;
#else
  /* ------------------------------------------------------------------
   * WFS CONNECTION Support not included...
   * ------------------------------------------------------------------ */
  msSetError(MS_WFSCONNERR, "WFS CLIENT CONNECTION support is not available.",
             "msWFSLayerWhichShapes()");
  return(MS_FAILURE);

#endif /* USE_WFS_LYR */
}
char *msAlignText(mapObj *map, labelObj *label, char *text)
{
  double spacewidth=0.0; /*size of a single space, in fractional pixels*/
  int numlines;
  char **textlines,*newtext,*newtextptr;
  int *textlinelengths,*numspacesforpadding;
  int numspacestoadd,maxlinelength,i;
  rectObj label_rect;
  if(!msCountChars(text,'\n'))
    return text; /*only one line*/

  /*split text into individual lines
   * TODO: check if splitting on \n is utf8 safe*/
  textlines = msStringSplit(text,'\n',&numlines);

  /*
   * label->space_size_10 contains a cache for the horizontal size of a single
   * 'space' character, at size 10 for the current label
   * FIXME: in case of attribute binding for the FONT of the label, this cache will
   * be wrong for labels where the attributed font is different than the first
   * computed font. This shouldn't happen too often, and hopefully the size of a
   * space character shouldn't vary too much between different fonts*/
  if(label->space_size_10 == 0.0) {
    /*if the cache hasn't been initialized yet, or with pixmap fonts*/

    /* compute the size of 16 adjacent spaces. we can't do this for just one space,
     * as the labelSize computing functions return integer bounding boxes. we assume
     * that the integer rounding for such a number of spaces will be negligeable
     * compared to the actual size of thoses spaces */
    if(msGetLabelSize(map,label,".              .",10.0,&label_rect,NULL) != MS_SUCCESS) {
      /*error computing label size, we can't continue*/

      /*free the previously allocated split text*/
      while(numlines--)
        free(textlines[numlines]);
      free(textlines);
      return text;
    }

    /* this is the size of a single space character. for truetype fonts,
     * it's the size of a 10pt space. For pixmap fonts, it's the size
     * for the current label */
    spacewidth = (label_rect.maxx-label_rect.minx)/16.0;
    if(label->type == MS_TRUETYPE) {
      label->space_size_10=spacewidth; /*cache the computed size*/

      /*size of a space for current label size*/
      spacewidth = spacewidth * (double)label->size/10.0;
    }
  } else {
    spacewidth = label->space_size_10 * (double)label->size/10.0;
  }
  spacewidth = MS_MAX(1,spacewidth);


  /*length in pixels of each line*/
  textlinelengths = (int*)msSmallMalloc(numlines*sizeof(int));

  /*number of spaces that need to be added to each line*/
  numspacesforpadding = (int*)msSmallMalloc(numlines*sizeof(int));

  /*total number of spaces that need to be added*/
  numspacestoadd=0;

  /*length in pixels of the longest line*/
  maxlinelength=0;
  for(i=0; i<numlines; i++) {
    if(MS_SUCCESS != msGetLabelSize(map,label,textlines[i],label->size, &label_rect,NULL)) {
      msFreeCharArray(textlines,numlines);
      msFree(textlinelengths);
      msFree(numspacesforpadding);
      return text;
    }
    textlinelengths[i] = label_rect.maxx-label_rect.minx;
    if(maxlinelength<textlinelengths[i])
      maxlinelength=textlinelengths[i];
  }
  for(i=0; i<numlines; i++) {
    /* number of spaces to add so the current line is
     * as long as the longest line */
    double nfracspaces = (maxlinelength - textlinelengths[i])/spacewidth;

    if(label->align == MS_ALIGN_CENTER) {
      numspacesforpadding[i]=MS_NINT(nfracspaces/2.0);
    } else {
      if(label->align == MS_ALIGN_RIGHT) {
        numspacesforpadding[i]=MS_NINT(nfracspaces);
      }
    }
    numspacestoadd+=numspacesforpadding[i];
  }

  /*allocate new text with room for the additional spaces needed*/
  newtext = (char*)msSmallMalloc(strlen(text)+1+numspacestoadd);
  newtextptr=newtext;
  for(i=0; i<numlines; i++) {
    int j;
    /*padd beginning of line with needed spaces*/
    for(j=0; j<numspacesforpadding[i]; j++) {
      *(newtextptr++)=' ';
    }
    /*copy original line*/
    strcpy(newtextptr,textlines[i]);
    /*place pointer at the char right after the current line*/
    newtextptr+=strlen(textlines[i])+1;
    if(i!=numlines-1) {
      /*put the \n back in (was taken away by msStringSplit)*/
      *(newtextptr-1)='\n';
    }
  }
  /*free the original text*/
  free(text);
  for(i=0; i<numlines; i++) {
    free(textlines[i]);
  }
  free(textlines);
  free(textlinelengths);
  free(numspacesforpadding);

  /*return the aligned text. note that the terminating \0 was added by the last
   * call to strcpy */
  return newtext;
}