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);
109 if (isset($aLangPrefOrder['name:en']))
111 $sQuery = preg_replace('/\\bil\\b/','illinois', $sQuery);
112 $sQuery = preg_replace('/\\bal\\b/','alabama', $sQuery);
113 $sQuery = preg_replace('/\\bla\\b/','louisiana', $sQuery);
116 // If we have a view box create the SQL
117 // Small is the actual view box, Large is double (on each axis) that
118 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
119 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
121 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
122 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
124 if (isset($_GET['viewbox']) && $_GET['viewbox'])
126 $aCoOrdinates = explode(',',$_GET['viewbox']);
127 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
128 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
129 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
130 $aCoOrdinates[0] += $fHeight;
131 $aCoOrdinates[2] -= $fHeight;
132 $aCoOrdinates[1] += $fWidth;
133 $aCoOrdinates[3] -= $fWidth;
134 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
136 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
138 $aPoints = explode(',',$_GET['route']);
139 if (sizeof($aPoints) % 2 != 0)
141 echo "Uneven number of points";
144 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
146 foreach($aPoints as $i => $fPoint)
150 if ($i != 1) $sViewboxCentreSQL .= ",";
151 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
155 $fPrevCoord = (float)$fPoint;
158 $sViewboxCentreSQL .= ")'::geometry,4326)";
160 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
161 $sViewboxSmallSQL = $oDB->getOne($sSQL);
162 if (PEAR::isError($sViewboxSmallSQL))
164 var_dump($sViewboxSmallSQL);
167 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
169 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
170 $sViewboxLargeSQL = $oDB->getOne($sSQL);
171 if (PEAR::isError($sViewboxLargeSQL))
173 var_dump($sViewboxLargeSQL);
176 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
179 // Do we have anything that looks like a lat/lon pair?
180 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
182 $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
183 $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
184 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
186 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
188 $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
189 $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
190 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
192 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b)/', $sQuery, $aData))
194 $_GET['nearlat'] = $aData[2];
195 $_GET['nearlon'] = $aData[3];
196 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
201 // Start with a blank search
203 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
204 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
207 $sNearPointSQL = false;
208 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
210 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
211 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
212 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
213 $aSearches[0]['fRadius'] = 0.1;
216 $bSpecialTerms = false;
217 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
218 $aSpecialTerms = array();
219 foreach($aSpecialTermsRaw as $aSpecialTerm)
221 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
222 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
225 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
226 $aSpecialTerms = array();
227 foreach($aSpecialTermsRaw as $aSpecialTerm)
229 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
230 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
231 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
232 $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';
233 $aSearchWords = $oDB->getAll($sSQL);
234 $aNewSearches = array();
235 foreach($aSearches as $aSearch)
237 foreach($aSearchWords as $aSearchTerm)
239 $aNewSearch = $aSearch;
240 if ($aSearchTerm['country_code'])
242 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
243 $aNewSearches[] = $aNewSearch;
244 $bSpecialTerms = true;
246 if ($aSearchTerm['class'])
248 $aNewSearch['sClass'] = $aSearchTerm['class'];
249 $aNewSearch['sType'] = $aSearchTerm['type'];
250 $aNewSearches[] = $aNewSearch;
251 $bSpecialTerms = true;
255 $aSearches = $aNewSearches;
258 // Split query into phrases
259 // Commas are used to reduce the search space by indicating where phrases split
260 $aPhrases = explode(',',$sQuery);
262 // Convert each phrase to standard form
263 // Create a list of standard words
264 // Get all 'sets' of words
265 // Generate a complete list of all
267 foreach($aPhrases as $iPhrase => $sPhrase)
269 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
270 if (PEAR::isError($aPhrase))
275 if (trim($aPhrase['string']))
277 $aPhrases[$iPhrase] = $aPhrase;
278 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
279 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
280 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
284 unset($aPhrases[$iPhrase]);
288 // reindex phrases - we make assumptions later on
289 $aPhrases = array_values($aPhrases);
291 if (sizeof($aTokens))
294 // Check which tokens we have, get the ID numbers
295 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
296 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
297 $sSQL .= ' and (class is null or class not in (\'highway\'))';
298 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
300 if (CONST_Debug) var_Dump($sSQL);
302 $aValidTokens = array();
303 if (sizeof($aTokens))
304 $aDatabaseWords = $oDB->getAll($sSQL);
306 $aDatabaseWords = array();
307 if (PEAR::IsError($aDatabaseWords))
309 var_dump($sSQL, $aDatabaseWords);
312 $aPossibleMainWordIDs = array();
313 foreach($aDatabaseWords as $aToken)
315 if (isset($aValidTokens[$aToken['word_token']]))
317 $aValidTokens[$aToken['word_token']][] = $aToken;
321 $aValidTokens[$aToken['word_token']] = array($aToken);
323 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
325 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
327 $aSuggestion = array();
328 $bSuggestion = false;
329 if (CONST_Suggestions_Enabled)
331 foreach($aPhrases as $iPhrase => $aPhrase)
333 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
335 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
336 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
337 $aRow = $aSuggestionWords[0];
338 if ($aRow && $aRow['word'])
340 $aSuggestion[] = $aRow['word'];
345 $aSuggestion[] = $aPhrase['string'];
350 $aSuggestion[] = $aPhrase['string'];
354 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
356 // Try and calculate GB postcodes we might be missing
357 foreach($aTokens as $sToken)
359 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))
361 if (substr($aData[1],-2,1) != ' ')
363 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
364 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
366 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
367 if ($aGBPostcodeLocation)
369 $aValidTokens[$sToken] = $aGBPostcodeLocation;
375 foreach($aTokens as $sToken)
377 // Unknown single word token with a number - assume it is a house number
378 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
380 $aValidTokens[' '.$sToken] = array('class'=>'place','type'=>'house');
384 // Any words that have failed completely?
387 // Start the search process
388 $aResultPlaceIDs = array();
391 Calculate all searches using aValidTokens i.e.
393 'Wodsworth Road, Sheffield' =>
397 0 1 (wodsworth)(road)
400 Score how good the search is so they can be ordered
403 foreach($aPhrases as $iPhrase => $sPhrase)
405 $aNewPhraseSearches = array();
407 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
409 $aWordsetSearches = $aSearches;
411 // Add all words from this wordset
412 foreach($aWordset as $sToken)
414 //echo "<br><b>$sToken</b>";
415 $aNewWordsetSearches = array();
417 foreach($aWordsetSearches as $aCurrentSearch)
420 //var_dump($aCurrentSearch);
423 // If the token is valid
424 if (isset($aValidTokens[' '.$sToken]))
426 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
428 $aSearch = $aCurrentSearch;
429 $aSearch['iSearchRank']++;
430 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
432 if ($aSearch['sCountryCode'] === false)
434 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
435 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
436 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
437 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
440 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
442 if ($aSearch['fLat'] === '')
444 $aSearch['fLat'] = $aSearchTerm['lat'];
445 $aSearch['fLon'] = $aSearchTerm['lon'];
446 $aSearch['fRadius'] = $aSearchTerm['radius'];
447 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
450 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
452 if ($aSearch['sHouseNumber'] === '')
454 $aSearch['sHouseNumber'] = $sToken;
455 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
457 // Fall back to not searching for this item (better than nothing)
458 $aSearch = $aCurrentSearch;
459 $aSearch['iSearchRank'] += 1;
460 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
464 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
466 if ($aSearch['sClass'] === '')
468 $aSearch['sOperator'] = $aSearchTerm['operator'];
469 $aSearch['sClass'] = $aSearchTerm['class'];
470 $aSearch['sType'] = $aSearchTerm['type'];
471 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
472 else $aSearch['sOperator'] = 'near'; // near = in for the moment
474 // Do we have a shortcut id?
475 if ($aSearch['sOperator'] == 'name')
477 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
478 if ($iAmenityID = $oDB->getOne($sSQL))
480 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
481 $aSearch['aName'][$iAmenityID] = $iAmenityID;
482 $aSearch['sClass'] = '';
483 $aSearch['sType'] = '';
486 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
491 if (sizeof($aSearch['aName']))
493 if (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false)
495 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
499 $aSearch['iSearchRank'] += 1000; // skip;
504 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
505 // $aSearch['iNamePhrase'] = $iPhrase;
507 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
511 if (isset($aValidTokens[$sToken]))
513 // Allow searching for a word - but at extra cost
514 foreach($aValidTokens[$sToken] as $aSearchTerm)
516 //var_Dump('<hr>',$aSearch['aName']);
518 if (sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
520 $aSearch = $aCurrentSearch;
521 $aSearch['iSearchRank'] += 1;
522 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
523 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
526 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
528 $aSearch = $aCurrentSearch;
529 $aSearch['iSearchRank'] += 2;
530 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
531 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
532 $aSearch['iNamePhrase'] = $iPhrase;
533 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
539 // Allow skipping a word - but at EXTREAM cost
540 //$aSearch = $aCurrentSearch;
541 //$aSearch['iSearchRank']+=100;
542 //$aNewWordsetSearches[] = $aSearch;
546 usort($aNewWordsetSearches, 'bySearchRank');
547 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
549 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
551 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
552 usort($aNewPhraseSearches, 'bySearchRank');
554 $aSearchHash = array();
555 foreach($aNewPhraseSearches as $iSearch => $aSearch)
557 $sHash = serialize($aSearch);
558 if (isset($aSearchHash[$sHash]))
560 unset($aNewPhraseSearches[$iSearch]);
564 $aSearchHash[$sHash] = 1;
568 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
571 // Re-group the searches by their score, junk anything over 20 as just not worth trying
572 $aGroupedSearches = array();
573 foreach($aNewPhraseSearches as $aSearch)
575 if ($aSearch['iSearchRank'] < $iMaxRank)
577 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
578 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
581 ksort($aGroupedSearches);
584 $aSearches = array();
585 foreach($aGroupedSearches as $iScore => $aNewSearches)
587 $iSearchCount += sizeof($aNewSearches);
588 $aSearches = array_merge($aSearches, $aNewSearches);
589 if ($iSearchCount > 50) break;
592 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
598 // Re-group the searches by their score, junk anything over 20 as just not worth trying
599 $aGroupedSearches = array();
600 foreach($aSearches as $aSearch)
602 if ($aSearch['iSearchRank'] < $iMaxRank)
604 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
605 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
608 ksort($aGroupedSearches);
611 if (CONST_Debug) var_Dump($aGroupedSearches);
615 $aCopyGroupedSearches = $aGroupedSearches;
616 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
618 foreach($aSearches as $iSearch => $aSearch)
620 if (sizeof($aSearch['aAddress']))
622 $iReverseItem = array_pop($aSearch['aAddress']);
623 if (isset($aPossibleMainWordIDs[$iReverseItem]))
625 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
626 $aSearch['aName'] = array($iReverseItem);
627 $aGroupedSearches[$iGroup][] = $aSearch;
629 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
630 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
636 // Filter out duplicate searches
637 $aSearchHash = array();
638 foreach($aGroupedSearches as $iGroup => $aSearches)
640 foreach($aSearches as $iSearch => $aSearch)
642 $sHash = serialize($aSearch);
643 if (isset($aSearchHash[$sHash]))
645 unset($aGroupedSearches[$iGroup][$iSearch]);
646 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
650 $aSearchHash[$sHash] = 1;
655 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
659 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
662 foreach($aSearches as $aSearch)
666 // Must have a location term
667 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
669 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
671 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
673 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
674 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
675 $sSQL .= " order by st_area(geometry) desc limit 1";
676 $aPlaceIDs = $oDB->getCol($sSQL);
681 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
682 if (!$aSearch['sClass']) continue;
683 if (CONST_Debug) var_dump('<hr>',$aSearch);
684 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
686 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
687 if ($oDB->getOne($sSQL))
689 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
690 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
691 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
692 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
693 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
694 $sSQL .= " limit $iLimit";
695 if (CONST_Debug) var_dump($sSQL);
696 $aPlaceIDs = $oDB->getCol($sSQL);
698 if (!sizeof($aPlaceIDs))
700 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];
701 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
702 $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
703 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
704 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
705 $sSQL .= " limit $iLimit";
706 if (CONST_Debug) var_dump($sSQL);
707 $aPlaceIDs = $oDB->getCol($sSQL);
712 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
713 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
714 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
715 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
716 $sSQL .= " limit $iLimit";
717 if (CONST_Debug) var_dump($sSQL);
718 $aPlaceIDs = $oDB->getCol($sSQL);
724 if (CONST_Debug) var_dump('<hr>',$aSearch);
725 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
726 $aPlaceIDs = array();
728 // First we need a position, either aName or fLat or both
731 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
732 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
733 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
734 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
735 if ($aSearch['fLon'] && $aSearch['fLat'])
737 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
738 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
740 if (sizeof($aExcludePlaceIDs))
742 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
744 if ($sCountryCodesSQL)
746 $aTerms[] = "country_code in ($sCountryCodesSQL)";
749 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
750 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
752 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
754 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
755 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
756 $aOrder[] = "$sImportanceSQL DESC";
760 $sSQL = "select place_id";
761 $sSQL .= " from search_name";
762 $sSQL .= " where ".join(' and ',$aTerms);
763 $sSQL .= " order by ".join(', ',$aOrder);
764 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
765 $sSQL .= " limit 50";
766 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
769 $sSQL .= " limit ".$iLimit;
771 if (CONST_Debug) var_dump($sSQL);
772 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
773 if (PEAR::IsError($aViewBoxPlaceIDs))
775 var_dump($sSQL, $aViewBoxPlaceIDs);
778 //var_dump($aViewBoxPlaceIDs);
779 // Did we have an viewbox matches?
780 $aPlaceIDs = array();
781 $bViewBoxMatch = false;
782 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
784 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
785 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
786 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
787 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
788 $aPlaceIDs[] = $aViewBoxRow['place_id'];
791 //var_Dump($aPlaceIDs);
794 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
796 $aRoadPlaceIDs = $aPlaceIDs;
797 $sPlaceIDs = join(',',$aPlaceIDs);
799 // Now they are indexed look for a house attached to a street we found
800 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
801 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
802 if (sizeof($aExcludePlaceIDs))
804 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
806 $sSQL .= " limit $iLimit";
807 if (CONST_Debug) var_dump($sSQL);
808 $aPlaceIDs = $oDB->getCol($sSQL);
810 // If not try the aux fallback table
811 if (!sizeof($aPlaceIDs))
813 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
814 if (sizeof($aExcludePlaceIDs))
816 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
818 // $sSQL .= " limit $iLimit";
819 if (CONST_Debug) var_dump($sSQL);
820 $aPlaceIDs = $oDB->getCol($sSQL);
823 if (!sizeof($aPlaceIDs))
825 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
826 if (sizeof($aExcludePlaceIDs))
828 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
830 // $sSQL .= " limit $iLimit";
831 if (CONST_Debug) var_dump($sSQL);
832 $aPlaceIDs = $oDB->getCol($sSQL);
835 // Fallback to the road
836 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
838 $aPlaceIDs = $aRoadPlaceIDs;
843 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
845 $sPlaceIDs = join(',',$aPlaceIDs);
847 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
849 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
850 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
851 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
852 $sSQL .= " order by rank_search asc limit $iLimit";
853 if (CONST_Debug) var_dump($sSQL);
854 $aPlaceIDs = $oDB->getCol($sSQL);
857 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
859 $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
861 if (CONST_Debug) var_dump($sSQL);
862 $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
864 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
865 if (CONST_Debug) var_dump($sSQL);
866 $aPlaceIDs = $oDB->getCol($sSQL);
867 $sPlaceIDs = join(',',$aPlaceIDs);
873 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
874 if ($oDB->getOne($sSQL))
876 // More efficient - can make the range bigger
878 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
879 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
880 $sSQL .= ",placex as f where ";
881 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
882 if (sizeof($aExcludePlaceIDs))
884 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
886 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
887 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.centroid) ASC";
888 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
889 $sSQL .= " limit $iLimit";
890 if (CONST_Debug) var_dump($sSQL);
891 $aPlaceIDs = $oDB->getCol($sSQL);
895 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
896 $sSQL = "select l.place_id from placex as l,placex as f where ";
897 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
898 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
899 if (sizeof($aExcludePlaceIDs))
901 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
903 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
904 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
905 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
906 $sSQL .= " limit $iLimit";
907 if (CONST_Debug) var_dump($sSQL);
908 $aPlaceIDs = $oDB->getCol($sSQL);
916 if (PEAR::IsError($aPlaceIDs))
918 var_dump($sSQL, $aPlaceIDs);
922 if (CONST_Debug) var_Dump($aPlaceIDs);
924 foreach($aPlaceIDs as $iPlaceID)
926 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
928 if ($iQueryLoop > 20) break;
931 if (sizeof($aResultPlaceIDs)) break;
932 if ($iGroupLoop > 4) break;
933 if ($iQueryLoop > 30) break;
936 // Did we find anything?
937 if (sizeof($aResultPlaceIDs))
939 //var_Dump($aResultPlaceIDs);exit;
940 // Get the details for display (is this a redundant extra step?)
941 $sPlaceIDs = join(',',$aResultPlaceIDs);
942 $sOrderSQL = 'CASE ';
943 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
945 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
947 $sOrderSQL .= ' ELSE 10000000 END';
948 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
949 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
950 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
951 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
952 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
953 // $sSQL .= $sOrderSQL." as porder, ";
954 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
955 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
956 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
957 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
958 if (!$bDeDupe) $sSQL .= ",place_id";
959 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
960 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
961 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
963 $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,";
964 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
965 $sSQL .= "null as placename,";
966 $sSQL .= "null as ref,";
967 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
968 // $sSQL .= $sOrderSQL." as porder, ";
969 $sSQL .= "-0.15 as importance ";
970 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
971 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
972 $sSQL .= "group by place_id";
973 if (!$bDeDupe) $sSQL .= ",place_id";
975 $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,";
976 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
977 $sSQL .= "null as placename,";
978 $sSQL .= "null as ref,";
979 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
980 // $sSQL .= $sOrderSQL." as porder, ";
981 $sSQL .= "-0.10 as importance ";
982 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
983 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
984 $sSQL .= "group by place_id";
985 if (!$bDeDupe) $sSQL .= ",place_id";
986 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
987 $sSQL .= "order by importance desc";
988 // $sSQL .= "order by rank_search,rank_address,porder asc";
989 if (CONST_Debug) var_dump('<hr>',$sSQL);
990 $aSearchResults = $oDB->getAll($sSQL);
991 //var_dump($sSQL,$aSearchResults);exit;
993 if (PEAR::IsError($aSearchResults))
995 var_dump($sSQL, $aSearchResults);
999 } // end if ($sQuery)
1002 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1004 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1005 $aResultPlaceIDs = array($iPlaceID);
1007 // TODO: this needs refactoring!
1009 // Get the details for display (is this a redundant extra step?)
1010 $sPlaceIDs = join(',',$aResultPlaceIDs);
1011 $sOrderSQL = 'CASE ';
1012 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1014 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1016 $sOrderSQL .= ' ELSE 10000000 END';
1017 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1018 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1019 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1020 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1021 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1022 // $sSQL .= $sOrderSQL." as porder, ";
1023 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1024 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1025 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1026 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1027 if (!$bDeDupe) $sSQL .= ",place_id";
1028 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1029 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1030 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1032 $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,";
1033 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1034 $sSQL .= "null as placename,";
1035 $sSQL .= "null as ref,";
1036 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1037 // $sSQL .= $sOrderSQL." as porder, ";
1038 $sSQL .= "-0.15 as importance ";
1039 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1040 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1041 $sSQL .= "group by place_id";
1042 if (!$bDeDupe) $sSQL .= ",place_id";
1044 $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,";
1045 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1046 $sSQL .= "null as placename,";
1047 $sSQL .= "null as ref,";
1048 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1049 // $sSQL .= $sOrderSQL." as porder, ";
1050 $sSQL .= "-0.10 as importance ";
1051 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1052 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1053 $sSQL .= "group by place_id";
1054 if (!$bDeDupe) $sSQL .= ",place_id";
1055 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1056 $sSQL .= "order by importance desc";
1057 // $sSQL .= "order by rank_search,rank_address,porder asc";
1058 if (CONST_Debug) var_dump('<hr>',$sSQL);
1059 $aSearchResults = $oDB->getAll($sSQL);
1060 //var_dump($sSQL,$aSearchResults);exit;
1062 if (PEAR::IsError($aSearchResults))
1064 var_dump($sSQL, $aSearchResults);
1071 $sSearchResult = '';
1072 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1074 $sSearchResult = 'No Results Found';
1076 //var_Dump($aSearchResults);
1078 $aClassType = getClassTypesWithImportance();
1079 foreach($aSearchResults as $iResNum => $aResult)
1081 if (CONST_Search_AreaPolygons || true)
1083 // Get the bounding box and outline polygon
1084 $sSQL = "select place_id,numfeatures,area,outline,";
1085 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
1086 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
1087 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1089 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1090 $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
1091 $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
1092 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
1093 $aPointPolygon = $oDB->getRow($sSQL);
1094 if (PEAR::IsError($aPointPolygon))
1096 var_dump($sSQL, $aPointPolygon);
1099 if ($aPointPolygon['place_id'])
1101 // Translate geometary string to point array
1102 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1104 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1106 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1109 $iSteps = ($fRadius * 40000)^2;
1110 $fStepSize = (2*pi())/$iSteps;
1111 $aPolyPoints = array();
1112 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1114 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1116 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1117 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1118 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1119 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1122 // Output data suitable for display (points and a bounding box)
1125 $aResult['aPolyPoints'] = array();
1126 foreach($aPolyPoints as $aPoint)
1128 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1131 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1135 if (!isset($aResult['aBoundingBox']))
1138 $fDiameter = 0.0001;
1140 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1141 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1143 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1145 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1146 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1148 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1150 $fRadius = $fDiameter / 2;
1152 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1153 $fStepSize = (2*pi())/$iSteps;
1154 $aPolyPoints = array();
1155 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1157 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1159 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1160 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1161 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1162 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1164 // Output data suitable for display (points and a bounding box)
1167 $aResult['aPolyPoints'] = array();
1168 foreach($aPolyPoints as $aPoint)
1170 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1173 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1176 // Is there an icon set for this type of result?
1177 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1178 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1180 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1183 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1184 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1186 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1189 if ($bShowAddressDetails)
1191 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1192 //var_dump($aResult['address']);
1196 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1198 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1199 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1201 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1203 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1204 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1206 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1210 $aResult['importance'] = 1000000000000000;
1213 $aResult['name'] = $aResult['langaddress'];
1214 $aResult['foundorder'] = $iResNum;
1215 $aSearchResults[$iResNum] = $aResult;
1218 uasort($aSearchResults, 'byImportance');
1220 //var_dump($aSearchResults);exit;
1222 $aOSMIDDone = array();
1223 $aClassTypeNameDone = array();
1224 $aToFilter = $aSearchResults;
1225 $aSearchResults = array();
1228 foreach($aToFilter as $iResNum => $aResult)
1230 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1231 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1234 $fLat = $aResult['lat'];
1235 $fLon = $aResult['lon'];
1236 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1239 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1240 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1242 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1243 $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1244 $aSearchResults[] = $aResult;
1247 // Absolute limit on number of results
1248 if (sizeof($aSearchResults) >= $iLimit) break;
1251 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1253 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1255 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1260 logEnd($oDB, $hLog, sizeof($aToFilter));
1262 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1263 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1264 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1265 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1266 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1267 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1270 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1272 $sMoreURL .= '&q='.urlencode($sQuery);
1274 if (CONST_Debug) exit;
1276 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');