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);
106 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
108 // Hack to make it handle "new york, ny" (and variants) correctly
109 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
110 if (isset($aLangPrefOrder['name:en']))
112 $sQuery = preg_replace('/\\bil\\b/','illinois', $sQuery);
113 $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
114 $sQuery = preg_replace('/\\bla\\b/','louisiana', $sQuery);
115 $sQuery = preg_replace('/\\bde louisiana\\b/','de la', $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))
274 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
275 if (CONST_Debug) var_dump($aPhrase);
278 if (trim($aPhrase['string']))
280 $aPhrases[$iPhrase] = $aPhrase;
281 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
282 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
283 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
287 unset($aPhrases[$iPhrase]);
291 // reindex phrases - we make assumptions later on
292 $aPhrases = array_values($aPhrases);
294 if (sizeof($aTokens))
297 // Check which tokens we have, get the ID numbers
298 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
299 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
300 $sSQL .= ' and (class is null or class not in (\'highway\'))';
301 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
303 if (CONST_Debug) var_Dump($sSQL);
305 $aValidTokens = array();
306 if (sizeof($aTokens))
307 $aDatabaseWords = $oDB->getAll($sSQL);
309 $aDatabaseWords = array();
310 if (PEAR::IsError($aDatabaseWords))
312 var_dump($sSQL, $aDatabaseWords);
315 $aPossibleMainWordIDs = array();
316 foreach($aDatabaseWords as $aToken)
318 if (isset($aValidTokens[$aToken['word_token']]))
320 $aValidTokens[$aToken['word_token']][] = $aToken;
324 $aValidTokens[$aToken['word_token']] = array($aToken);
326 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
328 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
330 $aSuggestion = array();
331 $bSuggestion = false;
332 if (CONST_Suggestions_Enabled)
334 foreach($aPhrases as $iPhrase => $aPhrase)
336 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
338 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
339 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
340 $aRow = $aSuggestionWords[0];
341 if ($aRow && $aRow['word'])
343 $aSuggestion[] = $aRow['word'];
348 $aSuggestion[] = $aPhrase['string'];
353 $aSuggestion[] = $aPhrase['string'];
357 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
359 // Try and calculate GB postcodes we might be missing
360 foreach($aTokens as $sToken)
362 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))
364 if (substr($aData[1],-2,1) != ' ')
366 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
367 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
369 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
370 if ($aGBPostcodeLocation)
372 $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
902 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
903 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
904 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
906 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
907 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
910 $sSQL .= ",placex as f where ";
911 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
916 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
918 if (sizeof($aExcludePlaceIDs))
920 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
922 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
923 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
924 if ($iOffset) $sSQL .= " offset $iOffset";
925 $sSQL .= " limit $iLimit";
926 if (CONST_Debug) var_dump($sSQL);
927 $aPlaceIDs = $oDB->getCol($sSQL);
931 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
934 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
935 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
937 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
938 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
939 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
940 if (sizeof($aExcludePlaceIDs))
942 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
944 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
945 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
946 if ($iOffset) $sSQL .= " offset $iOffset";
947 $sSQL .= " limit $iLimit";
948 if (CONST_Debug) var_dump($sSQL);
949 $aPlaceIDs = $oDB->getCol($sSQL);
957 if (PEAR::IsError($aPlaceIDs))
959 var_dump($sSQL, $aPlaceIDs);
963 if (CONST_Debug) var_Dump($aPlaceIDs);
965 foreach($aPlaceIDs as $iPlaceID)
967 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
969 if ($iQueryLoop > 20) break;
972 if (sizeof($aResultPlaceIDs)) break;
973 if ($iGroupLoop > 4) break;
974 if ($iQueryLoop > 30) break;
977 // Did we find anything?
978 if (sizeof($aResultPlaceIDs))
980 //var_Dump($aResultPlaceIDs);exit;
981 // Get the details for display (is this a redundant extra step?)
982 $sPlaceIDs = join(',',$aResultPlaceIDs);
983 $sOrderSQL = 'CASE ';
984 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
986 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
988 $sOrderSQL .= ' ELSE 10000000 END';
989 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
990 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
991 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
992 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
993 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
994 // $sSQL .= $sOrderSQL." as porder, ";
995 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
996 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
997 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
998 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
999 if (!$bDeDupe) $sSQL .= ",place_id";
1000 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1001 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1002 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1004 $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,";
1005 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1006 $sSQL .= "null as placename,";
1007 $sSQL .= "null as ref,";
1008 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1009 // $sSQL .= $sOrderSQL." as porder, ";
1010 $sSQL .= "-0.15 as importance ";
1011 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1012 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1013 $sSQL .= "group by place_id";
1014 if (!$bDeDupe) $sSQL .= ",place_id";
1016 $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,";
1017 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1018 $sSQL .= "null as placename,";
1019 $sSQL .= "null as ref,";
1020 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1021 // $sSQL .= $sOrderSQL." as porder, ";
1022 $sSQL .= "-0.10 as importance ";
1023 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1024 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1025 $sSQL .= "group by place_id";
1026 if (!$bDeDupe) $sSQL .= ",place_id";
1027 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1028 $sSQL .= "order by importance desc";
1029 // $sSQL .= "order by rank_search,rank_address,porder asc";
1030 if (CONST_Debug) var_dump('<hr>',$sSQL);
1031 $aSearchResults = $oDB->getAll($sSQL);
1032 //var_dump($sSQL,$aSearchResults);exit;
1034 if (PEAR::IsError($aSearchResults))
1036 var_dump($sSQL, $aSearchResults);
1040 } // end if ($sQuery)
1043 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1045 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1046 $aResultPlaceIDs = array($iPlaceID);
1048 // TODO: this needs refactoring!
1050 // Get the details for display (is this a redundant extra step?)
1051 $sPlaceIDs = join(',',$aResultPlaceIDs);
1052 $sOrderSQL = 'CASE ';
1053 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1055 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1057 $sOrderSQL .= ' ELSE 10000000 END';
1058 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1059 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1060 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1061 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1062 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1063 // $sSQL .= $sOrderSQL." as porder, ";
1064 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1065 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1066 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1067 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1068 if (!$bDeDupe) $sSQL .= ",place_id";
1069 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1070 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1071 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1073 $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,";
1074 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1075 $sSQL .= "null as placename,";
1076 $sSQL .= "null as ref,";
1077 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1078 // $sSQL .= $sOrderSQL." as porder, ";
1079 $sSQL .= "-0.15 as importance ";
1080 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1081 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1082 $sSQL .= "group by place_id";
1083 if (!$bDeDupe) $sSQL .= ",place_id";
1085 $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,";
1086 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1087 $sSQL .= "null as placename,";
1088 $sSQL .= "null as ref,";
1089 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1090 // $sSQL .= $sOrderSQL." as porder, ";
1091 $sSQL .= "-0.10 as importance ";
1092 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1093 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1094 $sSQL .= "group by place_id";
1095 if (!$bDeDupe) $sSQL .= ",place_id";
1096 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1097 $sSQL .= "order by importance desc";
1098 // $sSQL .= "order by rank_search,rank_address,porder asc";
1099 if (CONST_Debug) var_dump('<hr>',$sSQL);
1100 $aSearchResults = $oDB->getAll($sSQL);
1101 //var_dump($sSQL,$aSearchResults);exit;
1103 if (PEAR::IsError($aSearchResults))
1105 var_dump($sSQL, $aSearchResults);
1112 $sSearchResult = '';
1113 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1115 $sSearchResult = 'No Results Found';
1117 //var_Dump($aSearchResults);
1119 $aClassType = getClassTypesWithImportance();
1120 foreach($aSearchResults as $iResNum => $aResult)
1122 if (CONST_Search_AreaPolygons || true)
1124 // Get the bounding box and outline polygon
1125 $sSQL = "select place_id,numfeatures,area,outline,";
1126 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1127 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1128 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1130 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1131 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1132 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1133 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1134 $aPointPolygon = $oDB->getRow($sSQL);
1135 if (PEAR::IsError($aPointPolygon))
1137 var_dump($sSQL, $aPointPolygon);
1140 if ($aPointPolygon['place_id'])
1142 // Translate geometary string to point array
1143 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1145 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1147 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1150 $iSteps = ($fRadius * 40000)^2;
1151 $fStepSize = (2*pi())/$iSteps;
1152 $aPolyPoints = array();
1153 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1155 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1157 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1158 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1159 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1160 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1163 // Output data suitable for display (points and a bounding box)
1164 if ($bShowPolygons && isset($aPolyPoints))
1166 $aResult['aPolyPoints'] = array();
1167 foreach($aPolyPoints as $aPoint)
1169 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1172 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1176 if (!isset($aResult['aBoundingBox']))
1179 $fDiameter = 0.0001;
1181 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1182 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1184 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1186 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1187 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1189 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1191 $fRadius = $fDiameter / 2;
1193 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1194 $fStepSize = (2*pi())/$iSteps;
1195 $aPolyPoints = array();
1196 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1198 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1200 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1201 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1202 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1203 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1205 // Output data suitable for display (points and a bounding box)
1208 $aResult['aPolyPoints'] = array();
1209 foreach($aPolyPoints as $aPoint)
1211 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1214 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1217 // Is there an icon set for this type of result?
1218 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1219 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1221 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1224 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1225 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1227 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1230 if ($bShowAddressDetails)
1232 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1233 //var_dump($aResult['address']);
1237 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1239 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1240 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1242 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1244 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1245 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1247 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1251 $aResult['importance'] = 1000000000000000;
1254 $aResult['name'] = $aResult['langaddress'];
1255 $aResult['foundorder'] = $iResNum;
1256 $aSearchResults[$iResNum] = $aResult;
1259 uasort($aSearchResults, 'byImportance');
1261 //var_dump($aSearchResults);exit;
1263 $aOSMIDDone = array();
1264 $aClassTypeNameDone = array();
1265 $aToFilter = $aSearchResults;
1266 $aSearchResults = array();
1269 foreach($aToFilter as $iResNum => $aResult)
1271 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1272 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1275 $fLat = $aResult['lat'];
1276 $fLon = $aResult['lon'];
1277 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1280 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1281 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1283 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1284 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1285 $aSearchResults[] = $aResult;
1288 // Absolute limit on number of results
1289 if (sizeof($aSearchResults) >= $iLimit) break;
1292 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1294 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1296 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1301 logEnd($oDB, $hLog, sizeof($aToFilter));
1303 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1304 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1305 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1306 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1307 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1308 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1311 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1313 $sMoreURL .= '&q='.urlencode($sQuery);
1315 if (CONST_Debug) exit;
1317 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');