- // Re-group the searches by their score, junk anything over 20 as just not worth trying
- $aGroupedSearches = array();
- foreach($aSearches as $aSearch)
- {
- if ($aSearch['iSearchRank'] < $iMaxRank)
- {
- if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
- $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
- }
- }
- ksort($aGroupedSearches);
- }
-
- if (CONST_Debug) var_Dump($aGroupedSearches);
-
- if ($bReverseInPlan)
- {
- foreach($aGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
- if (sizeof($aSearch['aAddress']))
- {
- $aReverseSearch = $aSearch;
- $iReverseItem = array_pop($aSearch['aAddress']);
- $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
- $aGroupedSearches[$iGroup][] = $aReverseSearch;
- }
- }
- }
- }
-
-//var_Dump($aGroupedSearches); exit;
-
- // Filter out duplicate searches
- $aSearchHash = array();
- foreach($aGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
- $sHash = serialize($aSearch);
- if (isset($aSearchHash[$sHash]))
- {
- unset($aGroupedSearches[$iGroup][$iSearch]);
- if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
- }
- else
- {
- $aSearchHash[$sHash] = 1;
- }
- }
- }
-
- if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
-
- if ($bReverseInPlan)
- {
- foreach($aGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
- if (sizeof($aSearch['aAddress']))
- {
- $aReverseSearch = $aSearch;
- $iReverseItem = array_pop($aSearch['aAddress']);
- $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
- $aGroupedSearches[$iGroup][] = $aReverseSearch;
- }
- }
- }
- }
-
- // Filter out duplicate searches
- $aSearchHash = array();
- foreach($aGroupedSearches as $iGroup => $aSearches)
- {
- foreach($aSearches as $iSearch => $aSearch)
- {
- $sHash = serialize($aSearch);
- if (isset($aSearchHash[$sHash]))
- {
- unset($aGroupedSearches[$iGroup][$iSearch]);
- if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
- }
- else
- {
- $aSearchHash[$sHash] = 1;
- }
- }
- }
-
- if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
-
- $iGroupLoop = 0;
- $iQueryLoop = 0;
- foreach($aGroupedSearches as $iGroupedRank => $aSearches)
- {
- $iGroupLoop++;
- foreach($aSearches as $aSearch)
- {
- $iQueryLoop++;
- // Must have a location term
- if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress'] && !$aSearch['fLon']))
- {
- if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
- if (!$aSearch['sClass']) continue;
- if (CONST_Debug) var_dump('<hr>',$aSearch);
- if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
-
- $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
- if ($oDB->getOne($sSQL))
- {
- $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
- $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
- if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
-
- if (!sizeof($aPlaceIDs))
- {
- $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
- $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
- if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
- }
- else
- {
- $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
- $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
- if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
- }
- else
- {
- if ($aSearch['aName'] == array(282=>'282')) continue;
-
- if (CONST_Debug) var_dump('<hr>',$aSearch);
- if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
- $aPlaceIDs = array();
-
- // First we need a position, either aName or fLat or both
- $aTerms = array();
- $aOrder = array();
- if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
- if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
- if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
- if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
- if ($aSearch['fLon'] && $aSearch['fLat'])
- {
- $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
- $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
- }
- if (sizeof($aExcludePlaceIDs))
- {
- $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
- }
- if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
- if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
- if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
- if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
- $aOrder[] = "search_rank ASC";
-
- if (sizeof($aTerms))
- {
- $sSQL = "select place_id";
- if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
- else $sSQL .= ",false as in_small";
- if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
- else $sSQL .= ",false as in_large";
- $sSQL .= " from search_name";
- $sSQL .= " where ".join(' and ',$aTerms);
- $sSQL .= " order by ".join(', ',$aOrder);
- if ($aSearch['sHouseNumber'])
- $sSQL .= " limit 50";
- elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
- $sSQL .= " limit 1";
- else
- $sSQL .= " limit ".$iLimit;
-
- if (CONST_Debug) var_dump($sSQL);
- $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
- if (PEAR::IsError($aViewBoxPlaceIDs))
- {
- var_dump($sSQL, $aViewBoxPlaceIDs);
- exit;
- }
-
- // Did we have an viewbox matches?
- $aPlaceIDs = array();
- $bViewBoxMatch = false;
- foreach($aViewBoxPlaceIDs as $aViewBoxRow)
- {
- if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
- if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
- if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
- else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
- $aPlaceIDs[] = $aViewBoxRow['place_id'];
- }
- }
-
- if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
- {
- $sPlaceIDs = join(',',$aPlaceIDs);
-
- $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
-
- // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
- $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
- $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
- $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
- $sSQL .= " and placex.class='place' and placex.type='house'";
- if (CONST_Debug) var_dump($sSQL);
- $oDB->query($sSQL);
-
- // Now they are indexed look for a house attached to a street we found
- $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
- if (sizeof($aExcludePlaceIDs))
- {
- $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
- }
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
-
- if ($aSearch['sClass'] && sizeof($aPlaceIDs))
- {
- $sPlaceIDs = join(',',$aPlaceIDs);
-
- if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
- {
- // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
- $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
- $sSQL .= " order by rank_search asc limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
-
- if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
- {
- $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
- if (CONST_Debug) var_dump($sSQL);
- $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
-
- $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- $sPlaceIDs = join(',',$aPlaceIDs);
-
- $fRange = 0.01;
- $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
- if ($oDB->getOne($sSQL))
- {
- // More efficient - can make the range bigger
- $fRange = 0.05;
- $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
- $sSQL .= ",placex as f where ";
- $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
- if (sizeof($aExcludePlaceIDs))
- {
- $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
- }
- if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
- else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
- else
- {
- if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
- $sSQL = "select l.place_id from placex as l,placex as f where ";
- $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
- $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
- if (sizeof($aExcludePlaceIDs))
- {
- $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
- }
- if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
- else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
- $sSQL .= " limit $iLimit";
- if (CONST_Debug) var_dump($sSQL);
- $aPlaceIDs = $oDB->getCol($sSQL);
- }
- }
- }
-
- }
-
- if (PEAR::IsError($aPlaceIDs))
- {
- var_dump($sSQL, $aPlaceIDs);
- exit;
- }
-
- if (CONST_Debug) var_Dump($aPlaceIDs);
-
- foreach($aPlaceIDs as $iPlaceID)
- {
- $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
- }
- if ($iQueryLoop > 20) break;
- }
- //exit;
- if (sizeof($aResultPlaceIDs)) break;
- if ($iGroupLoop > 4) break;
- if ($iQueryLoop > 30) break;
- }
-//exit;
- // Did we find anything?
- if (sizeof($aResultPlaceIDs))
- {
-//var_Dump($aResultPlaceIDs);exit;
- // Get the details for display (is this a redundant extra step?)
- $sPlaceIDs = join(',',$aResultPlaceIDs);
- $sOrderSQL = 'CASE ';
- foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
- {
- $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
- }
- $sOrderSQL .= ' ELSE 10000000 END ASC';
- $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
- $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
- $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
- $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
- $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
- $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
- $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
- if (!$bDeDupe) $sSQL .= ",place_id";
- $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
- $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
- $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
- $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
- if (CONST_Debug) var_dump('<hr>',$sSQL);
- $aSearchResults = $oDB->getAll($sSQL);
-//var_dump($sSQL,$aSearchResults);exit;
-
- if (PEAR::IsError($aSearchResults))
- {
- var_dump($sSQL, $aSearchResults);
- exit;
- }
- }
- }
- }
-
- $sSearchResult = '';
- if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
- {
- $sSearchResult = 'No Results Found';
- }
-
- $aClassType = getClassTypesWithImportance();
-
- foreach($aSearchResults as $iResNum => $aResult)
- {
- if (CONST_Search_AreaPolygons || true)
- {
- // Get the bounding box and outline polygon
- $sSQL = "select place_id,numfeatures,area,outline,";
- $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
- $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
- $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
- $aPointPolygon = $oDB->getRow($sSQL);
- if (PEAR::IsError($aPointPolygon))
- {
- var_dump($sSQL, $aPointPolygon);
- exit;
- }
- if ($aPointPolygon['place_id'])
- {
- // Translate geometary string to point array
- if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
- {
- preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
- }
- elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
- {
- $fRadius = 0.01;
- $iSteps = ($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)));
- }
- $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
- $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
- $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
- $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
- }
-
- // Output data suitable for display (points and a bounding box)
- if ($bShowPolygons)
- {
- $aResult['aPolyPoints'] = array();
- foreach($aPolyPoints as $aPoint)
- {
- $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
- }
- }
- $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
- }
- }
-
- if (!isset($aResult['aBoundingBox']))
- {
- // 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']]['defzoom'];
- }
- elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
- && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
- {
- $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
- }
- $fRadius = $fDiameter / 2;
-
- $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
- $fStepSize = (2*pi())/$iSteps;
- $aPolyPoints = array();
- for($f = 0; $f < 2*pi(); $f += $fStepSize)
- {
- $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));