2 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3 require_once(CONST_BasePath.'/lib/log.php');
5 ini_set('memory_limit', '200M');
9 $fLat = CONST_Default_Lat;
10 $fLon = CONST_Default_Lon;
11 $iZoom = CONST_Default_Zoom;
12 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13 $sOutputFormat = 'html';
14 $aSearchResults = array();
15 $aExcludePlaceIDs = array();
16 $sCountryCodesSQL = false;
17 $sSuggestion = $sSuggestionURL = false;
18 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19 $bReverseInPlan = false;
20 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iLimit > 100) $iLimit = 100;
25 $iMaxAddressRank = 30;
28 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
30 $sOutputFormat = $_GET['format'];
33 // Show / use polygons
34 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
36 // Show address breakdown
37 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
40 $aLangPrefOrder = getPreferredLanguages();
41 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
42 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
43 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
45 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
47 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
49 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
51 $iExcludedPlaceID = (int)$iExcludedPlaceID;
52 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
56 // Only certain ranks of feature
57 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
59 if (isset($_GET['featuretype']))
61 switch($_GET['featuretype'])
64 $iMinAddressRank = $iMaxAddressRank = 4;
67 $iMinAddressRank = $iMaxAddressRank = 8;
70 $iMinAddressRank = 14;
71 $iMaxAddressRank = 16;
75 $iMaxAddressRank = 20;
80 if (isset($_GET['countrycodes']))
82 $aCountryCodes = array();
83 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
85 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
87 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
90 $sCountryCodesSQL = join(',', $aCountryCodes);
94 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
95 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
97 $sQuery = substr($_SERVER['PATH_INFO'], 1);
99 // reverse order of '/' seperated string
100 $aPhrases = explode('/', $sQuery);
101 $aPhrases = array_reverse($aPhrases);
102 $sQuery = join(', ',$aPhrases);
106 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
108 // Hack to make it handle "new york, ny" (and variants) correctly
109 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
110 if (isset($aLangPrefOrder['name:en']))
112 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
113 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
114 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
117 // If we have a view box create the SQL
118 // Small is the actual view box, Large is double (on each axis) that
119 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
120 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
122 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
123 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
125 if (isset($_GET['viewbox']) && $_GET['viewbox'])
127 $aCoOrdinates = explode(',',$_GET['viewbox']);
128 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
129 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
130 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
131 $aCoOrdinates[0] += $fHeight;
132 $aCoOrdinates[2] -= $fHeight;
133 $aCoOrdinates[1] += $fWidth;
134 $aCoOrdinates[3] -= $fWidth;
135 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
137 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
139 $aPoints = explode(',',$_GET['route']);
140 if (sizeof($aPoints) % 2 != 0)
142 echo "Uneven number of points";
145 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
147 foreach($aPoints as $i => $fPoint)
151 if ($i != 1) $sViewboxCentreSQL .= ",";
152 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
156 $fPrevCoord = (float)$fPoint;
159 $sViewboxCentreSQL .= ")'::geometry,4326)";
161 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
162 $sViewboxSmallSQL = $oDB->getOne($sSQL);
163 if (PEAR::isError($sViewboxSmallSQL))
165 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
167 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
169 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
170 $sViewboxLargeSQL = $oDB->getOne($sSQL);
171 if (PEAR::isError($sViewboxLargeSQL))
173 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
175 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
178 // Do we have anything that looks like a lat/lon pair?
179 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
181 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
182 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
183 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
185 $_GET['nearlat'] = $fQueryLat;
186 $_GET['nearlon'] = $fQueryLon;
187 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
190 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
192 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
193 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
194 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
196 $_GET['nearlat'] = $fQueryLat;
197 $_GET['nearlon'] = $fQueryLon;
198 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
201 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
203 $fQueryLat = $aData[2];
204 $fQueryLon = $aData[3];
205 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
207 $_GET['nearlat'] = $fQueryLat;
208 $_GET['nearlon'] = $fQueryLon;
209 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
215 // Start with a blank search
217 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
218 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
221 $sNearPointSQL = false;
222 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
224 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
225 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
226 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
227 $aSearches[0]['fRadius'] = 0.1;
230 $bSpecialTerms = false;
231 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
232 $aSpecialTerms = array();
233 foreach($aSpecialTermsRaw as $aSpecialTerm)
235 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
236 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
239 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
240 $aSpecialTerms = array();
241 foreach($aSpecialTermsRaw as $aSpecialTerm)
243 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
244 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
245 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
246 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\',\'highway\')) or country_code is not null';
247 if (CONST_Debug) var_Dump($sSQL);
248 $aSearchWords = $oDB->getAll($sSQL);
249 $aNewSearches = array();
250 foreach($aSearches as $aSearch)
252 foreach($aSearchWords as $aSearchTerm)
254 $aNewSearch = $aSearch;
255 if ($aSearchTerm['country_code'])
257 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
258 $aNewSearches[] = $aNewSearch;
259 $bSpecialTerms = true;
261 if ($aSearchTerm['class'])
263 $aNewSearch['sClass'] = $aSearchTerm['class'];
264 $aNewSearch['sType'] = $aSearchTerm['type'];
265 $aNewSearches[] = $aNewSearch;
266 $bSpecialTerms = true;
270 $aSearches = $aNewSearches;
273 // Split query into phrases
274 // Commas are used to reduce the search space by indicating where phrases split
275 $aPhrases = explode(',',$sQuery);
277 // Convert each phrase to standard form
278 // Create a list of standard words
279 // Get all 'sets' of words
280 // Generate a complete list of all
282 foreach($aPhrases as $iPhrase => $sPhrase)
284 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
285 if (PEAR::isError($aPhrase))
287 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
288 if (CONST_Debug) var_dump($aPhrase);
291 if (trim($aPhrase['string']))
293 $aPhrases[$iPhrase] = $aPhrase;
294 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
295 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
296 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
300 unset($aPhrases[$iPhrase]);
304 // reindex phrases - we make assumptions later on
305 $aPhrases = array_values($aPhrases);
307 if (sizeof($aTokens))
310 // Check which tokens we have, get the ID numbers
311 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
312 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
313 $sSQL .= ' and (class is null or class not in (\'highway\'))';
314 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
316 if (CONST_Debug) var_Dump($sSQL);
318 $aValidTokens = array();
319 if (sizeof($aTokens))
320 $aDatabaseWords = $oDB->getAll($sSQL);
322 $aDatabaseWords = array();
323 if (PEAR::IsError($aDatabaseWords))
325 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
327 $aPossibleMainWordIDs = array();
328 foreach($aDatabaseWords as $aToken)
330 if (isset($aValidTokens[$aToken['word_token']]))
332 $aValidTokens[$aToken['word_token']][] = $aToken;
336 $aValidTokens[$aToken['word_token']] = array($aToken);
338 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
340 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
342 $aSuggestion = array();
343 $bSuggestion = false;
344 if (CONST_Suggestions_Enabled)
346 foreach($aPhrases as $iPhrase => $aPhrase)
348 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
350 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
351 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
352 $aRow = $aSuggestionWords[0];
353 if ($aRow && $aRow['word'])
355 $aSuggestion[] = $aRow['word'];
360 $aSuggestion[] = $aPhrase['string'];
365 $aSuggestion[] = $aPhrase['string'];
369 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
371 // Try and calculate GB postcodes we might be missing
372 foreach($aTokens as $sToken)
374 // Source of gb postcodes is now definitive - always use
375 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
377 if (substr($aData[1],-2,1) != ' ')
379 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
380 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
382 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
383 if ($aGBPostcodeLocation)
385 $aValidTokens[$sToken] = $aGBPostcodeLocation;
390 foreach($aTokens as $sToken)
392 // Unknown single word token with a number - assume it is a house number
393 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
395 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
399 // Any words that have failed completely?
402 // Start the search process
403 $aResultPlaceIDs = array();
406 Calculate all searches using aValidTokens i.e.
408 'Wodsworth Road, Sheffield' =>
412 0 1 (wodsworth)(road)
415 Score how good the search is so they can be ordered
417 foreach($aPhrases as $iPhrase => $sPhrase)
419 $aNewPhraseSearches = array();
421 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
423 $aWordsetSearches = $aSearches;
425 // Add all words from this wordset
426 foreach($aWordset as $sToken)
428 //echo "<br><b>$sToken</b>";
429 $aNewWordsetSearches = array();
431 foreach($aWordsetSearches as $aCurrentSearch)
434 //var_dump($aCurrentSearch);
437 // If the token is valid
438 if (isset($aValidTokens[' '.$sToken]))
440 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
442 $aSearch = $aCurrentSearch;
443 $aSearch['iSearchRank']++;
444 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
446 if ($aSearch['sCountryCode'] === false)
448 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
449 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
450 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
451 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
454 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
456 if ($aSearch['fLat'] === '')
458 $aSearch['fLat'] = $aSearchTerm['lat'];
459 $aSearch['fLon'] = $aSearchTerm['lon'];
460 $aSearch['fRadius'] = $aSearchTerm['radius'];
461 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
464 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
466 if ($aSearch['sHouseNumber'] === '')
468 $aSearch['sHouseNumber'] = $sToken;
469 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
471 // Fall back to not searching for this item (better than nothing)
472 $aSearch = $aCurrentSearch;
473 $aSearch['iSearchRank'] += 1;
474 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
478 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
480 if ($aSearch['sClass'] === '')
482 $aSearch['sOperator'] = $aSearchTerm['operator'];
483 $aSearch['sClass'] = $aSearchTerm['class'];
484 $aSearch['sType'] = $aSearchTerm['type'];
485 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
486 else $aSearch['sOperator'] = 'near'; // near = in for the moment
488 // Do we have a shortcut id?
489 if ($aSearch['sOperator'] == 'name')
491 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
492 if ($iAmenityID = $oDB->getOne($sSQL))
494 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
495 $aSearch['aName'][$iAmenityID] = $iAmenityID;
496 $aSearch['sClass'] = '';
497 $aSearch['sType'] = '';
500 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
503 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
505 if (sizeof($aSearch['aName']))
507 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
509 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
513 $aSearch['iSearchRank'] += 1000; // skip;
518 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
519 // $aSearch['iNamePhrase'] = $iPhrase;
521 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
525 if (isset($aValidTokens[$sToken]))
527 // Allow searching for a word - but at extra cost
528 foreach($aValidTokens[$sToken] as $aSearchTerm)
530 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
532 //var_Dump('<hr>',$aSearch['aName']);
534 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
536 $aSearch = $aCurrentSearch;
537 $aSearch['iSearchRank'] += 1;
538 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
539 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
542 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
544 $aSearch = $aCurrentSearch;
545 $aSearch['iSearchRank'] += 2;
546 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
547 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
548 $aSearch['iNamePhrase'] = $iPhrase;
549 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
556 // Allow skipping a word - but at EXTREAM cost
557 //$aSearch = $aCurrentSearch;
558 //$aSearch['iSearchRank']+=100;
559 //$aNewWordsetSearches[] = $aSearch;
563 usort($aNewWordsetSearches, 'bySearchRank');
564 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
566 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
568 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
569 usort($aNewPhraseSearches, 'bySearchRank');
571 $aSearchHash = array();
572 foreach($aNewPhraseSearches as $iSearch => $aSearch)
574 $sHash = serialize($aSearch);
575 if (isset($aSearchHash[$sHash]))
577 unset($aNewPhraseSearches[$iSearch]);
581 $aSearchHash[$sHash] = 1;
585 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
588 // Re-group the searches by their score, junk anything over 20 as just not worth trying
589 $aGroupedSearches = array();
590 foreach($aNewPhraseSearches as $aSearch)
592 if ($aSearch['iSearchRank'] < $iMaxRank)
594 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
595 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
598 ksort($aGroupedSearches);
601 $aSearches = array();
602 foreach($aGroupedSearches as $iScore => $aNewSearches)
604 $iSearchCount += sizeof($aNewSearches);
605 $aSearches = array_merge($aSearches, $aNewSearches);
606 if ($iSearchCount > 50) break;
609 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
615 // Re-group the searches by their score, junk anything over 20 as just not worth trying
616 $aGroupedSearches = array();
617 foreach($aSearches as $aSearch)
619 if ($aSearch['iSearchRank'] < $iMaxRank)
621 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
622 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
625 ksort($aGroupedSearches);
628 if (CONST_Debug) var_Dump($aGroupedSearches);
632 $aCopyGroupedSearches = $aGroupedSearches;
633 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
635 foreach($aSearches as $iSearch => $aSearch)
637 if (sizeof($aSearch['aAddress']))
639 $iReverseItem = array_pop($aSearch['aAddress']);
640 if (isset($aPossibleMainWordIDs[$iReverseItem]))
642 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
643 $aSearch['aName'] = array($iReverseItem);
644 $aGroupedSearches[$iGroup][] = $aSearch;
646 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
647 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
653 // Filter out duplicate searches
654 $aSearchHash = array();
655 foreach($aGroupedSearches as $iGroup => $aSearches)
657 foreach($aSearches as $iSearch => $aSearch)
659 $sHash = serialize($aSearch);
660 if (isset($aSearchHash[$sHash]))
662 unset($aGroupedSearches[$iGroup][$iSearch]);
663 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
667 $aSearchHash[$sHash] = 1;
672 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
676 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
679 foreach($aSearches as $aSearch)
683 // Must have a location term
684 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
686 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
688 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
690 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
691 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
692 $sSQL .= " order by st_area(geometry) desc limit 1";
693 $aPlaceIDs = $oDB->getCol($sSQL);
698 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
699 if (!$aSearch['sClass']) continue;
700 if (CONST_Debug) var_dump('<hr>',$aSearch);
701 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
703 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
704 if ($oDB->getOne($sSQL))
706 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
707 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
708 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
709 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
710 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
711 $sSQL .= " limit $iLimit";
712 if (CONST_Debug) var_dump($sSQL);
713 $aPlaceIDs = $oDB->getCol($sSQL);
715 if (!sizeof($aPlaceIDs))
717 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
718 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
719 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
720 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
721 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
722 $sSQL .= " limit $iLimit";
723 if (CONST_Debug) var_dump($sSQL);
724 $aPlaceIDs = $oDB->getCol($sSQL);
729 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
730 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
731 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
732 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
733 $sSQL .= " limit $iLimit";
734 if (CONST_Debug) var_dump($sSQL);
735 $aPlaceIDs = $oDB->getCol($sSQL);
741 if (CONST_Debug) var_dump('<hr>',$aSearch);
742 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
743 $aPlaceIDs = array();
745 // First we need a position, either aName or fLat or both
749 // TODO: filter out the pointless search terms (2 letter name tokens and less)
750 // they might be right - but they are just too darned expensive to run
751 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
752 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
753 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
754 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
755 if ($aSearch['fLon'] && $aSearch['fLat'])
757 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
758 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
760 if (sizeof($aExcludePlaceIDs))
762 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
764 if ($sCountryCodesSQL)
766 $aTerms[] = "country_code in ($sCountryCodesSQL)";
769 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
770 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
772 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
774 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
775 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
776 $aOrder[] = "$sImportanceSQL DESC";
780 $sSQL = "select place_id";
781 $sSQL .= " from search_name";
782 $sSQL .= " where ".join(' and ',$aTerms);
783 $sSQL .= " order by ".join(', ',$aOrder);
784 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
785 $sSQL .= " limit 50";
786 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
789 $sSQL .= " limit ".$iLimit;
791 if (CONST_Debug) var_dump($sSQL);
792 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
793 if (PEAR::IsError($aViewBoxPlaceIDs))
795 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
797 //var_dump($aViewBoxPlaceIDs);
798 // Did we have an viewbox matches?
799 $aPlaceIDs = array();
800 $bViewBoxMatch = false;
801 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
803 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
804 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
805 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
806 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
807 $aPlaceIDs[] = $aViewBoxRow['place_id'];
810 //var_Dump($aPlaceIDs);
813 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
815 $aRoadPlaceIDs = $aPlaceIDs;
816 $sPlaceIDs = join(',',$aPlaceIDs);
818 // Now they are indexed look for a house attached to a street we found
819 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
820 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
821 if (sizeof($aExcludePlaceIDs))
823 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
825 $sSQL .= " limit $iLimit";
826 if (CONST_Debug) var_dump($sSQL);
827 $aPlaceIDs = $oDB->getCol($sSQL);
829 // If not try the aux fallback table
830 if (!sizeof($aPlaceIDs))
832 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
833 if (sizeof($aExcludePlaceIDs))
835 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
837 // $sSQL .= " limit $iLimit";
838 if (CONST_Debug) var_dump($sSQL);
839 $aPlaceIDs = $oDB->getCol($sSQL);
842 if (!sizeof($aPlaceIDs))
844 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
845 if (sizeof($aExcludePlaceIDs))
847 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
849 // $sSQL .= " limit $iLimit";
850 if (CONST_Debug) var_dump($sSQL);
851 $aPlaceIDs = $oDB->getCol($sSQL);
854 // Fallback to the road
855 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
857 $aPlaceIDs = $aRoadPlaceIDs;
862 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
864 $sPlaceIDs = join(',',$aPlaceIDs);
866 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
868 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
869 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
870 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
871 $sSQL .= " order by rank_search asc limit $iLimit";
872 if (CONST_Debug) var_dump($sSQL);
873 $aPlaceIDs = $oDB->getCol($sSQL);
876 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
878 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
879 $bCacheTable = $oDB->getOne($sSQL);
881 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
883 if (CONST_Debug) var_dump($sSQL);
884 $iMaxRank = ((int)$oDB->getOne($sSQL));
886 // For state / country level searches the normal radius search doesn't work very well
888 if ($iMaxRank < 9 && $bCacheTable)
890 // Try and get a polygon to search in instead
891 $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
892 if (CONST_Debug) var_dump($sSQL);
893 $sPlaceGeom = $oDB->getOne($sSQL);
903 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
904 if (CONST_Debug) var_dump($sSQL);
905 $aPlaceIDs = $oDB->getCol($sSQL);
906 $sPlaceIDs = join(',',$aPlaceIDs);
909 if ($sPlaceIDs || $sPlaceGeom)
915 // More efficient - can make the range bigger
919 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
920 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
921 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
923 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
924 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
927 $sSQL .= ",placex as f where ";
928 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
933 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
935 if (sizeof($aExcludePlaceIDs))
937 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
939 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
940 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
941 if ($iOffset) $sSQL .= " offset $iOffset";
942 $sSQL .= " limit $iLimit";
943 if (CONST_Debug) var_dump($sSQL);
944 $aPlaceIDs = $oDB->getCol($sSQL);
948 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
951 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
952 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
954 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
955 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
956 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
957 if (sizeof($aExcludePlaceIDs))
959 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
961 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
962 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
963 if ($iOffset) $sSQL .= " offset $iOffset";
964 $sSQL .= " limit $iLimit";
965 if (CONST_Debug) var_dump($sSQL);
966 $aPlaceIDs = $oDB->getCol($sSQL);
974 if (PEAR::IsError($aPlaceIDs))
976 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
979 if (CONST_Debug) var_Dump($aPlaceIDs);
981 foreach($aPlaceIDs as $iPlaceID)
983 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
985 if ($iQueryLoop > 20) break;
988 if (sizeof($aResultPlaceIDs)) break;
989 if ($iGroupLoop > 4) break;
990 if ($iQueryLoop > 30) break;
993 // Did we find anything?
994 if (sizeof($aResultPlaceIDs))
996 //var_Dump($aResultPlaceIDs);exit;
997 // Get the details for display (is this a redundant extra step?)
998 $sPlaceIDs = join(',',$aResultPlaceIDs);
999 $sOrderSQL = 'CASE ';
1000 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1002 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1004 $sOrderSQL .= ' ELSE 10000000 END';
1005 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1006 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1007 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1008 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1009 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1010 // $sSQL .= $sOrderSQL." as porder, ";
1011 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1012 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1013 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1014 $sSQL .= "and linked_place_id is null ";
1015 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1016 if (!$bDeDupe) $sSQL .= ",place_id";
1017 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1018 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1019 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1021 $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,";
1022 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1023 $sSQL .= "null as placename,";
1024 $sSQL .= "null as ref,";
1025 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1026 // $sSQL .= $sOrderSQL." as porder, ";
1027 $sSQL .= "-0.15 as importance ";
1028 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1029 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1030 $sSQL .= "group by place_id";
1031 if (!$bDeDupe) $sSQL .= ",place_id";
1033 $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,";
1034 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1035 $sSQL .= "null as placename,";
1036 $sSQL .= "null as ref,";
1037 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1038 // $sSQL .= $sOrderSQL." as porder, ";
1039 $sSQL .= "-0.10 as importance ";
1040 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1041 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1042 $sSQL .= "group by place_id";
1043 if (!$bDeDupe) $sSQL .= ",place_id";
1044 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1045 $sSQL .= "order by importance desc";
1046 // $sSQL .= "order by rank_search,rank_address,porder asc";
1047 if (CONST_Debug) var_dump('<hr>',$sSQL);
1048 $aSearchResults = $oDB->getAll($sSQL);
1049 //var_dump($sSQL,$aSearchResults);exit;
1051 if (PEAR::IsError($aSearchResults))
1053 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1056 } // end if ($sQuery)
1059 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1061 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1062 $aResultPlaceIDs = array($iPlaceID);
1064 // TODO: this needs refactoring!
1066 // Get the details for display (is this a redundant extra step?)
1067 $sPlaceIDs = join(',',$aResultPlaceIDs);
1068 $sOrderSQL = 'CASE ';
1069 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1071 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1073 $sOrderSQL .= ' ELSE 10000000 END';
1074 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1075 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1076 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1077 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1078 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1079 // $sSQL .= $sOrderSQL." as porder, ";
1080 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1081 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1082 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1083 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1084 if (!$bDeDupe) $sSQL .= ",place_id";
1085 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1086 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1087 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1089 $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,";
1090 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1091 $sSQL .= "null as placename,";
1092 $sSQL .= "null as ref,";
1093 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1094 // $sSQL .= $sOrderSQL." as porder, ";
1095 $sSQL .= "-0.15 as importance ";
1096 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1097 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1098 $sSQL .= "group by place_id";
1099 if (!$bDeDupe) $sSQL .= ",place_id";
1101 $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,";
1102 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1103 $sSQL .= "null as placename,";
1104 $sSQL .= "null as ref,";
1105 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1106 // $sSQL .= $sOrderSQL." as porder, ";
1107 $sSQL .= "-0.10 as importance ";
1108 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1109 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1110 $sSQL .= "group by place_id";
1111 if (!$bDeDupe) $sSQL .= ",place_id";
1112 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1113 $sSQL .= "order by importance desc";
1114 // $sSQL .= "order by rank_search,rank_address,porder asc";
1115 if (CONST_Debug) var_dump('<hr>',$sSQL);
1116 $aSearchResults = $oDB->getAll($sSQL);
1117 //var_dump($sSQL,$aSearchResults);exit;
1119 if (PEAR::IsError($aSearchResults))
1121 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1127 $sSearchResult = '';
1128 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1130 $sSearchResult = 'No Results Found';
1132 //var_Dump($aSearchResults);
1134 $aClassType = getClassTypesWithImportance();
1135 $aRecheckWords = preg_split('/\b/',$sQuery);
1136 foreach($aRecheckWords as $i => $sWord)
1138 if (!$sWord) unset($aRecheckWords[$i]);
1140 foreach($aSearchResults as $iResNum => $aResult)
1142 if (CONST_Search_AreaPolygons)
1144 // Get the bounding box and outline polygon
1145 $sSQL = "select place_id,numfeatures,area,outline,";
1146 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1147 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1148 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1150 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1151 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1152 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1153 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1154 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1155 $aPointPolygon = $oDB->getRow($sSQL);
1156 if (PEAR::IsError($aPointPolygon))
1158 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1160 if ($aPointPolygon['place_id'])
1162 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1163 $aResult['lat'] = $aPointPolygon['centrelat'];
1164 $aResult['lon'] = $aPointPolygon['centrelon'];
1166 // Translate geometary string to point array
1167 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1169 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1171 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1174 $iSteps = ($fRadius * 40000)^2;
1175 $fStepSize = (2*pi())/$iSteps;
1176 $aPolyPoints = array();
1177 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1179 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1181 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1182 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1183 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1184 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1187 // Output data suitable for display (points and a bounding box)
1188 if ($bShowPolygons && isset($aPolyPoints))
1190 $aResult['aPolyPoints'] = array();
1191 foreach($aPolyPoints as $aPoint)
1193 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1196 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1200 if (!isset($aResult['aBoundingBox']))
1203 $fDiameter = 0.0001;
1205 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1206 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1208 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1210 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1211 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1213 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1215 $fRadius = $fDiameter / 2;
1217 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1218 $fStepSize = (2*pi())/$iSteps;
1219 $aPolyPoints = array();
1220 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1222 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1224 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1225 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1226 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1227 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1229 // Output data suitable for display (points and a bounding box)
1232 $aResult['aPolyPoints'] = array();
1233 foreach($aPolyPoints as $aPoint)
1235 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1238 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1241 // Is there an icon set for this type of result?
1242 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1243 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1245 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1248 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1249 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1251 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1254 if ($bShowAddressDetails)
1256 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1257 //var_dump($aResult['address']);
1261 // Adjust importance for the number of exact string matches in the result
1262 $aResult['importance'] = max(0.001,$aResult['importance']);
1264 $sAddress = $aResult['langaddress'];
1265 foreach($aRecheckWords as $i => $sWord)
1267 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1269 $aResult['importance'] = $aResult['importance'] + $iCountWords;
1271 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1273 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1274 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1276 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1278 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1279 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1281 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1285 $aResult['importance'] = 1000000000000000;
1288 $aResult['name'] = $aResult['langaddress'];
1289 $aResult['foundorder'] = $iResNum;
1290 $aSearchResults[$iResNum] = $aResult;
1292 uasort($aSearchResults, 'byImportance');
1294 //var_dump($aSearchResults);exit;
1296 $aOSMIDDone = array();
1297 $aClassTypeNameDone = array();
1298 $aToFilter = $aSearchResults;
1299 $aSearchResults = array();
1302 foreach($aToFilter as $iResNum => $aResult)
1304 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1305 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1308 $fLat = $aResult['lat'];
1309 $fLon = $aResult['lon'];
1310 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1313 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1314 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1316 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1317 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1318 $aSearchResults[] = $aResult;
1321 // Absolute limit on number of results
1322 if (sizeof($aSearchResults) >= $iLimit) break;
1325 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1327 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1329 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1334 logEnd($oDB, $hLog, sizeof($aToFilter));
1336 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1337 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1338 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1339 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1340 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1341 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1344 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1346 $sMoreURL .= '&q='.urlencode($sQuery);
1348 if (CONST_Debug) exit;
1350 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');