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 = getPrefferedLangauges();
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 && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
97 $sQuery = substr($_SERVER['PATH_INFO'], 1);
99 // reverse order of '/' seperated string
100 $aPhrases = explode('/', $sQuery);
101 $aPhrases = array_reverse($aPhrases);
102 $sQuery = join(', ',$aPhrases);
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('/\\bil\\b/','illinois', $sQuery);
114 $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
115 $sQuery = preg_replace('/\\bla\\b/','louisiana', $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 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
140 $aPoints = explode(',',$_GET['route']);
141 if (sizeof($aPoints) % 2 != 0)
143 echo "Uneven number of points";
146 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
148 foreach($aPoints as $i => $fPoint)
152 if ($i != 1) $sViewboxCentreSQL .= ",";
153 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
157 $fPrevCoord = (float)$fPoint;
160 $sViewboxCentreSQL .= ")'::geometry,4326)";
162 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
163 $sViewboxSmallSQL = $oDB->getOne($sSQL);
164 if (PEAR::isError($sViewboxSmallSQL))
166 var_dump($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 var_dump($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 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
185 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
186 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
188 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
190 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
191 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
192 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
194 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b)/', $sQuery, $aData))
196 $_GET['nearlat'] = $aData[2];
197 $_GET['nearlon'] = $aData[3];
198 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
203 // Start with a blank search
205 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
206 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
209 $sNearPointSQL = false;
210 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
212 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
213 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
214 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
215 $aSearches[0]['fRadius'] = 0.1;
218 $bSpecialTerms = false;
219 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
220 $aSpecialTerms = array();
221 foreach($aSpecialTermsRaw as $aSpecialTerm)
223 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
224 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
227 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
228 $aSpecialTerms = array();
229 foreach($aSpecialTermsRaw as $aSpecialTerm)
231 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
232 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
233 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
234 $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';
235 $aSearchWords = $oDB->getAll($sSQL);
236 $aNewSearches = array();
237 foreach($aSearches as $aSearch)
239 foreach($aSearchWords as $aSearchTerm)
241 $aNewSearch = $aSearch;
242 if ($aSearchTerm['country_code'])
244 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
245 $aNewSearches[] = $aNewSearch;
246 $bSpecialTerms = true;
248 if ($aSearchTerm['class'])
250 $aNewSearch['sClass'] = $aSearchTerm['class'];
251 $aNewSearch['sType'] = $aSearchTerm['type'];
252 $aNewSearches[] = $aNewSearch;
253 $bSpecialTerms = true;
257 $aSearches = $aNewSearches;
260 // Split query into phrases
261 // Commas are used to reduce the search space by indicating where phrases split
262 $aPhrases = explode(',',$sQuery);
264 // Convert each phrase to standard form
265 // Create a list of standard words
266 // Get all 'sets' of words
267 // Generate a complete list of all
269 foreach($aPhrases as $iPhrase => $sPhrase)
271 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
272 if (PEAR::isError($aPhrase))
277 if (trim($aPhrase['string']))
279 $aPhrases[$iPhrase] = $aPhrase;
280 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
281 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
282 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
286 unset($aPhrases[$iPhrase]);
290 // reindex phrases - we make assumptions later on
291 $aPhrases = array_values($aPhrases);
293 if (sizeof($aTokens))
296 // Check which tokens we have, get the ID numbers
297 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
298 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
299 $sSQL .= ' and (class is null or class not in (\'highway\'))';
300 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
302 if (CONST_Debug) var_Dump($sSQL);
304 $aValidTokens = array();
305 if (sizeof($aTokens))
306 $aDatabaseWords = $oDB->getAll($sSQL);
308 $aDatabaseWords = array();
309 if (PEAR::IsError($aDatabaseWords))
311 var_dump($sSQL, $aDatabaseWords);
314 $aPossibleMainWordIDs = array();
315 foreach($aDatabaseWords as $aToken)
317 if (isset($aValidTokens[$aToken['word_token']]))
319 $aValidTokens[$aToken['word_token']][] = $aToken;
323 $aValidTokens[$aToken['word_token']] = array($aToken);
325 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
327 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
329 $aSuggestion = array();
330 $bSuggestion = false;
331 if (CONST_Suggestions_Enabled)
333 foreach($aPhrases as $iPhrase => $aPhrase)
335 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
337 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
338 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
339 $aRow = $aSuggestionWords[0];
340 if ($aRow && $aRow['word'])
342 $aSuggestion[] = $aRow['word'];
347 $aSuggestion[] = $aPhrase['string'];
352 $aSuggestion[] = $aPhrase['string'];
356 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
358 // Try and calculate GB postcodes we might be missing
359 foreach($aTokens as $sToken)
361 if (!isset($aValidTokens[$sToken]) && !isset($aValidTokens[' '.$sToken]) && preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
363 if (substr($aData[1],-2,1) != ' ')
365 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
366 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
368 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
369 if ($aGBPostcodeLocation)
371 $aValidTokens[$sToken] = $aGBPostcodeLocation;
377 foreach($aTokens as $sToken)
379 // Unknown single word token with a number - assume it is a house number
380 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
382 $aValidTokens[' '.$sToken] = array('class'=>'place','type'=>'house');
386 // Any words that have failed completely?
389 // Start the search process
390 $aResultPlaceIDs = array();
393 Calculate all searches using aValidTokens i.e.
395 'Wodsworth Road, Sheffield' =>
399 0 1 (wodsworth)(road)
402 Score how good the search is so they can be ordered
405 foreach($aPhrases as $iPhrase => $sPhrase)
407 $aNewPhraseSearches = array();
409 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
411 $aWordsetSearches = $aSearches;
413 // Add all words from this wordset
414 foreach($aWordset as $sToken)
416 //echo "<br><b>$sToken</b>";
417 $aNewWordsetSearches = array();
419 foreach($aWordsetSearches as $aCurrentSearch)
422 //var_dump($aCurrentSearch);
425 // If the token is valid
426 if (isset($aValidTokens[' '.$sToken]))
428 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
430 $aSearch = $aCurrentSearch;
431 $aSearch['iSearchRank']++;
432 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
434 if ($aSearch['sCountryCode'] === false)
436 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
437 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
438 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
439 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
442 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
444 if ($aSearch['fLat'] === '')
446 $aSearch['fLat'] = $aSearchTerm['lat'];
447 $aSearch['fLon'] = $aSearchTerm['lon'];
448 $aSearch['fRadius'] = $aSearchTerm['radius'];
449 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
452 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
454 if ($aSearch['sHouseNumber'] === '')
456 $aSearch['sHouseNumber'] = $sToken;
457 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
459 // Fall back to not searching for this item (better than nothing)
460 $aSearch = $aCurrentSearch;
461 $aSearch['iSearchRank'] += 1;
462 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
466 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
468 if ($aSearch['sClass'] === '')
470 $aSearch['sOperator'] = $aSearchTerm['operator'];
471 $aSearch['sClass'] = $aSearchTerm['class'];
472 $aSearch['sType'] = $aSearchTerm['type'];
473 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
474 else $aSearch['sOperator'] = 'near'; // near = in for the moment
476 // Do we have a shortcut id?
477 if ($aSearch['sOperator'] == 'name')
479 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
480 if ($iAmenityID = $oDB->getOne($sSQL))
482 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
483 $aSearch['aName'][$iAmenityID] = $iAmenityID;
484 $aSearch['sClass'] = '';
485 $aSearch['sType'] = '';
488 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
493 if (sizeof($aSearch['aName']))
495 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
497 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
501 $aSearch['iSearchRank'] += 1000; // skip;
506 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
507 // $aSearch['iNamePhrase'] = $iPhrase;
509 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
513 if (isset($aValidTokens[$sToken]))
515 // Allow searching for a word - but at extra cost
516 foreach($aValidTokens[$sToken] as $aSearchTerm)
518 //var_Dump('<hr>',$aSearch['aName']);
520 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
522 $aSearch = $aCurrentSearch;
523 $aSearch['iSearchRank'] += 1;
524 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
525 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
528 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
530 $aSearch = $aCurrentSearch;
531 $aSearch['iSearchRank'] += 2;
532 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
533 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
534 $aSearch['iNamePhrase'] = $iPhrase;
535 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
541 // Allow skipping a word - but at EXTREAM cost
542 //$aSearch = $aCurrentSearch;
543 //$aSearch['iSearchRank']+=100;
544 //$aNewWordsetSearches[] = $aSearch;
548 usort($aNewWordsetSearches, 'bySearchRank');
549 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
551 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
553 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
554 usort($aNewPhraseSearches, 'bySearchRank');
556 $aSearchHash = array();
557 foreach($aNewPhraseSearches as $iSearch => $aSearch)
559 $sHash = serialize($aSearch);
560 if (isset($aSearchHash[$sHash]))
562 unset($aNewPhraseSearches[$iSearch]);
566 $aSearchHash[$sHash] = 1;
570 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
573 // Re-group the searches by their score, junk anything over 20 as just not worth trying
574 $aGroupedSearches = array();
575 foreach($aNewPhraseSearches as $aSearch)
577 if ($aSearch['iSearchRank'] < $iMaxRank)
579 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
580 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
583 ksort($aGroupedSearches);
586 $aSearches = array();
587 foreach($aGroupedSearches as $iScore => $aNewSearches)
589 $iSearchCount += sizeof($aNewSearches);
590 $aSearches = array_merge($aSearches, $aNewSearches);
591 if ($iSearchCount > 50) break;
594 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
600 // Re-group the searches by their score, junk anything over 20 as just not worth trying
601 $aGroupedSearches = array();
602 foreach($aSearches as $aSearch)
604 if ($aSearch['iSearchRank'] < $iMaxRank)
606 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
607 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
610 ksort($aGroupedSearches);
613 if (CONST_Debug) var_Dump($aGroupedSearches);
617 $aCopyGroupedSearches = $aGroupedSearches;
618 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
620 foreach($aSearches as $iSearch => $aSearch)
622 if (sizeof($aSearch['aAddress']))
624 $iReverseItem = array_pop($aSearch['aAddress']);
625 if (isset($aPossibleMainWordIDs[$iReverseItem]))
627 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
628 $aSearch['aName'] = array($iReverseItem);
629 $aGroupedSearches[$iGroup][] = $aSearch;
631 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
632 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
638 // Filter out duplicate searches
639 $aSearchHash = array();
640 foreach($aGroupedSearches as $iGroup => $aSearches)
642 foreach($aSearches as $iSearch => $aSearch)
644 $sHash = serialize($aSearch);
645 if (isset($aSearchHash[$sHash]))
647 unset($aGroupedSearches[$iGroup][$iSearch]);
648 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
652 $aSearchHash[$sHash] = 1;
657 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
661 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
664 foreach($aSearches as $aSearch)
668 // Must have a location term
669 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
671 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
673 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
675 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
676 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
677 $sSQL .= " order by st_area(geometry) desc limit 1";
678 $aPlaceIDs = $oDB->getCol($sSQL);
683 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
684 if (!$aSearch['sClass']) continue;
685 if (CONST_Debug) var_dump('<hr>',$aSearch);
686 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
688 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
689 if ($oDB->getOne($sSQL))
691 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
692 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
693 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
694 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
695 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
696 $sSQL .= " limit $iLimit";
697 if (CONST_Debug) var_dump($sSQL);
698 $aPlaceIDs = $oDB->getCol($sSQL);
700 if (!sizeof($aPlaceIDs))
702 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
703 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
704 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
705 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
706 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
707 $sSQL .= " limit $iLimit";
708 if (CONST_Debug) var_dump($sSQL);
709 $aPlaceIDs = $oDB->getCol($sSQL);
714 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
715 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
716 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
717 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
718 $sSQL .= " limit $iLimit";
719 if (CONST_Debug) var_dump($sSQL);
720 $aPlaceIDs = $oDB->getCol($sSQL);
726 if (CONST_Debug) var_dump('<hr>',$aSearch);
727 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
728 $aPlaceIDs = array();
730 // First we need a position, either aName or fLat or both
733 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
734 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
735 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
736 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
737 if ($aSearch['fLon'] && $aSearch['fLat'])
739 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
740 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
742 if (sizeof($aExcludePlaceIDs))
744 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
746 if ($sCountryCodesSQL)
748 $aTerms[] = "country_code in ($sCountryCodesSQL)";
751 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
752 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
754 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
756 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
757 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
758 $aOrder[] = "$sImportanceSQL DESC";
762 $sSQL = "select place_id";
763 $sSQL .= " from search_name";
764 $sSQL .= " where ".join(' and ',$aTerms);
765 $sSQL .= " order by ".join(', ',$aOrder);
766 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
767 $sSQL .= " limit 50";
768 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
771 $sSQL .= " limit ".$iLimit;
773 if (CONST_Debug) var_dump($sSQL);
774 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
775 if (PEAR::IsError($aViewBoxPlaceIDs))
777 var_dump($sSQL, $aViewBoxPlaceIDs);
780 //var_dump($aViewBoxPlaceIDs);
781 // Did we have an viewbox matches?
782 $aPlaceIDs = array();
783 $bViewBoxMatch = false;
784 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
786 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
787 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
788 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
789 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
790 $aPlaceIDs[] = $aViewBoxRow['place_id'];
793 //var_Dump($aPlaceIDs);
796 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
798 $aRoadPlaceIDs = $aPlaceIDs;
799 $sPlaceIDs = join(',',$aPlaceIDs);
801 // Now they are indexed look for a house attached to a street we found
802 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
803 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
804 if (sizeof($aExcludePlaceIDs))
806 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
808 $sSQL .= " limit $iLimit";
809 if (CONST_Debug) var_dump($sSQL);
810 $aPlaceIDs = $oDB->getCol($sSQL);
812 // If not try the aux fallback table
813 if (!sizeof($aPlaceIDs))
815 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
816 if (sizeof($aExcludePlaceIDs))
818 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
820 // $sSQL .= " limit $iLimit";
821 if (CONST_Debug) var_dump($sSQL);
822 $aPlaceIDs = $oDB->getCol($sSQL);
825 if (!sizeof($aPlaceIDs))
827 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
828 if (sizeof($aExcludePlaceIDs))
830 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
832 // $sSQL .= " limit $iLimit";
833 if (CONST_Debug) var_dump($sSQL);
834 $aPlaceIDs = $oDB->getCol($sSQL);
837 // Fallback to the road
838 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
840 $aPlaceIDs = $aRoadPlaceIDs;
845 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
847 $sPlaceIDs = join(',',$aPlaceIDs);
849 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
851 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
852 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
853 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
854 $sSQL .= " order by rank_search asc limit $iLimit";
855 if (CONST_Debug) var_dump($sSQL);
856 $aPlaceIDs = $oDB->getCol($sSQL);
859 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
861 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
862 $bCacheTable = $oDB->getOne($sSQL);
864 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
866 if (CONST_Debug) var_dump($sSQL);
867 $iMaxRank = ((int)$oDB->getOne($sSQL));
869 // For state / country level searches the normal radius search doesn't work very well
871 if ($iMaxRank < 9 && $bCacheTable)
873 // Try and get a polygon to search in instead
874 $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";
875 if (CONST_Debug) var_dump($sSQL);
876 $sPlaceGeom = $oDB->getOne($sSQL);
886 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
887 if (CONST_Debug) var_dump($sSQL);
888 $aPlaceIDs = $oDB->getCol($sSQL);
889 $sPlaceIDs = join(',',$aPlaceIDs);
892 if ($sPlaceIDs || $sPlaceGeom)
898 // More efficient - can make the range bigger
901 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
902 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
905 $sSQL .= ",placex as f where ";
906 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
911 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
913 if (sizeof($aExcludePlaceIDs))
915 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
917 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
918 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.centroid) ASC";
919 else if ($sPlaceIDs) $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
920 else if ($sPlaceGeom) $sSQL .= " order by ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid) asc";
922 $sSQL .= " limit $iLimit";
923 if (CONST_Debug) var_dump($sSQL);
924 $aPlaceIDs = $oDB->getCol($sSQL);
928 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
929 $sSQL = "select l.place_id from placex as l,placex as f where ";
930 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
931 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
932 if (sizeof($aExcludePlaceIDs))
934 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
936 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
937 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
938 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
939 $sSQL .= " limit $iLimit";
940 if (CONST_Debug) var_dump($sSQL);
941 $aPlaceIDs = $oDB->getCol($sSQL);
949 if (PEAR::IsError($aPlaceIDs))
951 var_dump($sSQL, $aPlaceIDs);
955 if (CONST_Debug) var_Dump($aPlaceIDs);
957 foreach($aPlaceIDs as $iPlaceID)
959 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
961 if ($iQueryLoop > 20) break;
964 if (sizeof($aResultPlaceIDs)) break;
965 if ($iGroupLoop > 4) break;
966 if ($iQueryLoop > 30) break;
969 // Did we find anything?
970 if (sizeof($aResultPlaceIDs))
972 //var_Dump($aResultPlaceIDs);exit;
973 // Get the details for display (is this a redundant extra step?)
974 $sPlaceIDs = join(',',$aResultPlaceIDs);
975 $sOrderSQL = 'CASE ';
976 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
978 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
980 $sOrderSQL .= ' ELSE 10000000 END';
981 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
982 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
983 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
984 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
985 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
986 // $sSQL .= $sOrderSQL." as porder, ";
987 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
988 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
989 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
990 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
991 if (!$bDeDupe) $sSQL .= ",place_id";
992 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
993 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
994 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
996 $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,";
997 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
998 $sSQL .= "null as placename,";
999 $sSQL .= "null as ref,";
1000 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1001 // $sSQL .= $sOrderSQL." as porder, ";
1002 $sSQL .= "-0.15 as importance ";
1003 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1004 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1005 $sSQL .= "group by place_id";
1006 if (!$bDeDupe) $sSQL .= ",place_id";
1008 $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,";
1009 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1010 $sSQL .= "null as placename,";
1011 $sSQL .= "null as ref,";
1012 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1013 // $sSQL .= $sOrderSQL." as porder, ";
1014 $sSQL .= "-0.10 as importance ";
1015 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1016 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1017 $sSQL .= "group by place_id";
1018 if (!$bDeDupe) $sSQL .= ",place_id";
1019 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1020 $sSQL .= "order by importance desc";
1021 // $sSQL .= "order by rank_search,rank_address,porder asc";
1022 if (CONST_Debug) var_dump('<hr>',$sSQL);
1023 $aSearchResults = $oDB->getAll($sSQL);
1024 //var_dump($sSQL,$aSearchResults);exit;
1026 if (PEAR::IsError($aSearchResults))
1028 var_dump($sSQL, $aSearchResults);
1032 } // end if ($sQuery)
1035 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1037 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1038 $aResultPlaceIDs = array($iPlaceID);
1040 // TODO: this needs refactoring!
1042 // Get the details for display (is this a redundant extra step?)
1043 $sPlaceIDs = join(',',$aResultPlaceIDs);
1044 $sOrderSQL = 'CASE ';
1045 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1047 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1049 $sOrderSQL .= ' ELSE 10000000 END';
1050 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1051 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1052 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1053 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1054 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1055 // $sSQL .= $sOrderSQL." as porder, ";
1056 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1057 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1058 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1059 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1060 if (!$bDeDupe) $sSQL .= ",place_id";
1061 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1062 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1063 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1065 $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,";
1066 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1067 $sSQL .= "null as placename,";
1068 $sSQL .= "null as ref,";
1069 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1070 // $sSQL .= $sOrderSQL." as porder, ";
1071 $sSQL .= "-0.15 as importance ";
1072 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1073 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1074 $sSQL .= "group by place_id";
1075 if (!$bDeDupe) $sSQL .= ",place_id";
1077 $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,";
1078 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1079 $sSQL .= "null as placename,";
1080 $sSQL .= "null as ref,";
1081 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1082 // $sSQL .= $sOrderSQL." as porder, ";
1083 $sSQL .= "-0.10 as importance ";
1084 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1085 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1086 $sSQL .= "group by place_id";
1087 if (!$bDeDupe) $sSQL .= ",place_id";
1088 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1089 $sSQL .= "order by importance desc";
1090 // $sSQL .= "order by rank_search,rank_address,porder asc";
1091 if (CONST_Debug) var_dump('<hr>',$sSQL);
1092 $aSearchResults = $oDB->getAll($sSQL);
1093 //var_dump($sSQL,$aSearchResults);exit;
1095 if (PEAR::IsError($aSearchResults))
1097 var_dump($sSQL, $aSearchResults);
1104 $sSearchResult = '';
1105 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1107 $sSearchResult = 'No Results Found';
1109 //var_Dump($aSearchResults);
1111 $aClassType = getClassTypesWithImportance();
1112 foreach($aSearchResults as $iResNum => $aResult)
1114 if (CONST_Search_AreaPolygons || true)
1116 // Get the bounding box and outline polygon
1117 $sSQL = "select place_id,numfeatures,area,outline,";
1118 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1119 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1120 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1122 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1123 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1124 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1125 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1126 $aPointPolygon = $oDB->getRow($sSQL);
1127 if (PEAR::IsError($aPointPolygon))
1129 var_dump($sSQL, $aPointPolygon);
1132 if ($aPointPolygon['place_id'])
1134 // Translate geometary string to point array
1135 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1137 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1139 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1142 $iSteps = ($fRadius * 40000)^2;
1143 $fStepSize = (2*pi())/$iSteps;
1144 $aPolyPoints = array();
1145 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1147 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1149 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1150 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1151 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1152 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1155 // Output data suitable for display (points and a bounding box)
1158 $aResult['aPolyPoints'] = array();
1159 foreach($aPolyPoints as $aPoint)
1161 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1164 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1168 if (!isset($aResult['aBoundingBox']))
1171 $fDiameter = 0.0001;
1173 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1174 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1176 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1178 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1179 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1181 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1183 $fRadius = $fDiameter / 2;
1185 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1186 $fStepSize = (2*pi())/$iSteps;
1187 $aPolyPoints = array();
1188 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1190 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1192 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1193 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1194 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1195 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1197 // Output data suitable for display (points and a bounding box)
1200 $aResult['aPolyPoints'] = array();
1201 foreach($aPolyPoints as $aPoint)
1203 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1206 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1209 // Is there an icon set for this type of result?
1210 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1211 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1213 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1216 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1217 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1219 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1222 if ($bShowAddressDetails)
1224 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1225 //var_dump($aResult['address']);
1229 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1231 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1232 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1234 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1236 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1237 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1239 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1243 $aResult['importance'] = 1000000000000000;
1246 $aResult['name'] = $aResult['langaddress'];
1247 $aResult['foundorder'] = $iResNum;
1248 $aSearchResults[$iResNum] = $aResult;
1251 uasort($aSearchResults, 'byImportance');
1253 //var_dump($aSearchResults);exit;
1255 $aOSMIDDone = array();
1256 $aClassTypeNameDone = array();
1257 $aToFilter = $aSearchResults;
1258 $aSearchResults = array();
1261 foreach($aToFilter as $iResNum => $aResult)
1263 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1264 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1267 $fLat = $aResult['lat'];
1268 $fLon = $aResult['lon'];
1269 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1272 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1273 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1275 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1276 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1277 $aSearchResults[] = $aResult;
1280 // Absolute limit on number of results
1281 if (sizeof($aSearchResults) >= $iLimit) break;
1284 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1286 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1288 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1293 logEnd($oDB, $hLog, sizeof($aToFilter));
1295 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1296 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1297 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1298 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1299 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1300 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1303 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1305 $sMoreURL .= '&q='.urlencode($sQuery);
1307 if (CONST_Debug) exit;
1309 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');