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']))
59 switch($_GET['featuretype'])
62 $iMinAddressRank = $iMaxAddressRank = 4;
65 $iMinAddressRank = $iMaxAddressRank = 8;
68 $iMinAddressRank = 14;
69 $iMaxAddressRank = 16;
73 $iMaxAddressRank = 20;
78 if (isset($_GET['countrycodes']))
80 $aCountryCodes = array();
81 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
83 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
85 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
88 $sCountryCodesSQL = join(',', $aCountryCodes);
92 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
93 if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
95 $sQuery = substr($_SERVER['PATH_INFO'], 1);
97 // reverse order of '/' seperated string
98 $aPhrases = explode('/', $sQuery);
99 $aPhrases = array_reverse($aPhrases);
100 $sQuery = join(', ',$aPhrases);
105 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
107 // Hack to make it handle "new york, ny" (and variants) correctly
108 $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 we have a view box create the SQL
111 // Small is the actual view box, Large is double (on each axis) that
112 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
113 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
115 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
116 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
118 if (isset($_GET['viewbox']) && $_GET['viewbox'])
120 $aCoOrdinates = explode(',',$_GET['viewbox']);
121 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
122 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
123 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
124 $aCoOrdinates[0] += $fHeight;
125 $aCoOrdinates[2] -= $fHeight;
126 $aCoOrdinates[1] += $fWidth;
127 $aCoOrdinates[3] -= $fWidth;
128 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
130 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
132 $aPoints = explode(',',$_GET['route']);
133 if (sizeof($aPoints) % 2 != 0)
135 echo "Uneven number of points";
138 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
140 foreach($aPoints as $i => $fPoint)
144 if ($i != 1) $sViewboxCentreSQL .= ",";
145 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
149 $fPrevCoord = (float)$fPoint;
152 $sViewboxCentreSQL .= ")'::geometry,4326)";
154 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
155 $sViewboxSmallSQL = $oDB->getOne($sSQL);
156 if (PEAR::isError($sViewboxSmallSQL))
158 var_dump($sViewboxSmallSQL);
161 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
163 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
164 $sViewboxLargeSQL = $oDB->getOne($sSQL);
165 if (PEAR::isError($sViewboxLargeSQL))
167 var_dump($sViewboxLargeSQL);
170 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
173 // Do we have anything that looks like a lat/lon pair?
174 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
176 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
177 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
178 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
180 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
182 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
183 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
184 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
186 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b])/', $sQuery, $aData))
188 $_GET['nearlat'] = $aData[2];
189 $_GET['nearlon'] = $aData[3];
190 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
196 // Start with a blank search
198 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
199 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
202 $sNearPointSQL = false;
203 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
205 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
206 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
207 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
208 $aSearches[0]['fRadius'] = 0.1;
211 $bSpecialTerms = false;
212 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
213 $aSpecialTerms = array();
214 foreach($aSpecialTermsRaw as $aSpecialTerm)
216 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
217 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
220 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
221 $aSpecialTerms = array();
222 foreach($aSpecialTermsRaw as $aSpecialTerm)
224 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
225 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
226 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
227 $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';
228 $aSearchWords = $oDB->getAll($sSQL);
229 $aNewSearches = array();
230 foreach($aSearches as $aSearch)
232 foreach($aSearchWords as $aSearchTerm)
234 $aNewSearch = $aSearch;
235 if ($aSearchTerm['country_code'])
237 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
238 $aNewSearches[] = $aNewSearch;
239 $bSpecialTerms = true;
241 if ($aSearchTerm['class'])
243 $aNewSearch['sClass'] = $aSearchTerm['class'];
244 $aNewSearch['sType'] = $aSearchTerm['type'];
245 $aNewSearches[] = $aNewSearch;
246 $bSpecialTerms = true;
250 $aSearches = $aNewSearches;
253 // Split query into phrases
254 // Commas are used to reduce the search space by indicating where phrases split
255 $aPhrases = explode(',',$sQuery);
257 // Convert each phrase to standard form
258 // Create a list of standard words
259 // Get all 'sets' of words
260 // Generate a complete list of all
262 foreach($aPhrases as $iPhrase => $sPhrase)
264 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
265 if (PEAR::isError($aPhrase))
270 if (trim($aPhrase['string']))
272 $aPhrases[$iPhrase] = $aPhrase;
273 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
274 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
275 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
279 unset($aPhrases[$iPhrase]);
283 // reindex phrases - we make assumptions later on
284 $aPhrases = array_values($aPhrases);
286 if (sizeof($aTokens))
289 // Check which tokens we have, get the ID numbers
290 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
291 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
292 $sSQL .= ' and (class is null or class not in (\'highway\'))';
293 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
295 if (CONST_Debug) var_Dump($sSQL);
297 $aValidTokens = array();
298 if (sizeof($aTokens))
299 $aDatabaseWords = $oDB->getAll($sSQL);
301 $aDatabaseWords = array();
302 if (PEAR::IsError($aDatabaseWords))
304 var_dump($sSQL, $aDatabaseWords);
307 $aPossibleMainWordIDs = array();
308 foreach($aDatabaseWords as $aToken)
310 if (isset($aValidTokens[$aToken['word_token']]))
312 $aValidTokens[$aToken['word_token']][] = $aToken;
316 $aValidTokens[$aToken['word_token']] = array($aToken);
318 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
320 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
322 $aSuggestion = array();
323 $bSuggestion = false;
324 if (CONST_Suggestions_Enabled)
326 foreach($aPhrases as $iPhrase => $aPhrase)
328 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
330 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
331 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
332 $aRow = $aSuggestionWords[0];
333 if ($aRow && $aRow['word'])
335 $aSuggestion[] = $aRow['word'];
340 $aSuggestion[] = $aPhrase['string'];
345 $aSuggestion[] = $aPhrase['string'];
349 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
351 // Try and calculate GB postcodes we might be missing
352 foreach($aTokens as $sToken)
354 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))
356 if (substr($aData[1],-2,1) != ' ')
358 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
359 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
361 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
362 if ($aGBPostcodeLocation)
364 $aValidTokens[$sToken] = $aGBPostcodeLocation;
369 // Any words that have failed completely?
372 // Start the search process
373 $aResultPlaceIDs = array();
376 Calculate all searches using aValidTokens i.e.
378 'Wodsworth Road, Sheffield' =>
382 0 1 (wodsworth)(road)
385 Score how good the search is so they can be ordered
388 foreach($aPhrases as $iPhrase => $sPhrase)
390 $aNewPhraseSearches = array();
392 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
394 $aWordsetSearches = $aSearches;
396 // Add all words from this wordset
397 foreach($aWordset as $sToken)
399 //echo "<br><b>$sToken</b>";
400 $aNewWordsetSearches = array();
402 foreach($aWordsetSearches as $aCurrentSearch)
405 //var_dump($aCurrentSearch);
408 // If the token is valid
409 if (isset($aValidTokens[' '.$sToken]))
411 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
413 $aSearch = $aCurrentSearch;
414 $aSearch['iSearchRank']++;
415 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
417 if ($aSearch['sCountryCode'] === false)
419 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
420 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
421 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
422 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
425 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
427 if ($aSearch['fLat'] === '')
429 $aSearch['fLat'] = $aSearchTerm['lat'];
430 $aSearch['fLon'] = $aSearchTerm['lon'];
431 $aSearch['fRadius'] = $aSearchTerm['radius'];
432 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
435 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
437 if ($aSearch['sHouseNumber'] === '')
439 $aSearch['sHouseNumber'] = $sToken;
440 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
442 // Fall back to not searching for this item (better than nothing)
443 $aSearch = $aCurrentSearch;
444 $aSearch['iSearchRank'] += 1;
445 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
449 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
451 if ($aSearch['sClass'] === '')
453 $aSearch['sOperator'] = $aSearchTerm['operator'];
454 $aSearch['sClass'] = $aSearchTerm['class'];
455 $aSearch['sType'] = $aSearchTerm['type'];
456 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
457 else $aSearch['sOperator'] = 'near'; // near = in for the moment
459 // Do we have a shortcut id?
460 if ($aSearch['sOperator'] == 'name')
462 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
463 if ($iAmenityID = $oDB->getOne($sSQL))
465 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
466 $aSearch['aName'][$iAmenityID] = $iAmenityID;
467 $aSearch['sClass'] = '';
468 $aSearch['sType'] = '';
471 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
476 if (sizeof($aSearch['aName']))
478 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
480 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
484 $aSearch['iSearchRank'] += 1000; // skip;
489 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
490 // $aSearch['iNamePhrase'] = $iPhrase;
492 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
496 if (isset($aValidTokens[$sToken]))
498 // Allow searching for a word - but at extra cost
499 foreach($aValidTokens[$sToken] as $aSearchTerm)
501 //var_Dump('<hr>',$aSearch['aName']);
503 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
505 $aSearch = $aCurrentSearch;
506 $aSearch['iSearchRank'] += 1;
507 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
508 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
511 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
513 $aSearch = $aCurrentSearch;
514 $aSearch['iSearchRank'] += 2;
515 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
516 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
517 $aSearch['iNamePhrase'] = $iPhrase;
518 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
524 // Allow skipping a word - but at EXTREAM cost
525 //$aSearch = $aCurrentSearch;
526 //$aSearch['iSearchRank']+=100;
527 //$aNewWordsetSearches[] = $aSearch;
531 usort($aNewWordsetSearches, 'bySearchRank');
532 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
534 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
536 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
537 usort($aNewPhraseSearches, 'bySearchRank');
539 $aSearchHash = array();
540 foreach($aNewPhraseSearches as $iSearch => $aSearch)
542 $sHash = serialize($aSearch);
543 if (isset($aSearchHash[$sHash]))
545 unset($aNewPhraseSearches[$iSearch]);
549 $aSearchHash[$sHash] = 1;
553 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
556 // Re-group the searches by their score, junk anything over 20 as just not worth trying
557 $aGroupedSearches = array();
558 foreach($aNewPhraseSearches as $aSearch)
560 if ($aSearch['iSearchRank'] < $iMaxRank)
562 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
563 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
566 ksort($aGroupedSearches);
569 $aSearches = array();
570 foreach($aGroupedSearches as $iScore => $aNewSearches)
572 $iSearchCount += sizeof($aNewSearches);
573 $aSearches = array_merge($aSearches, $aNewSearches);
574 if ($iSearchCount > 50) break;
577 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
583 // Re-group the searches by their score, junk anything over 20 as just not worth trying
584 $aGroupedSearches = array();
585 foreach($aSearches as $aSearch)
587 if ($aSearch['iSearchRank'] < $iMaxRank)
589 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
590 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
593 ksort($aGroupedSearches);
596 if (CONST_Debug) var_Dump($aGroupedSearches);
600 $aCopyGroupedSearches = $aGroupedSearches;
601 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
603 foreach($aSearches as $iSearch => $aSearch)
605 if (sizeof($aSearch['aAddress']))
607 $iReverseItem = array_pop($aSearch['aAddress']);
608 if (isset($aPossibleMainWordIDs[$iReverseItem]))
610 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
611 $aSearch['aName'] = array($iReverseItem);
612 $aGroupedSearches[$iGroup][] = $aSearch;
614 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
615 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
621 // Filter out duplicate searches
622 $aSearchHash = array();
623 foreach($aGroupedSearches as $iGroup => $aSearches)
625 foreach($aSearches as $iSearch => $aSearch)
627 $sHash = serialize($aSearch);
628 if (isset($aSearchHash[$sHash]))
630 unset($aGroupedSearches[$iGroup][$iSearch]);
631 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
635 $aSearchHash[$sHash] = 1;
640 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
644 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
647 foreach($aSearches as $aSearch)
651 // Must have a location term
652 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
654 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
656 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
658 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4 order by st_area(geometry) desc limit 1";
659 $aPlaceIDs = $oDB->getCol($sSQL);
664 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
665 if (!$aSearch['sClass']) continue;
666 if (CONST_Debug) var_dump('<hr>',$aSearch);
667 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
669 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
670 if ($oDB->getOne($sSQL))
672 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
673 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
674 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
675 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
676 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
677 $sSQL .= " limit $iLimit";
678 if (CONST_Debug) var_dump($sSQL);
679 $aPlaceIDs = $oDB->getCol($sSQL);
681 if (!sizeof($aPlaceIDs))
683 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
684 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
685 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
686 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
687 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
688 $sSQL .= " limit $iLimit";
689 if (CONST_Debug) var_dump($sSQL);
690 $aPlaceIDs = $oDB->getCol($sSQL);
695 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
696 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
697 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
698 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
699 $sSQL .= " limit $iLimit";
700 if (CONST_Debug) var_dump($sSQL);
701 $aPlaceIDs = $oDB->getCol($sSQL);
707 if (CONST_Debug) var_dump('<hr>',$aSearch);
708 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
709 $aPlaceIDs = array();
711 // First we need a position, either aName or fLat or both
714 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
715 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
716 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
717 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
718 if ($aSearch['fLon'] && $aSearch['fLat'])
720 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
721 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
723 if (sizeof($aExcludePlaceIDs))
725 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
727 if ($sCountryCodesSQL)
729 $aTerms[] = "country_code in ($sCountryCodesSQL)";
732 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
733 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
735 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
737 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
738 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
739 $aOrder[] = "$sImportanceSQL DESC";
743 $sSQL = "select place_id";
744 $sSQL .= " from search_name";
745 $sSQL .= " where ".join(' and ',$aTerms);
746 $sSQL .= " order by ".join(', ',$aOrder);
747 if ($aSearch['sHouseNumber'])
748 $sSQL .= " limit 50";
749 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
752 $sSQL .= " limit ".$iLimit;
754 if (CONST_Debug) var_dump($sSQL);
755 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
756 if (PEAR::IsError($aViewBoxPlaceIDs))
758 var_dump($sSQL, $aViewBoxPlaceIDs);
761 //var_dump($aViewBoxPlaceIDs);
762 // Did we have an viewbox matches?
763 $aPlaceIDs = array();
764 $bViewBoxMatch = false;
765 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
767 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
768 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
769 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
770 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
771 $aPlaceIDs[] = $aViewBoxRow['place_id'];
774 //var_Dump($aPlaceIDs);
777 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
779 $aRoadPlaceIDs = $aPlaceIDs;
780 $sPlaceIDs = join(',',$aPlaceIDs);
782 // Now they are indexed look for a house attached to a street we found
783 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
784 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
785 if (sizeof($aExcludePlaceIDs))
787 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
789 $sSQL .= " limit $iLimit";
790 if (CONST_Debug) var_dump($sSQL);
791 $aPlaceIDs = $oDB->getCol($sSQL);
793 // If not try the aux fallback table
794 if (!sizeof($aPlaceIDs))
796 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
797 if (sizeof($aExcludePlaceIDs))
799 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
801 // $sSQL .= " limit $iLimit";
802 if (CONST_Debug) var_dump($sSQL);
803 $aPlaceIDs = $oDB->getCol($sSQL);
806 if (!sizeof($aPlaceIDs))
808 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
809 if (sizeof($aExcludePlaceIDs))
811 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
813 // $sSQL .= " limit $iLimit";
814 if (CONST_Debug) var_dump($sSQL);
815 $aPlaceIDs = $oDB->getCol($sSQL);
818 // Fallback to the road
819 if (!sizeof($aPlaceIDs) && preg_match('/^[0-9]+$/', $aSearch['sHouseNumber']))
821 $aPlaceIDs = $aRoadPlaceIDs;
826 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
828 $sPlaceIDs = join(',',$aPlaceIDs);
830 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
832 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
833 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
834 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
835 $sSQL .= " order by rank_search asc limit $iLimit";
836 if (CONST_Debug) var_dump($sSQL);
837 $aPlaceIDs = $oDB->getCol($sSQL);
840 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
842 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
844 if (CONST_Debug) var_dump($sSQL);
845 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
847 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
848 if (CONST_Debug) var_dump($sSQL);
849 $aPlaceIDs = $oDB->getCol($sSQL);
850 $sPlaceIDs = join(',',$aPlaceIDs);
856 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
857 if ($oDB->getOne($sSQL))
859 // More efficient - can make the range bigger
861 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
862 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
863 $sSQL .= ",placex as f where ";
864 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
865 if (sizeof($aExcludePlaceIDs))
867 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
869 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
870 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.centroid) ASC";
871 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
872 $sSQL .= " limit $iLimit";
873 if (CONST_Debug) var_dump($sSQL);
874 $aPlaceIDs = $oDB->getCol($sSQL);
878 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
879 $sSQL = "select l.place_id from placex as l,placex as f where ";
880 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
881 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
882 if (sizeof($aExcludePlaceIDs))
884 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
886 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
887 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
888 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
889 $sSQL .= " limit $iLimit";
890 if (CONST_Debug) var_dump($sSQL);
891 $aPlaceIDs = $oDB->getCol($sSQL);
899 if (PEAR::IsError($aPlaceIDs))
901 var_dump($sSQL, $aPlaceIDs);
905 if (CONST_Debug) var_Dump($aPlaceIDs);
907 foreach($aPlaceIDs as $iPlaceID)
909 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
911 if ($iQueryLoop > 20) break;
914 if (sizeof($aResultPlaceIDs)) break;
915 if ($iGroupLoop > 4) break;
916 if ($iQueryLoop > 30) break;
919 // Did we find anything?
920 if (sizeof($aResultPlaceIDs))
922 //var_Dump($aResultPlaceIDs);exit;
923 // Get the details for display (is this a redundant extra step?)
924 $sPlaceIDs = join(',',$aResultPlaceIDs);
925 $sOrderSQL = 'CASE ';
926 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
928 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
930 $sOrderSQL .= ' ELSE 10000000 END';
931 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
932 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
933 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
934 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
935 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
936 // $sSQL .= $sOrderSQL." as porder, ";
937 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
938 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
939 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
940 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
941 if (!$bDeDupe) $sSQL .= ",place_id";
942 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
943 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
944 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
946 $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,";
947 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
948 $sSQL .= "null as placename,";
949 $sSQL .= "null as ref,";
950 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
951 // $sSQL .= $sOrderSQL." as porder, ";
952 $sSQL .= "-0.15 as importance ";
953 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
954 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
955 $sSQL .= "group by place_id";
956 if (!$bDeDupe) $sSQL .= ",place_id";
958 $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,";
959 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
960 $sSQL .= "null as placename,";
961 $sSQL .= "null as ref,";
962 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
963 // $sSQL .= $sOrderSQL." as porder, ";
964 $sSQL .= "-0.10 as importance ";
965 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
966 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
967 $sSQL .= "group by place_id";
968 if (!$bDeDupe) $sSQL .= ",place_id";
969 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
970 $sSQL .= "order by importance desc";
971 // $sSQL .= "order by rank_search,rank_address,porder asc";
972 if (CONST_Debug) var_dump('<hr>',$sSQL);
973 $aSearchResults = $oDB->getAll($sSQL);
974 //var_dump($sSQL,$aSearchResults);exit;
976 if (PEAR::IsError($aSearchResults))
978 var_dump($sSQL, $aSearchResults);
986 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
988 $sSearchResult = 'No Results Found';
990 //var_Dump($aSearchResults);
992 $aClassType = getClassTypesWithImportance();
993 foreach($aSearchResults as $iResNum => $aResult)
995 if (CONST_Search_AreaPolygons || true)
997 // Get the bounding box and outline polygon
998 $sSQL = "select place_id,numfeatures,area,outline,";
999 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1000 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1001 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1003 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1004 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1005 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1006 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1007 $aPointPolygon = $oDB->getRow($sSQL);
1008 if (PEAR::IsError($aPointPolygon))
1010 var_dump($sSQL, $aPointPolygon);
1013 if ($aPointPolygon['place_id'])
1015 // Translate geometary string to point array
1016 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1018 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1020 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1023 $iSteps = ($fRadius * 40000)^2;
1024 $fStepSize = (2*pi())/$iSteps;
1025 $aPolyPoints = array();
1026 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1028 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1030 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1031 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1032 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1033 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1036 // Output data suitable for display (points and a bounding box)
1039 $aResult['aPolyPoints'] = array();
1040 foreach($aPolyPoints as $aPoint)
1042 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1045 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1049 if (!isset($aResult['aBoundingBox']))
1052 $fDiameter = 0.0001;
1054 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1055 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1057 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1059 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1060 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1062 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1064 $fRadius = $fDiameter / 2;
1066 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1067 $fStepSize = (2*pi())/$iSteps;
1068 $aPolyPoints = array();
1069 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1071 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1073 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1074 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1075 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1076 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1078 // Output data suitable for display (points and a bounding box)
1081 $aResult['aPolyPoints'] = array();
1082 foreach($aPolyPoints as $aPoint)
1084 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1087 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1090 // Is there an icon set for this type of result?
1091 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1092 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1094 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1097 if ($bShowAddressDetails)
1099 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1100 //var_dump($aResult['address']);
1104 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1106 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1107 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1109 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1111 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1112 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1114 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1118 $aResult['importance'] = 1000000000000000;
1121 $aResult['name'] = $aResult['langaddress'];
1122 $aResult['foundorder'] = $iResNum;
1123 $aSearchResults[$iResNum] = $aResult;
1126 uasort($aSearchResults, 'byImportance');
1128 //var_dump($aSearchResults);exit;
1130 $aOSMIDDone = array();
1131 $aClassTypeNameDone = array();
1132 $aToFilter = $aSearchResults;
1133 $aSearchResults = array();
1136 foreach($aToFilter as $iResNum => $aResult)
1138 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1139 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1142 $fLat = $aResult['lat'];
1143 $fLon = $aResult['lon'];
1144 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1147 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1148 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1150 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1151 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1152 $aSearchResults[] = $aResult;
1156 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1158 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1160 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1165 logEnd($oDB, $hLog, sizeof($aToFilter));
1167 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1168 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1169 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1170 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1171 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1172 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1175 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1177 $sMoreURL .= '&q='.urlencode($sQuery);
1179 if (CONST_Debug) exit;
1181 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');