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 '/' separated 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 $bBoundingBoxSearch = false;
139 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
141 $aPoints = explode(',',$_GET['route']);
142 if (sizeof($aPoints) % 2 != 0)
144 echo "Uneven number of points";
147 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
149 foreach($aPoints as $i => $fPoint)
153 if ($i != 1) $sViewboxCentreSQL .= ",";
154 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
158 $fPrevCoord = (float)$fPoint;
161 $sViewboxCentreSQL .= ")'::geometry,4326)";
163 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
164 $sViewboxSmallSQL = $oDB->getOne($sSQL);
165 if (PEAR::isError($sViewboxSmallSQL))
167 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
169 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
171 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
172 $sViewboxLargeSQL = $oDB->getOne($sSQL);
173 if (PEAR::isError($sViewboxLargeSQL))
175 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
177 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
180 // Do we have anything that looks like a lat/lon pair?
181 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
183 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
184 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
185 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
187 $_GET['nearlat'] = $fQueryLat;
188 $_GET['nearlon'] = $fQueryLon;
189 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
192 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
194 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
195 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
196 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
198 $_GET['nearlat'] = $fQueryLat;
199 $_GET['nearlon'] = $fQueryLon;
200 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
203 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
205 $fQueryLat = $aData[2];
206 $fQueryLon = $aData[3];
207 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
209 $_GET['nearlat'] = $fQueryLat;
210 $_GET['nearlon'] = $fQueryLon;
211 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
217 // Start with a blank search
219 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
220 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
223 $sNearPointSQL = false;
224 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
226 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
227 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
228 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
229 $aSearches[0]['fRadius'] = 0.1;
232 $bSpecialTerms = false;
233 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
234 $aSpecialTerms = array();
235 foreach($aSpecialTermsRaw as $aSpecialTerm)
237 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
238 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
241 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
242 $aSpecialTerms = array();
243 foreach($aSpecialTermsRaw as $aSpecialTerm)
245 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
246 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
247 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
248 $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';
249 if (CONST_Debug) var_Dump($sSQL);
250 $aSearchWords = $oDB->getAll($sSQL);
251 $aNewSearches = array();
252 foreach($aSearches as $aSearch)
254 foreach($aSearchWords as $aSearchTerm)
256 $aNewSearch = $aSearch;
257 if ($aSearchTerm['country_code'])
259 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
260 $aNewSearches[] = $aNewSearch;
261 $bSpecialTerms = true;
263 if ($aSearchTerm['class'])
265 $aNewSearch['sClass'] = $aSearchTerm['class'];
266 $aNewSearch['sType'] = $aSearchTerm['type'];
267 $aNewSearches[] = $aNewSearch;
268 $bSpecialTerms = true;
272 $aSearches = $aNewSearches;
275 // Split query into phrases
276 // Commas are used to reduce the search space by indicating where phrases split
277 $aPhrases = explode(',',$sQuery);
279 // Convert each phrase to standard form
280 // Create a list of standard words
281 // Get all 'sets' of words
282 // Generate a complete list of all
284 foreach($aPhrases as $iPhrase => $sPhrase)
286 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
287 if (PEAR::isError($aPhrase))
289 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
290 if (CONST_Debug) var_dump($aPhrase);
293 if (trim($aPhrase['string']))
295 $aPhrases[$iPhrase] = $aPhrase;
296 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
297 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
298 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
302 unset($aPhrases[$iPhrase]);
306 // reindex phrases - we make assumptions later on
307 $aPhrases = array_values($aPhrases);
309 if (sizeof($aTokens))
312 // Check which tokens we have, get the ID numbers
313 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
314 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
315 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
316 $sSQL .= ' and (class is null or class not in (\'highway\'))';
317 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
319 if (CONST_Debug) var_Dump($sSQL);
321 $aValidTokens = array();
322 if (sizeof($aTokens))
323 $aDatabaseWords = $oDB->getAll($sSQL);
325 $aDatabaseWords = array();
326 if (PEAR::IsError($aDatabaseWords))
328 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
330 $aPossibleMainWordIDs = array();
331 foreach($aDatabaseWords as $aToken)
333 if (isset($aValidTokens[$aToken['word_token']]))
335 $aValidTokens[$aToken['word_token']][] = $aToken;
339 $aValidTokens[$aToken['word_token']] = array($aToken);
341 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
343 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
345 $aSuggestion = array();
346 $bSuggestion = false;
347 if (CONST_Suggestions_Enabled)
349 foreach($aPhrases as $iPhrase => $aPhrase)
351 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
353 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
354 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
355 $aRow = $aSuggestionWords[0];
356 if ($aRow && $aRow['word'])
358 $aSuggestion[] = $aRow['word'];
363 $aSuggestion[] = $aPhrase['string'];
368 $aSuggestion[] = $aPhrase['string'];
372 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
374 // Try and calculate GB postcodes we might be missing
375 foreach($aTokens as $sToken)
377 // Source of gb postcodes is now definitive - always use
378 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
380 if (substr($aData[1],-2,1) != ' ')
382 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
383 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
385 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
386 if ($aGBPostcodeLocation)
388 $aValidTokens[$sToken] = $aGBPostcodeLocation;
393 foreach($aTokens as $sToken)
395 // Unknown single word token with a number - assume it is a house number
396 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
398 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
402 // Any words that have failed completely?
405 // Start the search process
406 $aResultPlaceIDs = array();
409 Calculate all searches using aValidTokens i.e.
411 'Wodsworth Road, Sheffield' =>
415 0 1 (wodsworth)(road)
418 Score how good the search is so they can be ordered
420 foreach($aPhrases as $iPhrase => $sPhrase)
422 $aNewPhraseSearches = array();
424 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
426 $aWordsetSearches = $aSearches;
428 // Add all words from this wordset
429 foreach($aWordset as $sToken)
431 //echo "<br><b>$sToken</b>";
432 $aNewWordsetSearches = array();
434 foreach($aWordsetSearches as $aCurrentSearch)
437 //var_dump($aCurrentSearch);
440 // If the token is valid
441 if (isset($aValidTokens[' '.$sToken]))
443 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
445 $aSearch = $aCurrentSearch;
446 $aSearch['iSearchRank']++;
447 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
449 if ($aSearch['sCountryCode'] === false)
451 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
452 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
453 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
454 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
457 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
459 if ($aSearch['fLat'] === '')
461 $aSearch['fLat'] = $aSearchTerm['lat'];
462 $aSearch['fLon'] = $aSearchTerm['lon'];
463 $aSearch['fRadius'] = $aSearchTerm['radius'];
464 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
467 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
469 if ($aSearch['sHouseNumber'] === '')
471 $aSearch['sHouseNumber'] = $sToken;
472 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
474 // Fall back to not searching for this item (better than nothing)
475 $aSearch = $aCurrentSearch;
476 $aSearch['iSearchRank'] += 1;
477 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
481 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
483 if ($aSearch['sClass'] === '')
485 $aSearch['sOperator'] = $aSearchTerm['operator'];
486 $aSearch['sClass'] = $aSearchTerm['class'];
487 $aSearch['sType'] = $aSearchTerm['type'];
488 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
489 else $aSearch['sOperator'] = 'near'; // near = in for the moment
491 // Do we have a shortcut id?
492 if ($aSearch['sOperator'] == 'name')
494 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
495 if ($iAmenityID = $oDB->getOne($sSQL))
497 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
498 $aSearch['aName'][$iAmenityID] = $iAmenityID;
499 $aSearch['sClass'] = '';
500 $aSearch['sType'] = '';
503 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
506 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
508 if (sizeof($aSearch['aName']))
510 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
512 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
516 $aSearch['iSearchRank'] += 1000; // skip;
521 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
522 // $aSearch['iNamePhrase'] = $iPhrase;
524 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
528 if (isset($aValidTokens[$sToken]))
530 // Allow searching for a word - but at extra cost
531 foreach($aValidTokens[$sToken] as $aSearchTerm)
533 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
535 //var_Dump('<hr>',$aSearch['aName']);
537 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
539 $aSearch = $aCurrentSearch;
540 $aSearch['iSearchRank'] += 1;
541 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
542 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
545 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
547 $aSearch = $aCurrentSearch;
548 $aSearch['iSearchRank'] += 2;
549 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
550 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
551 $aSearch['iNamePhrase'] = $iPhrase;
552 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
559 // Allow skipping a word - but at EXTREAM cost
560 //$aSearch = $aCurrentSearch;
561 //$aSearch['iSearchRank']+=100;
562 //$aNewWordsetSearches[] = $aSearch;
566 usort($aNewWordsetSearches, 'bySearchRank');
567 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
569 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
571 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
572 usort($aNewPhraseSearches, 'bySearchRank');
574 $aSearchHash = array();
575 foreach($aNewPhraseSearches as $iSearch => $aSearch)
577 $sHash = serialize($aSearch);
578 if (isset($aSearchHash[$sHash]))
580 unset($aNewPhraseSearches[$iSearch]);
584 $aSearchHash[$sHash] = 1;
588 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
591 // Re-group the searches by their score, junk anything over 20 as just not worth trying
592 $aGroupedSearches = array();
593 foreach($aNewPhraseSearches as $aSearch)
595 if ($aSearch['iSearchRank'] < $iMaxRank)
597 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
598 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
601 ksort($aGroupedSearches);
604 $aSearches = array();
605 foreach($aGroupedSearches as $iScore => $aNewSearches)
607 $iSearchCount += sizeof($aNewSearches);
608 $aSearches = array_merge($aSearches, $aNewSearches);
609 if ($iSearchCount > 50) break;
612 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
618 // Re-group the searches by their score, junk anything over 20 as just not worth trying
619 $aGroupedSearches = array();
620 foreach($aSearches as $aSearch)
622 if ($aSearch['iSearchRank'] < $iMaxRank)
624 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
625 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
628 ksort($aGroupedSearches);
631 if (CONST_Debug) var_Dump($aGroupedSearches);
635 $aCopyGroupedSearches = $aGroupedSearches;
636 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
638 foreach($aSearches as $iSearch => $aSearch)
640 if (sizeof($aSearch['aAddress']))
642 $iReverseItem = array_pop($aSearch['aAddress']);
643 if (isset($aPossibleMainWordIDs[$iReverseItem]))
645 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
646 $aSearch['aName'] = array($iReverseItem);
647 $aGroupedSearches[$iGroup][] = $aSearch;
649 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
650 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
656 // Filter out duplicate searches
657 $aSearchHash = array();
658 foreach($aGroupedSearches as $iGroup => $aSearches)
660 foreach($aSearches as $iSearch => $aSearch)
662 $sHash = serialize($aSearch);
663 if (isset($aSearchHash[$sHash]))
665 unset($aGroupedSearches[$iGroup][$iSearch]);
666 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
670 $aSearchHash[$sHash] = 1;
675 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
679 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
682 foreach($aSearches as $aSearch)
686 // Must have a location term
687 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
689 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
691 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
693 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
694 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
695 $sSQL .= " order by st_area(geometry) desc limit 1";
696 $aPlaceIDs = $oDB->getCol($sSQL);
701 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
702 if (!$aSearch['sClass']) continue;
703 if (CONST_Debug) var_dump('<hr>',$aSearch);
704 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
706 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
707 if ($oDB->getOne($sSQL))
709 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
710 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
711 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
712 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
713 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
714 $sSQL .= " limit $iLimit";
715 if (CONST_Debug) var_dump($sSQL);
716 $aPlaceIDs = $oDB->getCol($sSQL);
718 if (!sizeof($aPlaceIDs))
720 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
721 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
722 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
723 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
724 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
725 $sSQL .= " limit $iLimit";
726 if (CONST_Debug) var_dump($sSQL);
727 $aPlaceIDs = $oDB->getCol($sSQL);
732 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
733 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
734 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
735 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
736 $sSQL .= " limit $iLimit";
737 if (CONST_Debug) var_dump($sSQL);
738 $aPlaceIDs = $oDB->getCol($sSQL);
744 if (CONST_Debug) var_dump('<hr>',$aSearch);
745 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
746 $aPlaceIDs = array();
748 // First we need a position, either aName or fLat or both
752 // TODO: filter out the pointless search terms (2 letter name tokens and less)
753 // they might be right - but they are just too darned expensive to run
754 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
755 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
756 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
757 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
758 if ($aSearch['fLon'] && $aSearch['fLat'])
760 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
761 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
763 if (sizeof($aExcludePlaceIDs))
765 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
767 if ($sCountryCodesSQL)
769 $aTerms[] = "country_code in ($sCountryCodesSQL)";
772 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
773 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
775 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
777 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
778 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
779 $aOrder[] = "$sImportanceSQL DESC";
783 $sSQL = "select place_id";
784 $sSQL .= " from search_name";
785 $sSQL .= " where ".join(' and ',$aTerms);
786 $sSQL .= " order by ".join(', ',$aOrder);
787 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
788 $sSQL .= " limit 50";
789 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
792 $sSQL .= " limit ".$iLimit;
794 if (CONST_Debug) var_dump($sSQL);
795 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
796 if (PEAR::IsError($aViewBoxPlaceIDs))
798 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
800 //var_dump($aViewBoxPlaceIDs);
801 // Did we have an viewbox matches?
802 $aPlaceIDs = array();
803 $bViewBoxMatch = false;
804 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
806 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
807 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
808 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
809 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
810 $aPlaceIDs[] = $aViewBoxRow['place_id'];
813 //var_Dump($aPlaceIDs);
816 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
818 $aRoadPlaceIDs = $aPlaceIDs;
819 $sPlaceIDs = join(',',$aPlaceIDs);
821 // Now they are indexed look for a house attached to a street we found
822 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
823 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
824 if (sizeof($aExcludePlaceIDs))
826 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
828 $sSQL .= " limit $iLimit";
829 if (CONST_Debug) var_dump($sSQL);
830 $aPlaceIDs = $oDB->getCol($sSQL);
832 // If not try the aux fallback table
833 if (!sizeof($aPlaceIDs))
835 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
836 if (sizeof($aExcludePlaceIDs))
838 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
840 // $sSQL .= " limit $iLimit";
841 if (CONST_Debug) var_dump($sSQL);
842 $aPlaceIDs = $oDB->getCol($sSQL);
845 if (!sizeof($aPlaceIDs))
847 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
848 if (sizeof($aExcludePlaceIDs))
850 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
852 // $sSQL .= " limit $iLimit";
853 if (CONST_Debug) var_dump($sSQL);
854 $aPlaceIDs = $oDB->getCol($sSQL);
857 // Fallback to the road
858 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
860 $aPlaceIDs = $aRoadPlaceIDs;
865 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
867 $sPlaceIDs = join(',',$aPlaceIDs);
869 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
871 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
872 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
873 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
874 $sSQL .= " order by rank_search asc limit $iLimit";
875 if (CONST_Debug) var_dump($sSQL);
876 $aPlaceIDs = $oDB->getCol($sSQL);
879 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
881 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
882 $bCacheTable = $oDB->getOne($sSQL);
884 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
886 if (CONST_Debug) var_dump($sSQL);
887 $iMaxRank = ((int)$oDB->getOne($sSQL));
889 // For state / country level searches the normal radius search doesn't work very well
891 if ($iMaxRank < 9 && $bCacheTable)
893 // Try and get a polygon to search in instead
894 $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";
895 if (CONST_Debug) var_dump($sSQL);
896 $sPlaceGeom = $oDB->getOne($sSQL);
906 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
907 if (CONST_Debug) var_dump($sSQL);
908 $aPlaceIDs = $oDB->getCol($sSQL);
909 $sPlaceIDs = join(',',$aPlaceIDs);
912 if ($sPlaceIDs || $sPlaceGeom)
918 // More efficient - can make the range bigger
922 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
923 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
924 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
926 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
927 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
930 $sSQL .= ",placex as f where ";
931 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
936 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
938 if (sizeof($aExcludePlaceIDs))
940 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
942 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
943 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
944 if ($iOffset) $sSQL .= " offset $iOffset";
945 $sSQL .= " limit $iLimit";
946 if (CONST_Debug) var_dump($sSQL);
947 $aPlaceIDs = $oDB->getCol($sSQL);
951 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
954 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
955 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
957 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
958 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
959 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
960 if (sizeof($aExcludePlaceIDs))
962 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
964 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
965 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
966 if ($iOffset) $sSQL .= " offset $iOffset";
967 $sSQL .= " limit $iLimit";
968 if (CONST_Debug) var_dump($sSQL);
969 $aPlaceIDs = $oDB->getCol($sSQL);
977 if (PEAR::IsError($aPlaceIDs))
979 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
982 if (CONST_Debug) var_Dump($aPlaceIDs);
984 foreach($aPlaceIDs as $iPlaceID)
986 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
988 if ($iQueryLoop > 20) break;
991 if (sizeof($aResultPlaceIDs)) break;
992 if ($iGroupLoop > 4) break;
993 if ($iQueryLoop > 30) break;
996 // Did we find anything?
997 if (sizeof($aResultPlaceIDs))
999 //var_Dump($aResultPlaceIDs);exit;
1000 // Get the details for display (is this a redundant extra step?)
1001 $sPlaceIDs = join(',',$aResultPlaceIDs);
1002 $sOrderSQL = 'CASE ';
1003 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1005 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1007 $sOrderSQL .= ' ELSE 10000000 END';
1008 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1009 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1010 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1011 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1012 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1013 // $sSQL .= $sOrderSQL." as porder, ";
1014 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1015 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1016 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1017 $sSQL .= "and linked_place_id is null ";
1018 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1019 if (!$bDeDupe) $sSQL .= ",place_id";
1020 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1021 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1022 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1024 $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,";
1025 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1026 $sSQL .= "null as placename,";
1027 $sSQL .= "null as ref,";
1028 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1029 // $sSQL .= $sOrderSQL." as porder, ";
1030 $sSQL .= "-0.15 as importance ";
1031 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1032 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1033 $sSQL .= "group by place_id";
1034 if (!$bDeDupe) $sSQL .= ",place_id";
1036 $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,";
1037 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1038 $sSQL .= "null as placename,";
1039 $sSQL .= "null as ref,";
1040 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1041 // $sSQL .= $sOrderSQL." as porder, ";
1042 $sSQL .= "-0.10 as importance ";
1043 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1044 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1045 $sSQL .= "group by place_id";
1046 if (!$bDeDupe) $sSQL .= ",place_id";
1047 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1048 $sSQL .= "order by importance desc";
1049 // $sSQL .= "order by rank_search,rank_address,porder asc";
1050 if (CONST_Debug) var_dump('<hr>',$sSQL);
1051 $aSearchResults = $oDB->getAll($sSQL);
1052 //var_dump($sSQL,$aSearchResults);exit;
1054 if (PEAR::IsError($aSearchResults))
1056 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1059 } // end if ($sQuery)
1062 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1064 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1065 $aResultPlaceIDs = array($iPlaceID);
1067 // TODO: this needs refactoring!
1069 // Get the details for display (is this a redundant extra step?)
1070 $sPlaceIDs = join(',',$aResultPlaceIDs);
1071 $sOrderSQL = 'CASE ';
1072 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1074 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1076 $sOrderSQL .= ' ELSE 10000000 END';
1077 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1078 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1079 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1080 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1081 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1082 // $sSQL .= $sOrderSQL." as porder, ";
1083 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1084 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1085 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1086 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1087 if (!$bDeDupe) $sSQL .= ",place_id";
1088 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1089 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1090 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1092 $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,";
1093 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1094 $sSQL .= "null as placename,";
1095 $sSQL .= "null as ref,";
1096 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1097 // $sSQL .= $sOrderSQL." as porder, ";
1098 $sSQL .= "-0.15 as importance ";
1099 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1100 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1101 $sSQL .= "group by place_id";
1102 if (!$bDeDupe) $sSQL .= ",place_id";
1104 $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,";
1105 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1106 $sSQL .= "null as placename,";
1107 $sSQL .= "null as ref,";
1108 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1109 // $sSQL .= $sOrderSQL." as porder, ";
1110 $sSQL .= "-0.10 as importance ";
1111 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1112 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1113 $sSQL .= "group by place_id";
1114 if (!$bDeDupe) $sSQL .= ",place_id";
1115 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1116 $sSQL .= "order by importance desc";
1117 // $sSQL .= "order by rank_search,rank_address,porder asc";
1118 if (CONST_Debug) var_dump('<hr>',$sSQL);
1119 $aSearchResults = $oDB->getAll($sSQL);
1120 //var_dump($sSQL,$aSearchResults);exit;
1122 if (PEAR::IsError($aSearchResults))
1124 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1130 $sSearchResult = '';
1131 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1133 $sSearchResult = 'No Results Found';
1135 //var_Dump($aSearchResults);
1137 $aClassType = getClassTypesWithImportance();
1138 $aRecheckWords = preg_split('/\b/',$sQuery);
1139 foreach($aRecheckWords as $i => $sWord)
1141 if (!$sWord) unset($aRecheckWords[$i]);
1143 foreach($aSearchResults as $iResNum => $aResult)
1145 if (CONST_Search_AreaPolygons)
1147 // Get the bounding box and outline polygon
1148 $sSQL = "select place_id,numfeatures,area,outline,";
1149 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1150 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1151 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1153 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1154 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1155 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1156 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1157 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1158 $aPointPolygon = $oDB->getRow($sSQL);
1159 if (PEAR::IsError($aPointPolygon))
1161 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1163 if ($aPointPolygon['place_id'])
1165 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1166 $aResult['lat'] = $aPointPolygon['centrelat'];
1167 $aResult['lon'] = $aPointPolygon['centrelon'];
1169 // Translate geometary string to point array
1170 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1172 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1174 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1177 $iSteps = ($fRadius * 40000)^2;
1178 $fStepSize = (2*pi())/$iSteps;
1179 $aPolyPoints = array();
1180 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1182 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1184 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1185 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1186 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1187 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1190 // Output data suitable for display (points and a bounding box)
1191 if ($bShowPolygons && isset($aPolyPoints))
1193 $aResult['aPolyPoints'] = array();
1194 foreach($aPolyPoints as $aPoint)
1196 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1199 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1203 if (!isset($aResult['aBoundingBox']))
1206 $fDiameter = 0.0001;
1208 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1209 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1211 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1213 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1214 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1216 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1218 $fRadius = $fDiameter / 2;
1220 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1221 $fStepSize = (2*pi())/$iSteps;
1222 $aPolyPoints = array();
1223 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1225 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1227 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1228 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1229 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1230 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1232 // Output data suitable for display (points and a bounding box)
1235 $aResult['aPolyPoints'] = array();
1236 foreach($aPolyPoints as $aPoint)
1238 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1241 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1244 // Is there an icon set for this type of result?
1245 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1246 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1248 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1251 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1252 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1254 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1257 if ($bShowAddressDetails)
1259 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1260 //var_dump($aResult['address']);
1264 // Adjust importance for the number of exact string matches in the result
1265 $aResult['importance'] = max(0.001,$aResult['importance']);
1267 $sAddress = $aResult['langaddress'];
1268 foreach($aRecheckWords as $i => $sWord)
1270 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1272 $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
1274 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1276 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1277 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1279 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1281 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1282 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1284 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1288 $aResult['importance'] = 1000000000000000;
1291 $aResult['name'] = $aResult['langaddress'];
1292 $aResult['foundorder'] = $iResNum;
1293 $aSearchResults[$iResNum] = $aResult;
1295 uasort($aSearchResults, 'byImportance');
1297 //var_dump($aSearchResults);exit;
1299 $aOSMIDDone = array();
1300 $aClassTypeNameDone = array();
1301 $aToFilter = $aSearchResults;
1302 $aSearchResults = array();
1305 foreach($aToFilter as $iResNum => $aResult)
1307 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1308 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1311 $fLat = $aResult['lat'];
1312 $fLon = $aResult['lon'];
1313 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1316 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1317 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1319 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1320 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1321 $aSearchResults[] = $aResult;
1324 // Absolute limit on number of results
1325 if (sizeof($aSearchResults) >= $iLimit) break;
1328 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1330 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1332 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1337 logEnd($oDB, $hLog, sizeof($aToFilter));
1339 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1340 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1341 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1342 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1343 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1344 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1347 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1349 $sMoreURL .= '&q='.urlencode($sQuery);
1351 if (CONST_Debug) exit;
1353 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');