6 protected $aLangPrefOrder = array();
8 protected $bIncludeAddressDetails = false;
10 protected $bIncludePolygonAsPoints = false;
11 protected $bIncludePolygonAsText = false;
12 protected $bIncludePolygonAsGeoJSON = false;
13 protected $bIncludePolygonAsKML = false;
14 protected $bIncludePolygonAsSVG = false;
16 protected $aExcludePlaceIDs = array();
17 protected $bDeDupe = true;
18 protected $bReverseInPlan = false;
20 protected $iLimit = 20;
21 protected $iFinalLimit = 10;
22 protected $iOffset = 0;
24 protected $aCountryCodes = false;
25 protected $aNearPoint = false;
27 protected $bBoundedSearch = false;
28 protected $aViewBox = false;
29 protected $aRoutePoints = false;
31 protected $iMaxRank = 20;
32 protected $iMinAddressRank = 0;
33 protected $iMaxAddressRank = 30;
34 protected $aAddressRankList = array();
36 protected $sAllowedTypesSQLList = false;
38 protected $sQuery = false;
39 protected $aStructuredQuery = false;
41 function Geocode(&$oDB)
46 function setReverseInPlan($bReverse)
48 $this->bReverseInPlan = $bReverse;
51 function setLanguagePreference($aLangPref)
53 $this->aLangPrefOrder = $aLangPref;
56 function setIncludeAddressDetails($bAddressDetails = true)
58 $this->bIncludeAddressDetails = (bool)$bAddressDetails;
61 function getIncludeAddressDetails()
63 return $this->bIncludeAddressDetails;
66 function setIncludePolygonAsPoints($b = true)
68 $this->bIncludePolygonAsPoints = $b;
71 function getIncludePolygonAsPoints()
73 return $this->bIncludePolygonAsPoints;
76 function setIncludePolygonAsText($b = true)
78 $this->bIncludePolygonAsText = $b;
81 function getIncludePolygonAsText()
83 return $this->bIncludePolygonAsText;
86 function setIncludePolygonAsGeoJSON($b = true)
88 $this->bIncludePolygonAsGeoJSON = $b;
91 function setIncludePolygonAsKML($b = true)
93 $this->bIncludePolygonAsKML = $b;
96 function setIncludePolygonAsSVG($b = true)
98 $this->bIncludePolygonAsSVG = $b;
101 function setDeDupe($bDeDupe = true)
103 $this->bDeDupe = (bool)$bDeDupe;
106 function setLimit($iLimit = 10)
108 if ($iLimit > 50) $iLimit = 50;
109 if ($iLimit < 1) $iLimit = 1;
111 $this->iFinalLimit = $iLimit;
112 $this->iLimit = $this->iFinalLimit + min($this->iFinalLimit, 10);
115 function setOffset($iOffset = 0)
117 $this->iOffset = $iOffset;
120 function setExcludedPlaceIDs($a)
122 // TODO: force to int
123 $this->aExcludePlaceIDs = $a;
126 function getExcludedPlaceIDs()
128 return $this->aExcludePlaceIDs;
131 function setBounded($bBoundedSearch = true)
133 $this->bBoundedSearch = (bool)$bBoundedSearch;
136 function setViewBox($fLeft, $fBottom, $fRight, $fTop)
138 $this->aViewBox = array($fLeft, $fBottom, $fRight, $fTop);
141 function getViewBoxString()
143 if (!$this->aViewBox) return null;
144 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
147 function setRoute($aRoutePoints)
149 $this->aRoutePoints = $aRoutePoints;
152 function setFeatureType($sFeatureType)
154 switch($sFeatureType)
157 $this->setRankRange(4, 4);
160 $this->setRankRange(8, 8);
163 $this->setRankRange(14, 16);
166 $this->setRankRange(8, 20);
171 function setRankRange($iMin, $iMax)
173 $this->iMinAddressRank = (int)$iMin;
174 $this->iMaxAddressRank = (int)$iMax;
177 function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
179 $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
182 function setCountryCodesList($aCountryCodes)
184 $this->aCountryCodes = $aCountryCodes;
187 function setQuery($sQueryString)
189 $this->sQuery = $sQueryString;
190 $this->aStructuredQuery = false;
193 function getQueryString()
195 return $this->sQuery;
198 function loadStructuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, &$aAddressRankList, $sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
200 $sValue = trim($sValue);
201 if (!$sValue) return false;
202 $aStructuredQuery[$sKey] = $sValue;
203 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
205 $iMinAddressRank = $iNewMinAddressRank;
206 $iMaxAddressRank = $iNewMaxAddressRank;
208 if ($aItemListValues) $aAddressRankList = array_merge($aAddressRankList, $aItemListValues);
212 function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
214 $this->sQuery = false;
216 $this->aStructuredQuery = array();
217 $this->sAllowedTypesSQLList = '';
219 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sAmentiy, 'amenity', 26, 30, false);
220 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sStreet, 'street', 26, 30, false);
221 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sCity, 'city', 14, 24, false);
222 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sCounty, 'county', 9, 13, false);
223 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sState, 'state', 8, 8, false);
224 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sPostalCode, 'postalcode' , 5, 11, array(5, 11));
225 $this->loadStructuredAddressElement($this->aStructuredQuery, $this->iMinAddressRank, $this->iMaxAddressRank, $this->aAddressRankList, $sCountry, 'country', 4, 4, false);
227 if (sizeof($this->aStructuredQuery) > 0)
229 $this->sQuery = join(', ', $this->aStructuredQuery);
230 if ($this->iMaxAddressRank < 30)
232 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
238 function getDetails($aPlaceIDs)
240 if (sizeof($aPlaceIDs) == 0) return array();
242 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
244 // Get the details for display (is this a redundant extra step?)
245 $sPlaceIDs = join(',',$aPlaceIDs);
247 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
248 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
249 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
250 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
251 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
252 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
253 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(placex.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
254 $sSQL .= "(extratags->'place') as extra_place ";
255 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
256 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
257 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
258 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
260 if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
261 $sSQL .= "and linked_place_id is null ";
262 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
263 if (!$this->bDeDupe) $sSQL .= ",place_id";
264 $sSQL .= ",langaddress ";
265 $sSQL .= ",placename ";
267 $sSQL .= ",extratags->'place' ";
269 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank)
272 $sSQL .= "select 'T' 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,'us' as country_code,";
273 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
274 $sSQL .= "null as placename,";
275 $sSQL .= "null as ref,";
276 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
277 $sSQL .= "-0.15 as importance, ";
278 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
279 $sSQL .= "null as extra_place ";
280 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
281 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
282 $sSQL .= "group by place_id";
283 if (!$this->bDeDupe) $sSQL .= ",place_id";
285 $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,'us' as country_code,";
286 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
287 $sSQL .= "null as placename,";
288 $sSQL .= "null as ref,";
289 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
290 $sSQL .= "-0.10 as importance, ";
291 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
292 $sSQL .= "null as extra_place ";
293 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
294 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
295 $sSQL .= "group by place_id";
296 if (!$this->bDeDupe) $sSQL .= ",place_id";
297 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
300 $sSQL .= "order by importance desc";
301 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
302 $aSearchResults = $this->oDB->getAll($sSQL);
304 if (PEAR::IsError($aSearchResults))
306 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
309 return $aSearchResults;
314 if (!$this->sQuery && !$this->aStructuredQuery) return false;
316 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$this->aLangPrefOrder))."]";
318 $sCountryCodesSQL = false;
319 if ($this->aCountryCodes && sizeof($this->aCountryCodes))
321 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
324 // Hack to make it handle "new york, ny" (and variants) correctly
325 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $this->sQuery);
327 // Conflicts between US state abreviations and various words for 'the' in different languages
328 if (isset($this->aLangPrefOrder['name:en']))
330 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
331 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
332 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
336 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
337 $bBoundingBoxSearch = false;
340 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
341 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
342 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
343 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
344 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
345 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
347 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$this->aViewBox[0].",".(float)$this->aViewBox[1]."),ST_Point(".(float)$this->aViewBox[2].",".(float)$this->aViewBox[3].")),4326)";
348 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
349 $bBoundingBoxSearch = $this->bBoundedSearch;
353 if ($this->aRoutePoints)
355 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
357 foreach($this->aRouteaPoints as $aPoint)
359 if (!$bFirst) $sViewboxCentreSQL .= ",";
360 $sViewboxCentreSQL .= $aPoint[1].' '.$aPoint[0];
362 $sViewboxCentreSQL .= ")'::geometry,4326)";
364 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
365 $sViewboxSmallSQL = $this->oDB->getOne($sSQL);
366 if (PEAR::isError($sViewboxSmallSQL))
368 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
370 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
372 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
373 $sViewboxLargeSQL = $this->oDB->getOne($sSQL);
374 if (PEAR::isError($sViewboxLargeSQL))
376 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
378 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
379 $bBoundingBoxSearch = $this->bBoundedSearch;
382 // Do we have anything that looks like a lat/lon pair?
383 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
385 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
386 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
387 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
389 $this->setNearPoint(array($fQueryLat, $fQueryLon));
390 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
393 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
395 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
396 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
397 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
399 $this->setNearPoint(array($fQueryLat, $fQueryLon));
400 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
403 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
405 $fQueryLat = $aData[2];
406 $fQueryLon = $aData[3];
407 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
409 $this->setNearPoint(array($fQueryLat, $fQueryLon));
410 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
414 $aSearchResults = array();
415 if ($sQuery || $this->aStructuredQuery)
417 // Start with a blank search
419 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
420 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
421 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
424 // Do we have a radius search?
425 $sNearPointSQL = false;
426 if ($this->aNearPoint)
428 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
429 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
430 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
431 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
434 // Any 'special' terms in the search?
435 $bSpecialTerms = false;
436 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
437 $aSpecialTerms = array();
438 foreach($aSpecialTermsRaw as $aSpecialTerm)
440 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
441 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
444 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
445 $aSpecialTerms = array();
446 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
448 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
449 unset($aStructuredQuery['amenity']);
451 foreach($aSpecialTermsRaw as $aSpecialTerm)
453 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
454 $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
455 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
456 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
457 if (CONST_Debug) var_Dump($sSQL);
458 $aSearchWords = $this->oDB->getAll($sSQL);
459 $aNewSearches = array();
460 foreach($aSearches as $aSearch)
462 foreach($aSearchWords as $aSearchTerm)
464 $aNewSearch = $aSearch;
465 if ($aSearchTerm['country_code'])
467 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
468 $aNewSearches[] = $aNewSearch;
469 $bSpecialTerms = true;
471 if ($aSearchTerm['class'])
473 $aNewSearch['sClass'] = $aSearchTerm['class'];
474 $aNewSearch['sType'] = $aSearchTerm['type'];
475 $aNewSearches[] = $aNewSearch;
476 $bSpecialTerms = true;
480 $aSearches = $aNewSearches;
483 // Split query into phrases
484 // Commas are used to reduce the search space by indicating where phrases split
485 if ($this->aStructuredQuery)
487 $aPhrases = $this->aStructuredQuery;
488 $bStructuredPhrases = true;
492 $aPhrases = explode(',',$sQuery);
493 $bStructuredPhrases = false;
496 // Convert each phrase to standard form
497 // Create a list of standard words
498 // Get all 'sets' of words
499 // Generate a complete list of all
501 foreach($aPhrases as $iPhrase => $sPhrase)
503 $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
504 if (PEAR::isError($aPhrase))
506 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
507 if (CONST_Debug) var_dump($aPhrase);
510 if (trim($aPhrase['string']))
512 $aPhrases[$iPhrase] = $aPhrase;
513 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
514 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
515 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
519 unset($aPhrases[$iPhrase]);
523 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
524 $aPhraseTypes = array_keys($aPhrases);
525 $aPhrases = array_values($aPhrases);
527 if (sizeof($aTokens))
529 // Check which tokens we have, get the ID numbers
530 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
531 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
533 if (CONST_Debug) var_Dump($sSQL);
535 $aValidTokens = array();
536 if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
537 else $aDatabaseWords = array();
538 if (PEAR::IsError($aDatabaseWords))
540 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
542 $aPossibleMainWordIDs = array();
543 $aWordFrequencyScores = array();
544 foreach($aDatabaseWords as $aToken)
546 // Very special case - require 2 letter country param to match the country code found
547 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
548 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
553 if (isset($aValidTokens[$aToken['word_token']]))
555 $aValidTokens[$aToken['word_token']][] = $aToken;
559 $aValidTokens[$aToken['word_token']] = array($aToken);
561 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
562 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
564 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
566 // Try and calculate GB postcodes we might be missing
567 foreach($aTokens as $sToken)
569 // Source of gb postcodes is now definitive - always use
570 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
572 if (substr($aData[1],-2,1) != ' ')
574 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
575 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
577 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
578 if ($aGBPostcodeLocation)
580 $aValidTokens[$sToken] = $aGBPostcodeLocation;
583 // US ZIP+4 codes - if there is no token,
584 // merge in the 5-digit ZIP code
585 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
587 if (isset($aValidTokens[$aData[1]]))
589 foreach($aValidTokens[$aData[1]] as $aToken)
591 if (!$aToken['class'])
593 if (isset($aValidTokens[$sToken]))
595 $aValidTokens[$sToken][] = $aToken;
599 $aValidTokens[$sToken] = array($aToken);
607 foreach($aTokens as $sToken)
609 // Unknown single word token with a number - assume it is a house number
610 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
612 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
616 // Any words that have failed completely?
619 // Start the search process
620 $aResultPlaceIDs = array();
623 Calculate all searches using aValidTokens i.e.
624 'Wodsworth Road, Sheffield' =>
628 0 1 (wodsworth)(road)
631 Score how good the search is so they can be ordered
633 foreach($aPhrases as $iPhrase => $sPhrase)
635 $aNewPhraseSearches = array();
636 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
637 else $sPhraseType = '';
639 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
641 // Too many permutations - too expensive
642 if ($iWordSet > 120) break;
644 $aWordsetSearches = $aSearches;
646 // Add all words from this wordset
647 foreach($aWordset as $iToken => $sToken)
649 //echo "<br><b>$sToken</b>";
650 $aNewWordsetSearches = array();
652 foreach($aWordsetSearches as $aCurrentSearch)
655 //var_dump($aCurrentSearch);
658 // If the token is valid
659 if (isset($aValidTokens[' '.$sToken]))
661 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
663 $aSearch = $aCurrentSearch;
664 $aSearch['iSearchRank']++;
665 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
667 if ($aSearch['sCountryCode'] === false)
669 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
670 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
671 // If reverse order is enabled, it may appear at the beginning as well.
672 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
673 (!$this->bReverseInPlan || $iToken > 0 || $iPhrase > 0))
675 $aSearch['iSearchRank'] += 5;
677 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
680 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
682 if ($aSearch['fLat'] === '')
684 $aSearch['fLat'] = $aSearchTerm['lat'];
685 $aSearch['fLon'] = $aSearchTerm['lon'];
686 $aSearch['fRadius'] = $aSearchTerm['radius'];
687 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
690 elseif ($sPhraseType == 'postalcode')
692 // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
693 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
695 // If we already have a name try putting the postcode first
696 if (sizeof($aSearch['aName']))
698 $aNewSearch = $aSearch;
699 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
700 $aNewSearch['aName'] = array();
701 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
702 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
705 if (sizeof($aSearch['aName']))
707 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
709 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
713 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
714 $aSearch['iSearchRank'] += 1000; // skip;
719 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
720 //$aSearch['iNamePhrase'] = $iPhrase;
722 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
726 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
728 if ($aSearch['sHouseNumber'] === '')
730 $aSearch['sHouseNumber'] = $sToken;
731 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
733 // Fall back to not searching for this item (better than nothing)
734 $aSearch = $aCurrentSearch;
735 $aSearch['iSearchRank'] += 1;
736 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
740 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
742 if ($aSearch['sClass'] === '')
744 $aSearch['sOperator'] = $aSearchTerm['operator'];
745 $aSearch['sClass'] = $aSearchTerm['class'];
746 $aSearch['sType'] = $aSearchTerm['type'];
747 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
748 else $aSearch['sOperator'] = 'near'; // near = in for the moment
750 // Do we have a shortcut id?
751 if ($aSearch['sOperator'] == 'name')
753 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
754 if ($iAmenityID = $this->oDB->getOne($sSQL))
756 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
757 $aSearch['aName'][$iAmenityID] = $iAmenityID;
758 $aSearch['sClass'] = '';
759 $aSearch['sType'] = '';
762 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
765 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
767 if (sizeof($aSearch['aName']))
769 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
771 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
775 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
776 $aSearch['iSearchRank'] += 1000; // skip;
781 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
782 //$aSearch['iNamePhrase'] = $iPhrase;
784 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
788 if (isset($aValidTokens[$sToken]))
790 // Allow searching for a word - but at extra cost
791 foreach($aValidTokens[$sToken] as $aSearchTerm)
793 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
795 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
797 $aSearch = $aCurrentSearch;
798 $aSearch['iSearchRank'] += 1;
799 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
801 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
802 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
804 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
806 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
808 if (empty($aSearchTermToken['country_code'])
809 && empty($aSearchTermToken['lat'])
810 && empty($aSearchTermToken['class']))
812 $aSearch = $aCurrentSearch;
813 $aSearch['iSearchRank'] += 1;
814 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
815 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
821 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
822 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
826 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
828 $aSearch = $aCurrentSearch;
829 $aSearch['iSearchRank'] += 2;
830 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
831 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
832 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
834 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
835 $aSearch['iNamePhrase'] = $iPhrase;
836 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
843 // Allow skipping a word - but at EXTREAM cost
844 //$aSearch = $aCurrentSearch;
845 //$aSearch['iSearchRank']+=100;
846 //$aNewWordsetSearches[] = $aSearch;
850 usort($aNewWordsetSearches, 'bySearchRank');
851 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
853 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
855 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
856 usort($aNewPhraseSearches, 'bySearchRank');
858 $aSearchHash = array();
859 foreach($aNewPhraseSearches as $iSearch => $aSearch)
861 $sHash = serialize($aSearch);
862 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
863 else $aSearchHash[$sHash] = 1;
866 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
869 // Re-group the searches by their score, junk anything over 20 as just not worth trying
870 $aGroupedSearches = array();
871 foreach($aNewPhraseSearches as $aSearch)
873 if ($aSearch['iSearchRank'] < $this->iMaxRank)
875 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
876 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
879 ksort($aGroupedSearches);
882 $aSearches = array();
883 foreach($aGroupedSearches as $iScore => $aNewSearches)
885 $iSearchCount += sizeof($aNewSearches);
886 $aSearches = array_merge($aSearches, $aNewSearches);
887 if ($iSearchCount > 50) break;
890 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
897 // Re-group the searches by their score, junk anything over 20 as just not worth trying
898 $aGroupedSearches = array();
899 foreach($aSearches as $aSearch)
901 if ($aSearch['iSearchRank'] < $this->iMaxRank)
903 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
904 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
907 ksort($aGroupedSearches);
910 if (CONST_Debug) var_Dump($aGroupedSearches);
912 if ($this->bReverseInPlan)
914 $aCopyGroupedSearches = $aGroupedSearches;
915 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
917 foreach($aSearches as $iSearch => $aSearch)
919 if (sizeof($aSearch['aAddress']))
921 $iReverseItem = array_pop($aSearch['aAddress']);
922 if (isset($aPossibleMainWordIDs[$iReverseItem]))
924 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
925 $aSearch['aName'] = array($iReverseItem);
926 $aGroupedSearches[$iGroup][] = $aSearch;
928 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
929 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
935 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
937 $aCopyGroupedSearches = $aGroupedSearches;
938 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
940 foreach($aSearches as $iSearch => $aSearch)
942 $aReductionsList = array($aSearch['aAddress']);
943 $iSearchRank = $aSearch['iSearchRank'];
944 while(sizeof($aReductionsList) > 0)
947 if ($iSearchRank > iMaxRank) break 3;
948 $aNewReductionsList = array();
949 foreach($aReductionsList as $aReductionsWordList)
951 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
953 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
954 $aReverseSearch = $aSearch;
955 $aSearch['aAddress'] = $aReductionsWordListResult;
956 $aSearch['iSearchRank'] = $iSearchRank;
957 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
958 if (sizeof($aReductionsWordListResult) > 0)
960 $aNewReductionsList[] = $aReductionsWordListResult;
964 $aReductionsList = $aNewReductionsList;
968 ksort($aGroupedSearches);
971 // Filter out duplicate searches
972 $aSearchHash = array();
973 foreach($aGroupedSearches as $iGroup => $aSearches)
975 foreach($aSearches as $iSearch => $aSearch)
977 $sHash = serialize($aSearch);
978 if (isset($aSearchHash[$sHash]))
980 unset($aGroupedSearches[$iGroup][$iSearch]);
981 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
985 $aSearchHash[$sHash] = 1;
990 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
994 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
997 foreach($aSearches as $aSearch)
1001 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1002 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1004 // No location term?
1005 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1007 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1009 // Just looking for a country by code - look it up
1010 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1012 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1013 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1014 $sSQL .= " order by st_area(geometry) desc limit 1";
1015 if (CONST_Debug) var_dump($sSQL);
1016 $aPlaceIDs = $this->oDB->getCol($sSQL);
1021 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1022 if (!$aSearch['sClass']) continue;
1023 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1024 if ($this->oDB->getOne($sSQL))
1026 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1027 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1028 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
1029 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1030 if (sizeof($this->aExcludePlaceIDs))
1032 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1034 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1035 $sSQL .= " limit $this->iLimit";
1036 if (CONST_Debug) var_dump($sSQL);
1037 $aPlaceIDs = $this->oDB->getCol($sSQL);
1039 // If excluded place IDs are given, it is fair to assume that
1040 // there have been results in the small box, so no further
1041 // expansion in that case.
1042 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs))
1044 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1045 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1046 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
1047 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1048 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1049 $sSQL .= " limit $this->iLimit";
1050 if (CONST_Debug) var_dump($sSQL);
1051 $aPlaceIDs = $this->oDB->getCol($sSQL);
1056 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1057 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
1058 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1059 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
1060 $sSQL .= " limit $this->iLimit";
1061 if (CONST_Debug) var_dump($sSQL);
1062 $aPlaceIDs = $this->oDB->getCol($sSQL);
1068 $aPlaceIDs = array();
1070 // First we need a position, either aName or fLat or both
1074 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1075 // they might be right - but they are just too darned expensive to run
1076 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1077 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1078 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1080 // For infrequent name terms disable index usage for address
1081 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1082 sizeof($aSearch['aName']) == 1 &&
1083 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1085 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1089 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1090 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1093 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1094 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
1095 if ($aSearch['fLon'] && $aSearch['fLat'])
1097 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1098 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1100 if (sizeof($this->aExcludePlaceIDs))
1102 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1104 if ($sCountryCodesSQL)
1106 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1109 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
1110 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1112 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1113 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1114 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1115 $aOrder[] = "$sImportanceSQL DESC";
1116 if (sizeof($aSearch['aFullNameAddress']))
1118 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
1121 if (sizeof($aTerms))
1123 $sSQL = "select place_id";
1124 $sSQL .= " from search_name";
1125 $sSQL .= " where ".join(' and ',$aTerms);
1126 $sSQL .= " order by ".join(', ',$aOrder);
1127 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1128 $sSQL .= " limit 50";
1129 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1130 $sSQL .= " limit 1";
1132 $sSQL .= " limit ".$this->iLimit;
1134 if (CONST_Debug) { var_dump($sSQL); }
1135 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
1136 if (PEAR::IsError($aViewBoxPlaceIDs))
1138 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
1140 //var_dump($aViewBoxPlaceIDs);
1141 // Did we have an viewbox matches?
1142 $aPlaceIDs = array();
1143 $bViewBoxMatch = false;
1144 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1146 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1147 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1148 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1149 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1150 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1153 //var_Dump($aPlaceIDs);
1156 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1158 $aRoadPlaceIDs = $aPlaceIDs;
1159 $sPlaceIDs = join(',',$aPlaceIDs);
1161 // Now they are indexed look for a house attached to a street we found
1162 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1163 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1164 if (sizeof($this->aExcludePlaceIDs))
1166 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1168 $sSQL .= " limit $this->iLimit";
1169 if (CONST_Debug) var_dump($sSQL);
1170 $aPlaceIDs = $this->oDB->getCol($sSQL);
1172 // If not try the aux fallback table
1173 if (!sizeof($aPlaceIDs))
1175 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1176 if (sizeof($this->aExcludePlaceIDs))
1178 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1180 //$sSQL .= " limit $this->iLimit";
1181 if (CONST_Debug) var_dump($sSQL);
1182 $aPlaceIDs = $this->oDB->getCol($sSQL);
1185 if (!sizeof($aPlaceIDs))
1187 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1188 if (sizeof($this->aExcludePlaceIDs))
1190 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1192 //$sSQL .= " limit $this->iLimit";
1193 if (CONST_Debug) var_dump($sSQL);
1194 $aPlaceIDs = $this->oDB->getCol($sSQL);
1197 // Fallback to the road
1198 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1200 $aPlaceIDs = $aRoadPlaceIDs;
1205 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1207 $sPlaceIDs = join(',',$aPlaceIDs);
1208 $aClassPlaceIDs = array();
1210 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1212 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1213 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1214 $sSQL .= " and linked_place_id is null";
1215 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1216 $sSQL .= " order by rank_search asc limit $this->iLimit";
1217 if (CONST_Debug) var_dump($sSQL);
1218 $aClassPlaceIDs = $this->oDB->getCol($sSQL);
1221 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1223 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1224 $bCacheTable = $this->oDB->getOne($sSQL);
1226 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1228 if (CONST_Debug) var_dump($sSQL);
1229 $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
1231 // For state / country level searches the normal radius search doesn't work very well
1232 $sPlaceGeom = false;
1233 if ($this->iMaxRank < 9 && $bCacheTable)
1235 // Try and get a polygon to search in instead
1236 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
1237 if (CONST_Debug) var_dump($sSQL);
1238 $sPlaceGeom = $this->oDB->getOne($sSQL);
1247 $this->iMaxRank += 5;
1248 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1249 if (CONST_Debug) var_dump($sSQL);
1250 $aPlaceIDs = $this->oDB->getCol($sSQL);
1251 $sPlaceIDs = join(',',$aPlaceIDs);
1254 if ($sPlaceIDs || $sPlaceGeom)
1260 // More efficient - can make the range bigger
1264 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1265 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1266 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1268 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1269 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1272 $sSQL .= ",placex as f where ";
1273 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1278 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1280 if (sizeof($this->aExcludePlaceIDs))
1282 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1284 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1285 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1286 if ($iOffset) $sSQL .= " offset $iOffset";
1287 $sSQL .= " limit $this->iLimit";
1288 if (CONST_Debug) var_dump($sSQL);
1289 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1293 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1296 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1297 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1299 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1300 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1301 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1302 if (sizeof($this->aExcludePlaceIDs))
1304 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1306 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1307 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1308 if ($iOffset) $sSQL .= " offset $iOffset";
1309 $sSQL .= " limit $this->iLimit";
1310 if (CONST_Debug) var_dump($sSQL);
1311 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1316 $aPlaceIDs = $aClassPlaceIDs;
1322 if (PEAR::IsError($aPlaceIDs))
1324 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1327 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1329 foreach($aPlaceIDs as $iPlaceID)
1331 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1333 if ($iQueryLoop > 20) break;
1336 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1338 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1339 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
1340 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1341 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1342 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1343 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
1344 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1345 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1347 if (CONST_Debug) var_dump($sSQL);
1348 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
1352 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1353 if ($iGroupLoop > 4) break;
1354 if ($iQueryLoop > 30) break;
1357 // Did we find anything?
1358 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1360 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1366 // Just interpret as a reverse geocode
1367 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
1369 $aSearchResults = $this->getDetails(array($iPlaceID));
1371 $aSearchResults = array();
1375 if (!sizeof($aSearchResults))
1380 $aClassType = getClassTypesWithImportance();
1381 $aRecheckWords = preg_split('/\b/u',$sQuery);
1382 foreach($aRecheckWords as $i => $sWord)
1384 if (!$sWord) unset($aRecheckWords[$i]);
1387 foreach($aSearchResults as $iResNum => $aResult)
1389 if (CONST_Search_AreaPolygons)
1391 // Get the bounding box and outline polygon
1392 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1393 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1394 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1395 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1396 if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1397 if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1398 if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1399 if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
1400 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1401 $aPointPolygon = $this->oDB->getRow($sSQL);
1402 if (PEAR::IsError($aPointPolygon))
1404 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1407 if ($aPointPolygon['place_id'])
1409 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1410 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1411 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1412 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
1414 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1416 $aResult['lat'] = $aPointPolygon['centrelat'];
1417 $aResult['lon'] = $aPointPolygon['centrelon'];
1420 if ($this->bIncludePolygonAsPoints)
1422 // Translate geometary string to point array
1423 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1425 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1427 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1429 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1431 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1434 $iSteps = ($fRadius * 40000)^2;
1435 $fStepSize = (2*pi())/$iSteps;
1436 $aPolyPoints = array();
1437 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1439 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1441 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1442 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1443 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1444 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1448 // Output data suitable for display (points and a bounding box)
1449 if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
1451 $aResult['aPolyPoints'] = array();
1452 foreach($aPolyPoints as $aPoint)
1454 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1457 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1461 if ($aResult['extra_place'] == 'city')
1463 $aResult['class'] = 'place';
1464 $aResult['type'] = 'city';
1465 $aResult['rank_search'] = 16;
1468 if (!isset($aResult['aBoundingBox']))
1471 $fDiameter = 0.0001;
1473 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1474 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1476 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1478 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1479 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1481 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1483 $fRadius = $fDiameter / 2;
1485 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1486 $fStepSize = (2*pi())/$iSteps;
1487 $aPolyPoints = array();
1488 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1490 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1492 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1493 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1494 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1495 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1497 // Output data suitable for display (points and a bounding box)
1498 if ($this->bIncludePolygonAsPoints)
1500 $aResult['aPolyPoints'] = array();
1501 foreach($aPolyPoints as $aPoint)
1503 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1506 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1509 // Is there an icon set for this type of result?
1510 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1511 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1513 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1516 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1517 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1519 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1521 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1522 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1524 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1527 if ($this->bIncludeAddressDetails)
1529 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1530 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1532 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1536 // Adjust importance for the number of exact string matches in the result
1537 $aResult['importance'] = max(0.001,$aResult['importance']);
1539 $sAddress = $aResult['langaddress'];
1540 foreach($aRecheckWords as $i => $sWord)
1542 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1545 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
1547 $aResult['name'] = $aResult['langaddress'];
1548 $aResult['foundorder'] = -$aResult['addressimportance'];
1549 $aSearchResults[$iResNum] = $aResult;
1551 uasort($aSearchResults, 'byImportance');
1553 $aOSMIDDone = array();
1554 $aClassTypeNameDone = array();
1555 $aToFilter = $aSearchResults;
1556 $aSearchResults = array();
1559 foreach($aToFilter as $iResNum => $aResult)
1561 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1562 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1565 $fLat = $aResult['lat'];
1566 $fLon = $aResult['lon'];
1567 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1570 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1571 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1573 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1574 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1575 $aSearchResults[] = $aResult;
1578 // Absolute limit on number of results
1579 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1582 return $aSearchResults;
1591 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
1593 $aPoints = explode(',',$_GET['route']);
1594 if (sizeof($aPoints) % 2 != 0)
1596 userError("Uneven number of points");
1599 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
1600 $fPrevCoord = false;