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;
44 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
46 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
48 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
50 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
52 $iExcludedPlaceID = (int)$iExcludedPlaceID;
53 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
57 // Only certain ranks of feature
58 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
60 if (isset($_GET['featuretype']))
62 switch($_GET['featuretype'])
65 $iMinAddressRank = $iMaxAddressRank = 4;
68 $iMinAddressRank = $iMaxAddressRank = 8;
71 $iMinAddressRank = 14;
72 $iMaxAddressRank = 16;
76 $iMaxAddressRank = 20;
81 if (isset($_GET['countrycodes']))
83 $aCountryCodes = array();
84 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
86 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
88 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
91 $sCountryCodesSQL = join(',', $aCountryCodes);
95 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
96 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
98 $sQuery = substr($_SERVER['PATH_INFO'], 1);
100 // reverse order of '/' separated string
101 $aPhrases = explode('/', $sQuery);
102 $aPhrases = array_reverse($aPhrases);
103 $sQuery = join(', ',$aPhrases);
107 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
109 // Hack to make it handle "new york, ny" (and variants) correctly
110 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
111 if (isset($aLangPrefOrder['name:en']))
113 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
114 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
115 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
118 // If we have a view box create the SQL
119 // Small is the actual view box, Large is double (on each axis) that
120 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
121 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
123 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
124 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
126 if (isset($_GET['viewbox']) && $_GET['viewbox'])
128 $aCoOrdinates = explode(',',$_GET['viewbox']);
129 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
130 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
131 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
132 $aCoOrdinates[0] += $fHeight;
133 $aCoOrdinates[2] -= $fHeight;
134 $aCoOrdinates[1] += $fWidth;
135 $aCoOrdinates[3] -= $fWidth;
136 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
138 $bBoundingBoxSearch = false;
140 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
142 $aPoints = explode(',',$_GET['route']);
143 if (sizeof($aPoints) % 2 != 0)
145 echo "Uneven number of points";
148 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
150 foreach($aPoints as $i => $fPoint)
154 if ($i != 1) $sViewboxCentreSQL .= ",";
155 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
159 $fPrevCoord = (float)$fPoint;
162 $sViewboxCentreSQL .= ")'::geometry,4326)";
164 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
165 $sViewboxSmallSQL = $oDB->getOne($sSQL);
166 if (PEAR::isError($sViewboxSmallSQL))
168 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
170 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
172 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
173 $sViewboxLargeSQL = $oDB->getOne($sSQL);
174 if (PEAR::isError($sViewboxLargeSQL))
176 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
178 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
181 // Do we have anything that looks like a lat/lon pair?
182 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
184 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
185 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
186 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
188 $_GET['nearlat'] = $fQueryLat;
189 $_GET['nearlon'] = $fQueryLon;
190 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
193 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
195 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
196 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
197 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
199 $_GET['nearlat'] = $fQueryLat;
200 $_GET['nearlon'] = $fQueryLon;
201 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
204 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
206 $fQueryLat = $aData[2];
207 $fQueryLon = $aData[3];
208 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
210 $_GET['nearlat'] = $fQueryLat;
211 $_GET['nearlon'] = $fQueryLon;
212 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
218 // Start with a blank search
220 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
221 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
224 $sNearPointSQL = false;
225 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
227 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
228 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
229 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
230 $aSearches[0]['fRadius'] = 0.1;
233 $bSpecialTerms = false;
234 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
235 $aSpecialTerms = array();
236 foreach($aSpecialTermsRaw as $aSpecialTerm)
238 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
239 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
242 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
243 $aSpecialTerms = array();
244 foreach($aSpecialTermsRaw as $aSpecialTerm)
246 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
247 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
248 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
249 $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';
250 if (CONST_Debug) var_Dump($sSQL);
251 $aSearchWords = $oDB->getAll($sSQL);
252 $aNewSearches = array();
253 foreach($aSearches as $aSearch)
255 foreach($aSearchWords as $aSearchTerm)
257 $aNewSearch = $aSearch;
258 if ($aSearchTerm['country_code'])
260 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
261 $aNewSearches[] = $aNewSearch;
262 $bSpecialTerms = true;
264 if ($aSearchTerm['class'])
266 $aNewSearch['sClass'] = $aSearchTerm['class'];
267 $aNewSearch['sType'] = $aSearchTerm['type'];
268 $aNewSearches[] = $aNewSearch;
269 $bSpecialTerms = true;
273 $aSearches = $aNewSearches;
276 // Split query into phrases
277 // Commas are used to reduce the search space by indicating where phrases split
278 $aPhrases = explode(',',$sQuery);
280 // Convert each phrase to standard form
281 // Create a list of standard words
282 // Get all 'sets' of words
283 // Generate a complete list of all
285 foreach($aPhrases as $iPhrase => $sPhrase)
287 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
288 if (PEAR::isError($aPhrase))
290 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
291 if (CONST_Debug) var_dump($aPhrase);
294 if (trim($aPhrase['string']))
296 $aPhrases[$iPhrase] = $aPhrase;
297 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
298 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
299 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
303 unset($aPhrases[$iPhrase]);
307 // reindex phrases - we make assumptions later on
308 $aPhrases = array_values($aPhrases);
310 if (sizeof($aTokens))
313 // Check which tokens we have, get the ID numbers
314 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
315 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
317 // (mis)using search_name_count to exclude words that return too many
318 // search results. saerch_name_count is currently set to 1 by hand
319 // because there is no fast way to extract this count from a live database.
320 $sSQL .= ' and search_name_count = 0';
321 // $sSQL .= ' and (class is null or class not in (\'highway\'))';
322 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
324 if (CONST_Debug) var_Dump($sSQL);
326 $aValidTokens = array();
327 if (sizeof($aTokens))
328 $aDatabaseWords = $oDB->getAll($sSQL);
330 $aDatabaseWords = array();
331 if (PEAR::IsError($aDatabaseWords))
333 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
335 $aPossibleMainWordIDs = array();
336 foreach($aDatabaseWords as $aToken)
338 if (isset($aValidTokens[$aToken['word_token']]))
340 $aValidTokens[$aToken['word_token']][] = $aToken;
344 $aValidTokens[$aToken['word_token']] = array($aToken);
346 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
348 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
350 $aSuggestion = array();
351 $bSuggestion = false;
352 if (CONST_Suggestions_Enabled)
354 foreach($aPhrases as $iPhrase => $aPhrase)
356 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
358 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
359 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
360 $aRow = $aSuggestionWords[0];
361 if ($aRow && $aRow['word'])
363 $aSuggestion[] = $aRow['word'];
368 $aSuggestion[] = $aPhrase['string'];
373 $aSuggestion[] = $aPhrase['string'];
377 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
379 // Try and calculate GB postcodes we might be missing
380 foreach($aTokens as $sToken)
382 // Source of gb postcodes is now definitive - always use
383 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
385 if (substr($aData[1],-2,1) != ' ')
387 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
388 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
390 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
391 if ($aGBPostcodeLocation)
393 $aValidTokens[$sToken] = $aGBPostcodeLocation;
398 foreach($aTokens as $sToken)
400 // Unknown single word token with a number - assume it is a house number
401 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
403 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
407 // Any words that have failed completely?
410 // Start the search process
411 $aResultPlaceIDs = array();
414 Calculate all searches using aValidTokens i.e.
416 'Wodsworth Road, Sheffield' =>
420 0 1 (wodsworth)(road)
423 Score how good the search is so they can be ordered
425 foreach($aPhrases as $iPhrase => $sPhrase)
427 $aNewPhraseSearches = array();
429 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
431 $aWordsetSearches = $aSearches;
433 // Add all words from this wordset
434 foreach($aWordset as $sToken)
436 //echo "<br><b>$sToken</b>";
437 $aNewWordsetSearches = array();
439 foreach($aWordsetSearches as $aCurrentSearch)
442 //var_dump($aCurrentSearch);
445 // If the token is valid
446 if (isset($aValidTokens[' '.$sToken]))
448 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
450 $aSearch = $aCurrentSearch;
451 $aSearch['iSearchRank']++;
452 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
454 if ($aSearch['sCountryCode'] === false)
456 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
457 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
458 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
459 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
462 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
464 if ($aSearch['fLat'] === '')
466 $aSearch['fLat'] = $aSearchTerm['lat'];
467 $aSearch['fLon'] = $aSearchTerm['lon'];
468 $aSearch['fRadius'] = $aSearchTerm['radius'];
469 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
472 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
474 if ($aSearch['sHouseNumber'] === '')
476 $aSearch['sHouseNumber'] = $sToken;
477 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
479 // Fall back to not searching for this item (better than nothing)
480 $aSearch = $aCurrentSearch;
481 $aSearch['iSearchRank'] += 1;
482 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
486 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
488 if ($aSearch['sClass'] === '')
490 $aSearch['sOperator'] = $aSearchTerm['operator'];
491 $aSearch['sClass'] = $aSearchTerm['class'];
492 $aSearch['sType'] = $aSearchTerm['type'];
493 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
494 else $aSearch['sOperator'] = 'near'; // near = in for the moment
496 // Do we have a shortcut id?
497 if ($aSearch['sOperator'] == 'name')
499 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
500 if ($iAmenityID = $oDB->getOne($sSQL))
502 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
503 $aSearch['aName'][$iAmenityID] = $iAmenityID;
504 $aSearch['sClass'] = '';
505 $aSearch['sType'] = '';
508 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
511 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
513 if (sizeof($aSearch['aName']))
515 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
517 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
521 $aSearch['iSearchRank'] += 1000; // skip;
526 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
527 // $aSearch['iNamePhrase'] = $iPhrase;
529 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
533 if (isset($aValidTokens[$sToken]))
535 // Allow searching for a word - but at extra cost
536 foreach($aValidTokens[$sToken] as $aSearchTerm)
538 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
540 //var_Dump('<hr>',$aSearch['aName']);
542 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
544 $aSearch = $aCurrentSearch;
545 $aSearch['iSearchRank'] += 1;
546 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
547 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
550 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
552 $aSearch = $aCurrentSearch;
553 $aSearch['iSearchRank'] += 2;
554 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
555 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
556 $aSearch['iNamePhrase'] = $iPhrase;
557 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
564 // Allow skipping a word - but at EXTREAM cost
565 //$aSearch = $aCurrentSearch;
566 //$aSearch['iSearchRank']+=100;
567 //$aNewWordsetSearches[] = $aSearch;
571 usort($aNewWordsetSearches, 'bySearchRank');
572 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
574 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
576 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
577 usort($aNewPhraseSearches, 'bySearchRank');
579 $aSearchHash = array();
580 foreach($aNewPhraseSearches as $iSearch => $aSearch)
582 $sHash = serialize($aSearch);
583 if (isset($aSearchHash[$sHash]))
585 unset($aNewPhraseSearches[$iSearch]);
589 $aSearchHash[$sHash] = 1;
593 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
596 // Re-group the searches by their score, junk anything over 20 as just not worth trying
597 $aGroupedSearches = array();
598 foreach($aNewPhraseSearches as $aSearch)
600 if ($aSearch['iSearchRank'] < $iMaxRank)
602 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
603 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
606 ksort($aGroupedSearches);
609 $aSearches = array();
610 foreach($aGroupedSearches as $iScore => $aNewSearches)
612 $iSearchCount += sizeof($aNewSearches);
613 $aSearches = array_merge($aSearches, $aNewSearches);
614 if ($iSearchCount > 50) break;
617 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
623 // Re-group the searches by their score, junk anything over 20 as just not worth trying
624 $aGroupedSearches = array();
625 foreach($aSearches as $aSearch)
627 if ($aSearch['iSearchRank'] < $iMaxRank)
629 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
630 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
633 ksort($aGroupedSearches);
636 if (CONST_Debug) var_Dump($aGroupedSearches);
640 $aCopyGroupedSearches = $aGroupedSearches;
641 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
643 foreach($aSearches as $iSearch => $aSearch)
645 if (sizeof($aSearch['aAddress']))
647 $iReverseItem = array_pop($aSearch['aAddress']);
648 if (isset($aPossibleMainWordIDs[$iReverseItem]))
650 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
651 $aSearch['aName'] = array($iReverseItem);
652 $aGroupedSearches[$iGroup][] = $aSearch;
654 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
655 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
661 // Filter out duplicate searches
662 $aSearchHash = array();
663 foreach($aGroupedSearches as $iGroup => $aSearches)
665 foreach($aSearches as $iSearch => $aSearch)
667 $sHash = serialize($aSearch);
668 if (isset($aSearchHash[$sHash]))
670 unset($aGroupedSearches[$iGroup][$iSearch]);
671 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
675 $aSearchHash[$sHash] = 1;
680 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
684 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
687 foreach($aSearches as $aSearch)
691 // Must have a location term
692 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
694 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
696 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
698 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
699 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
700 $sSQL .= " order by st_area(geometry) desc limit 1";
701 $aPlaceIDs = $oDB->getCol($sSQL);
706 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
707 if (!$aSearch['sClass']) continue;
708 if (CONST_Debug) var_dump('<hr>',$aSearch);
709 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
711 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
712 if ($oDB->getOne($sSQL))
714 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
715 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
716 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
717 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
718 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
719 $sSQL .= " limit $iLimit";
720 if (CONST_Debug) var_dump($sSQL);
721 $aPlaceIDs = $oDB->getCol($sSQL);
723 if (!sizeof($aPlaceIDs))
725 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
726 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
727 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
728 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
729 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
730 $sSQL .= " limit $iLimit";
731 if (CONST_Debug) var_dump($sSQL);
732 $aPlaceIDs = $oDB->getCol($sSQL);
737 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
738 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
739 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
740 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
741 $sSQL .= " limit $iLimit";
742 if (CONST_Debug) var_dump($sSQL);
743 $aPlaceIDs = $oDB->getCol($sSQL);
749 if (CONST_Debug) var_dump('<hr>',$aSearch);
750 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
751 $aPlaceIDs = array();
753 // First we need a position, either aName or fLat or both
757 // TODO: filter out the pointless search terms (2 letter name tokens and less)
758 // they might be right - but they are just too darned expensive to run
759 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
760 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
761 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
762 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
763 if ($aSearch['fLon'] && $aSearch['fLat'])
765 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
766 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
768 if (sizeof($aExcludePlaceIDs))
770 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
772 if ($sCountryCodesSQL)
774 $aTerms[] = "country_code in ($sCountryCodesSQL)";
777 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
778 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
780 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
782 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
783 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
784 $aOrder[] = "$sImportanceSQL DESC";
788 $sSQL = "select place_id";
789 $sSQL .= " from search_name";
790 $sSQL .= " where ".join(' and ',$aTerms);
791 $sSQL .= " order by ".join(', ',$aOrder);
792 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
793 $sSQL .= " limit 50";
794 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
797 $sSQL .= " limit ".$iLimit;
799 if (CONST_Debug) var_dump($sSQL);
800 $iStartTime = time();
801 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
802 if (PEAR::IsError($aViewBoxPlaceIDs))
804 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
806 if (time() - $iStartTime > 60) {
807 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
810 //var_dump($aViewBoxPlaceIDs);
811 // Did we have an viewbox matches?
812 $aPlaceIDs = array();
813 $bViewBoxMatch = false;
814 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
816 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
817 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
818 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
819 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
820 $aPlaceIDs[] = $aViewBoxRow['place_id'];
823 //var_Dump($aPlaceIDs);
826 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
828 $aRoadPlaceIDs = $aPlaceIDs;
829 $sPlaceIDs = join(',',$aPlaceIDs);
831 // Now they are indexed look for a house attached to a street we found
832 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
833 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
834 if (sizeof($aExcludePlaceIDs))
836 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
838 $sSQL .= " limit $iLimit";
839 if (CONST_Debug) var_dump($sSQL);
840 $aPlaceIDs = $oDB->getCol($sSQL);
842 // If not try the aux fallback table
843 if (!sizeof($aPlaceIDs))
845 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
846 if (sizeof($aExcludePlaceIDs))
848 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
850 // $sSQL .= " limit $iLimit";
851 if (CONST_Debug) var_dump($sSQL);
852 $aPlaceIDs = $oDB->getCol($sSQL);
855 if (!sizeof($aPlaceIDs))
857 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
858 if (sizeof($aExcludePlaceIDs))
860 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
862 // $sSQL .= " limit $iLimit";
863 if (CONST_Debug) var_dump($sSQL);
864 $aPlaceIDs = $oDB->getCol($sSQL);
867 // Fallback to the road
868 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
870 $aPlaceIDs = $aRoadPlaceIDs;
875 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
877 $sPlaceIDs = join(',',$aPlaceIDs);
879 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
881 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
882 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
883 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
884 $sSQL .= " order by rank_search asc limit $iLimit";
885 if (CONST_Debug) var_dump($sSQL);
886 $aPlaceIDs = $oDB->getCol($sSQL);
889 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
891 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
892 $bCacheTable = $oDB->getOne($sSQL);
894 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
896 if (CONST_Debug) var_dump($sSQL);
897 $iMaxRank = ((int)$oDB->getOne($sSQL));
899 // For state / country level searches the normal radius search doesn't work very well
901 if ($iMaxRank < 9 && $bCacheTable)
903 // Try and get a polygon to search in instead
904 $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";
905 if (CONST_Debug) var_dump($sSQL);
906 $sPlaceGeom = $oDB->getOne($sSQL);
916 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
917 if (CONST_Debug) var_dump($sSQL);
918 $aPlaceIDs = $oDB->getCol($sSQL);
919 $sPlaceIDs = join(',',$aPlaceIDs);
922 if ($sPlaceIDs || $sPlaceGeom)
928 // More efficient - can make the range bigger
932 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
933 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
934 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
936 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
937 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
940 $sSQL .= ",placex as f where ";
941 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
946 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
948 if (sizeof($aExcludePlaceIDs))
950 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
952 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
953 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
954 if ($iOffset) $sSQL .= " offset $iOffset";
955 $sSQL .= " limit $iLimit";
956 if (CONST_Debug) var_dump($sSQL);
957 $aPlaceIDs = $oDB->getCol($sSQL);
961 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
964 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
965 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
967 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
968 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
969 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
970 if (sizeof($aExcludePlaceIDs))
972 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
974 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
975 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
976 if ($iOffset) $sSQL .= " offset $iOffset";
977 $sSQL .= " limit $iLimit";
978 if (CONST_Debug) var_dump($sSQL);
979 $aPlaceIDs = $oDB->getCol($sSQL);
987 if (PEAR::IsError($aPlaceIDs))
989 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
992 if (CONST_Debug) var_Dump($aPlaceIDs);
994 foreach($aPlaceIDs as $iPlaceID)
996 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
998 if ($iQueryLoop > 20) break;
1001 if (sizeof($aResultPlaceIDs)) break;
1002 if ($iGroupLoop > 4) break;
1003 if ($iQueryLoop > 30) break;
1006 // Did we find anything?
1007 if (sizeof($aResultPlaceIDs))
1009 //var_Dump($aResultPlaceIDs);exit;
1010 // Get the details for display (is this a redundant extra step?)
1011 $sPlaceIDs = join(',',$aResultPlaceIDs);
1012 $sOrderSQL = 'CASE ';
1013 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1015 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1017 $sOrderSQL .= ' ELSE 10000000 END';
1018 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1019 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1020 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1021 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1022 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1023 // $sSQL .= $sOrderSQL." as porder, ";
1024 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1025 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1026 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1027 $sSQL .= "and linked_place_id is null ";
1028 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1029 if (!$bDeDupe) $sSQL .= ",place_id";
1030 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1031 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1032 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1034 $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,";
1035 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1036 $sSQL .= "null as placename,";
1037 $sSQL .= "null as ref,";
1038 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1039 // $sSQL .= $sOrderSQL." as porder, ";
1040 $sSQL .= "-0.15 as importance ";
1041 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1042 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1043 $sSQL .= "group by place_id";
1044 if (!$bDeDupe) $sSQL .= ",place_id";
1046 $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,";
1047 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1048 $sSQL .= "null as placename,";
1049 $sSQL .= "null as ref,";
1050 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1051 // $sSQL .= $sOrderSQL." as porder, ";
1052 $sSQL .= "-0.10 as importance ";
1053 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1054 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1055 $sSQL .= "group by place_id";
1056 if (!$bDeDupe) $sSQL .= ",place_id";
1057 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1058 $sSQL .= "order by importance desc";
1059 // $sSQL .= "order by rank_search,rank_address,porder asc";
1060 if (CONST_Debug) var_dump('<hr>',$sSQL);
1061 $aSearchResults = $oDB->getAll($sSQL);
1062 //var_dump($sSQL,$aSearchResults);exit;
1064 if (PEAR::IsError($aSearchResults))
1066 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1069 } // end if ($sQuery)
1072 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1074 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1075 $aResultPlaceIDs = array($iPlaceID);
1077 // TODO: this needs refactoring!
1079 // Get the details for display (is this a redundant extra step?)
1080 $sPlaceIDs = join(',',$aResultPlaceIDs);
1081 $sOrderSQL = 'CASE ';
1082 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1084 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1086 $sOrderSQL .= ' ELSE 10000000 END';
1087 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1088 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1089 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1090 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1091 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1092 // $sSQL .= $sOrderSQL." as porder, ";
1093 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1094 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1095 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1096 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1097 if (!$bDeDupe) $sSQL .= ",place_id";
1098 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1099 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1100 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1102 $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,";
1103 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1104 $sSQL .= "null as placename,";
1105 $sSQL .= "null as ref,";
1106 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1107 // $sSQL .= $sOrderSQL." as porder, ";
1108 $sSQL .= "-0.15 as importance ";
1109 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1110 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1111 $sSQL .= "group by place_id";
1112 if (!$bDeDupe) $sSQL .= ",place_id";
1114 $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,";
1115 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1116 $sSQL .= "null as placename,";
1117 $sSQL .= "null as ref,";
1118 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1119 // $sSQL .= $sOrderSQL." as porder, ";
1120 $sSQL .= "-0.10 as importance ";
1121 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1122 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1123 $sSQL .= "group by place_id";
1124 if (!$bDeDupe) $sSQL .= ",place_id";
1125 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1126 $sSQL .= "order by importance desc";
1127 // $sSQL .= "order by rank_search,rank_address,porder asc";
1128 if (CONST_Debug) var_dump('<hr>',$sSQL);
1129 $aSearchResults = $oDB->getAll($sSQL);
1130 //var_dump($sSQL,$aSearchResults);exit;
1132 if (PEAR::IsError($aSearchResults))
1134 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1140 $sSearchResult = '';
1141 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1143 $sSearchResult = 'No Results Found';
1145 //var_Dump($aSearchResults);
1147 $aClassType = getClassTypesWithImportance();
1148 $aRecheckWords = preg_split('/\b/',$sQuery);
1149 foreach($aRecheckWords as $i => $sWord)
1151 if (!$sWord) unset($aRecheckWords[$i]);
1153 foreach($aSearchResults as $iResNum => $aResult)
1155 if (CONST_Search_AreaPolygons)
1157 // Get the bounding box and outline polygon
1158 $sSQL = "select place_id,numfeatures,area,outline,";
1159 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1160 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1161 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1163 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1164 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1165 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1166 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1167 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1168 $aPointPolygon = $oDB->getRow($sSQL);
1169 if (PEAR::IsError($aPointPolygon))
1171 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1173 if ($aPointPolygon['place_id'])
1175 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1176 $aResult['lat'] = $aPointPolygon['centrelat'];
1177 $aResult['lon'] = $aPointPolygon['centrelon'];
1179 // Translate geometary string to point array
1180 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1182 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1184 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1187 $iSteps = ($fRadius * 40000)^2;
1188 $fStepSize = (2*pi())/$iSteps;
1189 $aPolyPoints = array();
1190 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1192 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1194 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1195 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1196 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1197 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1200 // Output data suitable for display (points and a bounding box)
1201 if ($bShowPolygons && isset($aPolyPoints))
1203 $aResult['aPolyPoints'] = array();
1204 foreach($aPolyPoints as $aPoint)
1206 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1209 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1213 if (!isset($aResult['aBoundingBox']))
1216 $fDiameter = 0.0001;
1218 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1219 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1221 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1223 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1224 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1226 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1228 $fRadius = $fDiameter / 2;
1230 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1231 $fStepSize = (2*pi())/$iSteps;
1232 $aPolyPoints = array();
1233 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1235 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1237 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1238 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1239 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1240 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1242 // Output data suitable for display (points and a bounding box)
1245 $aResult['aPolyPoints'] = array();
1246 foreach($aPolyPoints as $aPoint)
1248 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1251 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1254 // Is there an icon set for this type of result?
1255 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1256 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1258 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1261 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1262 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1264 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1267 if ($bShowAddressDetails)
1269 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1270 //var_dump($aResult['address']);
1274 // Adjust importance for the number of exact string matches in the result
1275 $aResult['importance'] = max(0.001,$aResult['importance']);
1277 $sAddress = $aResult['langaddress'];
1278 foreach($aRecheckWords as $i => $sWord)
1280 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1282 $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
1284 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1286 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1287 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1289 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1291 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1292 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1294 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1298 $aResult['importance'] = 1000000000000000;
1301 $aResult['name'] = $aResult['langaddress'];
1302 $aResult['foundorder'] = $iResNum;
1303 $aSearchResults[$iResNum] = $aResult;
1305 uasort($aSearchResults, 'byImportance');
1307 //var_dump($aSearchResults);exit;
1309 $aOSMIDDone = array();
1310 $aClassTypeNameDone = array();
1311 $aToFilter = $aSearchResults;
1312 $aSearchResults = array();
1315 foreach($aToFilter as $iResNum => $aResult)
1317 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1318 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1321 $fLat = $aResult['lat'];
1322 $fLon = $aResult['lon'];
1323 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1326 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1327 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1329 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1330 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1331 $aSearchResults[] = $aResult;
1334 // Absolute limit on number of results
1335 if (sizeof($aSearchResults) >= $iLimit) break;
1338 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1340 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1342 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1347 logEnd($oDB, $hLog, sizeof($aToFilter));
1349 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1350 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1351 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1352 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1353 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1354 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1357 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1359 $sMoreURL .= '&q='.urlencode($sQuery);
1361 if (CONST_Debug) exit;
1363 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');