]> git.openstreetmap.org Git - nominatim.git/commitdiff
Merge remote-tracking branch 'upstream/master'
authorSarah Hoffmann <lonvia@denofr.de>
Wed, 9 Mar 2016 22:28:33 +0000 (23:28 +0100)
committerSarah Hoffmann <lonvia@denofr.de>
Wed, 9 Mar 2016 22:28:33 +0000 (23:28 +0100)
1  2 
lib/Geocode.php
lib/init-website.php
lib/lib.php
tests/features/api/search_params.feature
website/reverse.php

diff --combined lib/Geocode.php
index afeaf68767614dae8165a1533c509bbb59dcd3ff,1dbde919d4fda8975763af3e79d300206c6737a0..48055ec6780cbfe708a843e33070fc7ed869c22d
@@@ -1,4 -1,6 +1,6 @@@
  <?php
+       require_once(CONST_BasePath.'/lib/PlaceLookup.php');
        class Geocode
        {
                protected $oDB;
@@@ -18,7 -20,7 +20,7 @@@
  
                protected $aExcludePlaceIDs = array();
                protected $bDeDupe = true;
 -              protected $bReverseInPlan = false;
 +              protected $bReverseInPlan = true;
  
                protected $iLimit = 20;
                protected $iFinalLimit = 10;
                                $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
                                $sSQL .= "group by place_id";
                                if (!$this->bDeDupe) $sSQL .= ",place_id ";
 +                              /*
                                $sSQL .= " union ";
                                $sSQL .= "select 'L' as osm_type,place_id as osm_id,'place' as class,'house' as type,null as admin_level,30 as rank_search,30 as rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id,'us' as country_code,";
                                $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
                                $sSQL .= "group by place_id";
                                if (!$this->bDeDupe) $sSQL .= ",place_id";
                                $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
 +                              */
                        }
  
                        $sSQL .= " order by importance desc";
                function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
                {
                        /*
-                          Calculate all searches using aValidTokens i.e.
-                          'Wodsworth Road, Sheffield' =>
+                                Calculate all searches using aValidTokens i.e.
+                                'Wodsworth Road, Sheffield' =>
  
-                          Phrase Wordset
-                          0      0       (wodsworth road)
-                          0      1       (wodsworth)(road)
-                          1      0       (sheffield)
+                                Phrase Wordset
+                                0      0       (wodsworth road)
+                                0      1       (wodsworth)(road)
+                                1      0       (sheffield)
  
-                          Score how good the search is so they can be ordered
+                                Score how good the search is so they can be ordered
                         */
                        foreach($aPhrases as $iPhrase => $sPhrase)
                        {
                /* Perform the actual query lookup.
  
                        Returns an ordered list of results, each with the following fields:
-                         osm_type: type of corresponding OSM object
+                               osm_type: type of corresponding OSM object
                                                        N - node
                                                        W - way
                                                        R - relation
                                                        P - postcode (internally computed)
-                         osm_id: id of corresponding OSM object
-                         class: general object class (corresponds to tag key of primary OSM tag)
-                         type: subclass of object (corresponds to tag value of primary OSM tag)
-                         admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
-                         rank_search: rank in search hierarchy
+                               osm_id: id of corresponding OSM object
+                               class: general object class (corresponds to tag key of primary OSM tag)
+                               type: subclass of object (corresponds to tag value of primary OSM tag)
+                               admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
+                               rank_search: rank in search hierarchy
                                                        (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
-                         rank_address: rank in address hierarchy (determines orer in address)
-                         place_id: internal key (may differ between different instances)
-                         country_code: ISO country code
-                         langaddress: localized full address
-                         placename: localized name of object
-                         ref: content of ref tag (if available)
-                         lon: longitude
-                         lat: latitude
-                         importance: importance of place based on Wikipedia link count
-                         addressimportance: cumulated importance of address elements
-                         extra_place: type of place (for admin boundaries, if there is a place tag)
-                         aBoundingBox: bounding Box
-                         label: short description of the object class/type (English only) 
-                         name: full name (currently the same as langaddress)
-                         foundorder: secondary ordering for places with same importance
+                               rank_address: rank in address hierarchy (determines orer in address)
+                               place_id: internal key (may differ between different instances)
+                               country_code: ISO country code
+                               langaddress: localized full address
+                               placename: localized name of object
+                               ref: content of ref tag (if available)
+                               lon: longitude
+                               lat: latitude
+                               importance: importance of place based on Wikipedia link count
+                               addressimportance: cumulated importance of address elements
+                               extra_place: type of place (for admin boundaries, if there is a place tag)
+                               aBoundingBox: bounding Box
+                               label: short description of the object class/type (English only) 
+                               name: full name (currently the same as langaddress)
+                               foundorder: secondary ordering for places with same importance
                */
                function lookup()
                {
                        {
                                // Start with a blank search
                                $aSearches = array(
-                                       array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
-                                             'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
-                                             'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
+                                       array('iSearchRank' => 0, 
+                                                               'iNamePhrase' => -1, 
+                                                               'sCountryCode' => false, 
+                                                               'aName' => array(), 
+                                                               'aAddress' => array(), 
+                                                               'aFullNameAddress' => array(),
+                                                               'aNameNonSearch' => array(), 
+                                                               'aAddressNonSearch' => array(),
+                                                               'sOperator' => '', 
+                                                               'aFeatureName' => array(), 
+                                                               'sClass' => '', 
+                                                               'sType' => '', 
+                                                               'sHouseNumber' => '', 
+                                                               'fLat' => '', 
+                                                               'fLon' => '', 
+                                                               'fRadius' => ''
+                                                       )
                                );
  
                                // Do we have a radius search?
                                                                {
                                                                        $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
                                                                        if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
-                                     if ($bBoundingBoxSearch)
-                                         $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
+                                                                       if ($bBoundingBoxSearch)
+                                                                               $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
                                                                        $sSQL .= " order by st_area(geometry) desc limit 1";
                                                                        if (CONST_Debug) var_dump($sSQL);
                                                                        $aPlaceIDs = $this->oDB->getCol($sSQL);
                                                        // TODO: filter out the pointless search terms (2 letter name tokens and less)
                                                        // they might be right - but they are just too darned expensive to run
                                                        if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
 -                                                      if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
 +                                                      //if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
                                                        if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
                                                        {
                                                                // For infrequent name terms disable index usage for address
                                                                                sizeof($aSearch['aName']) == 1 &&
                                                                                $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
                                                                {
 -                                                                      $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
 +                                                                      //$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
 +                                                                      $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
                                                                }
                                                                else
                                                                {
                                                                        $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
 -                                                                      if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
 +                                                                      //if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
                                                                }
                                                        }
                                                        if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
                                                                $aPlaceIDs = $this->oDB->getCol($sSQL);
  
                                                                // If not try the aux fallback table
 +                                                              /*
                                                                if (!sizeof($aPlaceIDs))
                                                                {
                                                                        $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
                                                                        if (CONST_Debug) var_dump($sSQL);
                                                                        $aPlaceIDs = $this->oDB->getCol($sSQL);
                                                                }
 +                                                              */
  
                                                                if (!sizeof($aPlaceIDs))
                                                                {
                                if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
                        }
  
-             if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
+                       if (CONST_Debug) { echo '<i>Recheck words:<\i>'; var_dump($aRecheckWords); }
  
                        foreach($aSearchResults as $iResNum => $aResult)
                        {
                                // Default
-                               $fDiameter = 0.0001;
-                               if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
-                                               && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
-                               {
-                                       $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
-                               }
-                               elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
-                                               && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
-                               {
-                                       $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
-                               }
-                               $fRadius = $fDiameter / 2;
-                               if (CONST_Search_AreaPolygons)
-                               {
-                                       // Get the bounding box and outline polygon
-                                       $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
-                                       $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
-                                       $sSQL .= "ST_YMin(geometry) as minlat,ST_YMax(geometry) as maxlat,";
-                                       $sSQL .= "ST_XMin(geometry) as minlon,ST_XMax(geometry) as maxlon";
-                                       if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
-                                       if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
-                                       if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
-                                       if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
-                                       $sFrom = " from placex where place_id = ".$aResult['place_id'];
-                                       if ($this->fPolygonSimplificationThreshold > 0)
-                                       {
-                                               $sSQL .= " from (select place_id,centroid,ST_SimplifyPreserveTopology(geometry,".$this->fPolygonSimplificationThreshold.") as geometry".$sFrom.") as plx";
-                                       }
-                                       else
-                                       {
-                                               $sSQL .= $sFrom;
-                                       }
+                               $fDiameter = getResultDiameter($aResult);
  
-                                       $aPointPolygon = $this->oDB->getRow($sSQL);
-                                       if (PEAR::IsError($aPointPolygon))
-                                       {
-                                               failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
-                                       }
+                               $oPlaceLookup = new PlaceLookup($this->oDB);
+                               $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
+                               $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
+                               $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
+                               $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
+                               $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
+                               $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
  
-                                       if ($aPointPolygon['place_id'])
-                                       {
-                                               if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
-                                               if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
-                                               if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
-                                               if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
-                                               if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
-                                               {
-                                                       $aResult['lat'] = $aPointPolygon['centrelat'];
-                                                       $aResult['lon'] = $aPointPolygon['centrelon'];
-                                               }
-                                               if ($this->bIncludePolygonAsPoints)
-                                               {
-                                                       // Translate geometry string to point array
-                                                       if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
-                                                       {
-                                                               preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
-                                                       }
-                             /*
-                                                       elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
-                                                       {
-                                                               preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
-                                                       }
-                             */
-                                                       elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
-                                                       {
-                                                               $iSteps = max(8, min(100, ($fRadius * 40000)^2));
-                                                               $fStepSize = (2*pi())/$iSteps;
-                                                               $aPolyPoints = array();
-                                                               for($f = 0; $f < 2*pi(); $f += $fStepSize)
-                                                               {
-                                                                       $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
-                                                               }
-                                                       }
-                                               }
-                                               // Output data suitable for display (points and a bounding box)
-                                               if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
-                                               {
-                                                       $aResult['aPolyPoints'] = array();
-                                                       foreach($aPolyPoints as $aPoint)
-                                                       {
-                                                               $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
-                                                       }
-                                               }
-                                               if (abs($aPointPolygon['minlat'] - $aPointPolygon['maxlat']) < 0.0000001)
-                                               {
-                                                       $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
-                                                       $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
-                                               }
-                                               if (abs($aPointPolygon['minlon'] - $aPointPolygon['maxlon']) < 0.0000001)
-                                               {
-                                                       $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
-                                                       $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
-                                               }
-                                               $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
-                                       }
-                               }
+                               $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
+                               $aResult = array_merge($aResult, $aOutlineResult);
  
                                if ($aResult['extra_place'] == 'city')
                                {
                                        $aResult['rank_search'] = 16;
                                }
  
-                               if (!isset($aResult['aBoundingBox']))
-                               {
-                                       $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
-                                       $fStepSize = (2*pi())/$iSteps;
-                                       $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
-                                       $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
-                                       $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
-                                       $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
-                                       // Output data suitable for display (points and a bounding box)
-                                       if ($this->bIncludePolygonAsPoints)
-                                       {
-                                               $aPolyPoints = array();
-                                               for($f = 0; $f < 2*pi(); $f += $fStepSize)
-                                               {
-                                                       $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
-                                               }
-                                               $aResult['aPolyPoints'] = array();
-                                               foreach($aPolyPoints as $aPoint)
-                                               {
-                                                       $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
-                                               }
-                                       }
-                                       $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
-                               }
                                // Is there an icon set for this type of result?
                                if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
                                                && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
diff --combined lib/init-website.php
index 013aee4b4a1c07daf07dde2389baff9f85069a11,a34e4c82787ae1dee4f77d5431a66376aeb077dc..03e269656a0516fcad57db2bd687413c4b25b113
@@@ -5,7 -5,6 +5,7 @@@
        {
                header("Access-Control-Allow-Origin: *");
                header("Access-Control-Allow-Methods: OPTIONS,GET");
 +              header("Access-Control-Max-Age: 8640000");
                if (!empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                {
                        header("Access-Control-Allow-Headers: ".$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
        }
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') exit;
  
-     header('Content-type: text/html; charset=utf-8');
 -      if (CONST_ClosedForIndexing && strpos(CONST_ClosedForIndexingExceptionIPs, ','.$_SERVER["REMOTE_ADDR"].',') === false)
 -      {
 -              echo "Closed for re-indexing...";
 -              exit;
 -      }
 -
 -      $aBucketKeys = array();
 -
 -      if (isset($_SERVER["HTTP_REFERER"])) $aBucketKeys[] = str_replace('www.','',strtolower(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST)));
 -      if (isset($_SERVER["REMOTE_ADDR"])) $aBucketKeys[] = $_SERVER["REMOTE_ADDR"];
 -      if (isset($_GET["email"])) $aBucketKeys[] = $_GET["email"];
 -
 -      $fBucketVal = doBucket($aBucketKeys, 
 -                      (defined('CONST_ConnectionBucket_PageType')?constant('CONST_ConnectionBucket_Cost_'.CONST_ConnectionBucket_PageType):1) + user_busy_cost(),
 -                      CONST_ConnectionBucket_LeakRate, CONST_ConnectionBucket_BlockLimit);
 -
 -      if ($fBucketVal > CONST_ConnectionBucket_WaitLimit && $fBucketVal < CONST_ConnectionBucket_BlockLimit)
 -      {
 -              $m = getBucketMemcache();
 -              $iCurrentSleeping = $m->increment('sleepCounter');
 -              if (false === $iCurrentSleeping)
 -              {
 -                      $m->add('sleepCounter', 0);
 -                      $iCurrentSleeping = $m->increment('sleepCounter');
 -              }
 -              if ($iCurrentSleeping >= CONST_ConnectionBucket_MaxSleeping || isBucketSleeping($aBucketKeys))
 -              {
 -                      // Too many threads sleeping already.  This becomes a hard block.
 -                      $fBucketVal = doBucket($aBucketKeys, CONST_ConnectionBucket_BlockLimit, CONST_ConnectionBucket_LeakRate, CONST_ConnectionBucket_BlockLimit);
 -              }
 -              else
 -              {
 -                      setBucketSleeping($aBucketKeys, true);
 -                      sleep(($fBucketVal - CONST_ConnectionBucket_WaitLimit)/CONST_ConnectionBucket_LeakRate);
 -                      $fBucketVal = doBucket($aBucketKeys, CONST_ConnectionBucket_LeakRate, CONST_ConnectionBucket_LeakRate, CONST_ConnectionBucket_BlockLimit);
 -                      setBucketSleeping($aBucketKeys, false);
 -              }
 -              $m->decrement('sleepCounter');
 -      }
 -
 -      if (strpos(CONST_BlockedIPs, ','.$_SERVER["REMOTE_ADDR"].',') !== false || $fBucketVal >= CONST_ConnectionBucket_BlockLimit)
 -      {
 -              header("HTTP/1.0 429 Too Many Requests");
 -              echo "Your IP has been blocked. \n";
 -              echo CONST_BlockMessage;
 -              exit;
 -      }
 -
+       header('Content-type: text/html; charset=utf-8');
 -
diff --combined lib/lib.php
index d1afedbd68414278f90dbcb1906c6c067c06147c,51bf7ebb13381e32507535ca394f7aad46545685..e657daf4207c7bd433e85425990b0ccf5cc20ffe
        function bySearchRank($a, $b)
        {
                if ($a['iSearchRank'] == $b['iSearchRank'])
-             return strlen($a['sOperator']) + strlen($a['sHouseNumber']) - strlen($b['sOperator']) - strlen($b['sHouseNumber']);
+                       return strlen($a['sOperator']) + strlen($a['sHouseNumber']) - strlen($b['sOperator']) - strlen($b['sHouseNumber']);
                return ($a['iSearchRank'] < $b['iSearchRank']?-1:1);
        }
  
        {
                $aResult = array(array(join(' ',$aWords)));
                $sFirstToken = '';
 -              if ($iDepth < 8) {
 +              if ($iDepth < 7) {
                        while(sizeof($aWords) > 1)
                        {
                                $sWord = array_shift($aWords);
                return $aOrders;
        }
  
+       function getResultDiameter($aResult)
+       {
+               $aClassType = getClassTypes();
+               $fDiameter = 0.0001;
+               if (isset($aResult['class'])
+                         && isset($aResult['type'])
+                         && isset($aResult['admin_level'])
+                         && isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
+                               && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
+               {
+                       $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'];
+               }
+               elseif (isset($aResult['class'])
+                         && isset($aResult['type'])
+                         && isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
+                               && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
+               {
+                       $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
+               }
+               return $fDiameter;
+       }
  
        function javascript_renderData($xVal, $iOptions = 0)
        {
  
                return array('lat' => $fQueryLat, 'lon' => $fQueryLon, 'query' => $sQuery);
        }
 -              elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
+       function geometryText2Points($geometry_as_text, $fRadius)
+       {
+               $aPolyPoints = NULL;
+               if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
+               {
+                       preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
+               }
+               elseif (preg_match('#LINESTRING\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
+               {
+                       preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
+               }
 -              }
++/*            elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#', $geometry_as_text, $aMatch))
+               {
+                       preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/', $aMatch[1], $aPolyPoints, PREG_SET_ORDER);
++        }*/
+               elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#', $geometry_as_text, $aMatch))
+               {
+                       $aPolyPoints = createPointsAroundCenter($aMatch[1], $aMatch[2], $fRadius);
+               }
+               if (isset($aPolyPoints))
+               {
+                       $aResultPoints = array();
+                       foreach($aPolyPoints as $aPoint)
+                       {
+                               $aResultPoints[] = array($aPoint[1], $aPoint[2]);
+                       }
+                       return $aResultPoints;
+               }
+               return;
+       }
+       function createPointsAroundCenter($fLon, $fLat, $fRadius)
+       {
+                       $iSteps = max(8, min(100, ($fRadius * 40000)^2));
+                       $fStepSize = (2*pi())/$iSteps;
+                       $aPolyPoints = array();
+                       for($f = 0; $f < 2*pi(); $f += $fStepSize)
+                       {
+                               $aPolyPoints[] = array('', $fLon+($fRadius*sin($f)), $fLat+($fRadius*cos($f)) );
+                       }
+                       return $aPolyPoints;
+       }
index a4885a1577933fcdfbb3ef80cb928a99acaf5320,150d6bdcf45479d1255eeca63afc262347de31e3..34e43328d50d1c1a68a8a6ad0ecd36cf7e238497
@@@ -8,6 -8,7 +8,7 @@@ Feature: Search querie
          And result 0 has attributes lat,lon,display_name
          And result 0 has attributes class,type,importance,icon
          And result 0 has not attributes address
+         And results contain valid boundingboxes
  
      Scenario: Simple JSON search
          When sending json search query "Vaduz"
@@@ -15,6 -16,7 +16,7 @@@
          And result 0 has attributes osm_type,osm_id,boundingbox
          And result 0 has attributes lat,lon,display_name,importance
          And result 0 has not attributes address
+         And results contain valid boundingboxes
  
      Scenario: JSON search with addressdetails
          When sending json search query "Montevideo" with address
@@@ -83,7 -85,7 +85,7 @@@
      Scenario: bounded search remains within viewbox, even with no results
          Given the request parameters
           | bounded | viewbox
 -         | 1       | 43.54285,-5.662003,43.5403125,-5.6563282
 +         | 1       | 43.5403125,-5.6563282,43.54285,-5.662003
           When sending json search query "restaurant"
          Then less than 1 result is returned
  
          | xml
          | json
          | jsonv2
+    Scenario Outline: Search result with contains TEXT geometry
+         Given the request parameters
+           | polygon_text
+           | 1
+         When sending <format> search query "switzerland"
+         Then result 0 has attributes <response_attribute>
+    Examples:
+         | format   | response_attribute
+         | xml      | geotext
+         | json     | geotext
+         | jsonv2   | geotext
+    Scenario Outline: Search result contains polygon-as-points geometry
+         Given the request parameters
+           | polygon
+           | 1
+         When sending <format> search query "switzerland"
+         Then result 0 has attributes <response_attribute>
+    Examples:
+         | format   | response_attribute
+         | xml      | polygonpoints
+         | json     | polygonpoints
+         | jsonv2   | polygonpoints
+    Scenario Outline: Search result contains SVG geometry
+         Given the request parameters
+           | polygon_svg
+           | 1
+         When sending <format> search query "switzerland"
+         Then result 0 has attributes <response_attribute>
+    Examples:
+         | format   | response_attribute
+         | xml      | geosvg
+         | json     | svg
+         | jsonv2   | svg
+    Scenario Outline: Search result contains KML geometry
+         Given the request parameters
+           | polygon_kml
+           | 1
+         When sending <format> search query "switzerland"
+         Then result 0 has attributes <response_attribute>
+    Examples:
+         | format   | response_attribute
+         | xml      | geokml
+         | json     | geokml
+         | jsonv2   | geokml
+    Scenario Outline: Search result contains GEOJSON geometry
+         Given the request parameters
+           | polygon_geojson
+           | 1
+         When sending <format> search query "switzerland"
+         Then result 0 has attributes <response_attribute>
+    Examples:
+         | format   | response_attribute
+         | xml      | geojson
+         | json     | geojson
+         | jsonv2   | geojson
diff --combined website/reverse.php
index d1603fa1e1752f68b55544ea44150dc96bf294a5,d1c554a454352a79914f2f75a4096c182f8fa490..1f6e0aad1114f9acbd14e5baf210ef8cc4e792a9
@@@ -6,6 -6,48 +6,35 @@@
        require_once(CONST_BasePath.'/lib/PlaceLookup.php');
        require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
  
 -      if (strpos(CONST_BulkUserIPs, ','.$_SERVER["REMOTE_ADDR"].',') !== false)
 -      {
 -              $fLoadAvg = getLoadAverage();
 -              if ($fLoadAvg > 2) sleep(60);
 -              if ($fLoadAvg > 4) sleep(120);
 -              if ($fLoadAvg > 6)
 -              {
 -                      echo "Bulk User: Temporary block due to high server load\n";
 -                      exit;
 -              }
 -      }
 -
 -
+       $bAsPoints = false;
+       $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
+       $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
+       $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
+       $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
+       if ( ( ($bAsGeoJSON?1:0)
+                        + ($bAsKML?1:0)
+                        + ($bAsSVG?1:0)
+                        + ($bAsText?1:0)
+                        + ($bAsPoints?1:0)
+                        ) > CONST_PolygonOutput_MaximumTypes)
+       {
+               if (CONST_PolygonOutput_MaximumTypes)
+               {
+                       userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
+               }
+               else
+               {
+                       userError("Polygon output is disabled");
+               }
+               exit;
+       }
+       // Polygon simplification threshold (optional)
+       $fThreshold = 0.0;
+       if (isset($_GET['polygon_threshold'])) $fThreshold = (float)$_GET['polygon_threshold'];
        $oDB =& getDB();
        ini_set('memory_limit', '200M');
  
                $oPlaceLookup->setIncludeNameDetails(getParamBool('namedetails', false));
  
                $aPlace = $oPlaceLookup->lookupPlace($aLookup);
+               $oPlaceLookup->setIncludePolygonAsPoints($bAsPoints);
+               $oPlaceLookup->setIncludePolygonAsText($bAsText);
+               $oPlaceLookup->setIncludePolygonAsGeoJSON($bAsGeoJSON);
+               $oPlaceLookup->setIncludePolygonAsKML($bAsKML);
+               $oPlaceLookup->setIncludePolygonAsSVG($bAsSVG);
+               $oPlaceLookup->setPolygonSimplificationThreshold($fThreshold);
+               $fRadius = $fDiameter = getResultDiameter($aPlace);
+               $aOutlineResult = $oPlaceLookup->getOutlines($aPlace['place_id'],$aPlace['lon'],$aPlace['lat'],$fRadius);
+               $aPlace = array_merge($aPlace, $aOutlineResult);
        }
        else
        {
                $aPlace = null;
        }
  
 +      logEnd($oDB, $hLog, sizeof($aPlace)?1:0);
  
        if (CONST_Debug)
        {
                exit;
        }
  
-       $sTileURL = CONST_Map_Tile_URL;
-       $sTileAttribution = CONST_Map_Tile_Attribution;
+       if ($sOutputFormat=='html')
+       {
+               $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
+               $sTileURL = CONST_Map_Tile_URL;
+               $sTileAttribution = CONST_Map_Tile_Attribution;
+       }
        include(CONST_BasePath.'/lib/template/address-'.$sOutputFormat.'.php');