2 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3 require_once(CONST_BasePath.'/lib/log.php');
5 ini_set('memory_limit', '200M');
9 $fLat = CONST_Default_Lat;
10 $fLon = CONST_Default_Lon;
11 $iZoom = CONST_Default_Zoom;
12 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13 $sOutputFormat = 'html';
14 $aSearchResults = array();
15 $aExcludePlaceIDs = array();
16 $sCountryCodesSQL = false;
17 $sSuggestion = $sSuggestionURL = false;
18 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19 $bReverseInPlan = false;
20 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iLimit > 100) $iLimit = 100;
25 $iMaxAddressRank = 30;
28 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
30 $sOutputFormat = $_GET['format'];
33 // Show / use polygons
34 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
36 // Show address breakdown
37 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
40 $aLangPrefOrder = getPreferredLanguages();
41 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
42 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
43 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
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 && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
97 $sQuery = substr($_SERVER['PATH_INFO'], 1);
99 // reverse order of '/' separated string
100 $aPhrases = explode('/', $sQuery);
101 $aPhrases = array_reverse($aPhrases);
102 $sQuery = join(', ',$aPhrases);
105 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
107 if (!isset($_GET[$sKey])) return false;
108 $sValue = trim($_GET[$sKey]);
109 if (!$sValue) return false;
110 $aStructuredQuery[$sKey] = $sValue;
111 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
112 $iMinAddressRank = $iNewMinAddressRank;
113 $iMaxAddressRank = $iNewMaxAddressRank;
119 $aStructuredOptions = array(
120 array('amenity', 26, 30),
121 array('street', 26, 30),
122 array('city', 14, 24),
123 array('county', 9, 13),
124 array('state', 8, 8),
125 array('country', 4, 4),
126 array('postalcode', 16, 25),
128 $aStructuredQuery = array();
129 foreach($aStructuredOptions as $aStructuredOption)
131 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
133 if (sizeof($aStructuredQuery) > 0) {
134 $sQuery = join(', ', $aStructuredQuery);
139 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
141 // Hack to make it handle "new york, ny" (and variants) correctly
142 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
143 if (isset($aLangPrefOrder['name:en']))
145 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
146 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
147 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
150 // If we have a view box create the SQL
151 // Small is the actual view box, Large is double (on each axis) that
152 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
153 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
155 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
156 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
158 if (isset($_GET['viewbox']) && $_GET['viewbox'])
160 $aCoOrdinates = explode(',',$_GET['viewbox']);
161 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
162 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
163 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
164 $aCoOrdinates[0] += $fHeight;
165 $aCoOrdinates[2] -= $fHeight;
166 $aCoOrdinates[1] += $fWidth;
167 $aCoOrdinates[3] -= $fWidth;
168 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
170 $bBoundingBoxSearch = false;
172 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
174 $aPoints = explode(',',$_GET['route']);
175 if (sizeof($aPoints) % 2 != 0)
177 echo "Uneven number of points";
180 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
182 foreach($aPoints as $i => $fPoint)
186 if ($i != 1) $sViewboxCentreSQL .= ",";
187 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
191 $fPrevCoord = (float)$fPoint;
194 $sViewboxCentreSQL .= ")'::geometry,4326)";
196 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
197 $sViewboxSmallSQL = $oDB->getOne($sSQL);
198 if (PEAR::isError($sViewboxSmallSQL))
200 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
202 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
204 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
205 $sViewboxLargeSQL = $oDB->getOne($sSQL);
206 if (PEAR::isError($sViewboxLargeSQL))
208 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
210 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
213 // Do we have anything that looks like a lat/lon pair?
214 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
216 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
217 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
218 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
220 $_GET['nearlat'] = $fQueryLat;
221 $_GET['nearlon'] = $fQueryLon;
222 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
225 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
227 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
228 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
229 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
231 $_GET['nearlat'] = $fQueryLat;
232 $_GET['nearlon'] = $fQueryLon;
233 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
236 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
238 $fQueryLat = $aData[2];
239 $fQueryLon = $aData[3];
240 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
242 $_GET['nearlat'] = $fQueryLat;
243 $_GET['nearlon'] = $fQueryLon;
244 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
248 if ($sQuery || $aStructuredQuery)
250 // Start with a blank search
252 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
253 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
256 $sNearPointSQL = false;
257 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
259 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
260 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
261 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
262 $aSearches[0]['fRadius'] = 0.1;
265 $bSpecialTerms = false;
266 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
267 $aSpecialTerms = array();
268 foreach($aSpecialTermsRaw as $aSpecialTerm)
270 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
271 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
274 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
275 $aSpecialTerms = array();
276 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
278 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
279 unset($aStructuredQuery['amenity']);
281 foreach($aSpecialTermsRaw as $aSpecialTerm)
283 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
284 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
285 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
286 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class not in (\'place\')) or country_code is not null';
287 if (CONST_Debug) var_Dump($sSQL);
288 $aSearchWords = $oDB->getAll($sSQL);
289 $aNewSearches = array();
290 foreach($aSearches as $aSearch)
292 foreach($aSearchWords as $aSearchTerm)
294 $aNewSearch = $aSearch;
295 if ($aSearchTerm['country_code'])
297 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
298 $aNewSearches[] = $aNewSearch;
299 $bSpecialTerms = true;
301 if ($aSearchTerm['class'])
303 $aNewSearch['sClass'] = $aSearchTerm['class'];
304 $aNewSearch['sType'] = $aSearchTerm['type'];
305 $aNewSearches[] = $aNewSearch;
306 $bSpecialTerms = true;
310 $aSearches = $aNewSearches;
313 // Split query into phrases
314 // Commas are used to reduce the search space by indicating where phrases split
315 if (sizeof($aStructuredQuery) > 0)
317 $aPhrases = $aStructuredQuery;
318 $bStructuredPhrases = true;
322 $aPhrases = explode(',',$sQuery);
323 $bStructuredPhrases = false;
327 // Convert each phrase to standard form
328 // Create a list of standard words
329 // Get all 'sets' of words
330 // Generate a complete list of all
332 foreach($aPhrases as $iPhrase => $sPhrase)
334 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
335 if (PEAR::isError($aPhrase))
337 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
338 if (CONST_Debug) var_dump($aPhrase);
341 if (trim($aPhrase['string']))
343 $aPhrases[$iPhrase] = $aPhrase;
344 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
345 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
346 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
350 unset($aPhrases[$iPhrase]);
354 // reindex phrases - we make assumptions later on
355 $aPhraseTypes = array_keys($aPhrases);
356 $aPhrases = array_values($aPhrases);
358 if (sizeof($aTokens))
361 // Check which tokens we have, get the ID numbers
362 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
363 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
364 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
365 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
367 if (CONST_Debug) var_Dump($sSQL);
369 $aValidTokens = array();
370 if (sizeof($aTokens))
371 $aDatabaseWords = $oDB->getAll($sSQL);
373 $aDatabaseWords = array();
374 if (PEAR::IsError($aDatabaseWords))
376 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
378 $aPossibleMainWordIDs = array();
379 foreach($aDatabaseWords as $aToken)
381 if (isset($aValidTokens[$aToken['word_token']]))
383 $aValidTokens[$aToken['word_token']][] = $aToken;
387 $aValidTokens[$aToken['word_token']] = array($aToken);
389 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
391 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
393 $aSuggestion = array();
394 $bSuggestion = false;
395 if (CONST_Suggestions_Enabled)
397 foreach($aPhrases as $iPhrase => $aPhrase)
399 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
401 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
402 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
403 $aRow = $aSuggestionWords[0];
404 if ($aRow && $aRow['word'])
406 $aSuggestion[] = $aRow['word'];
411 $aSuggestion[] = $aPhrase['string'];
416 $aSuggestion[] = $aPhrase['string'];
420 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
422 // Try and calculate GB postcodes we might be missing
423 foreach($aTokens as $sToken)
425 // Source of gb postcodes is now definitive - always use
426 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
428 if (substr($aData[1],-2,1) != ' ')
430 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
431 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
433 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
434 if ($aGBPostcodeLocation)
436 $aValidTokens[$sToken] = $aGBPostcodeLocation;
441 foreach($aTokens as $sToken)
443 // Unknown single word token with a number - assume it is a house number
444 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
446 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
450 // Any words that have failed completely?
453 // Start the search process
454 $aResultPlaceIDs = array();
457 Calculate all searches using aValidTokens i.e.
459 'Wodsworth Road, Sheffield' =>
463 0 1 (wodsworth)(road)
466 Score how good the search is so they can be ordered
468 foreach($aPhrases as $iPhrase => $sPhrase)
470 $aNewPhraseSearches = array();
471 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
472 else $sPhraseType = '';
474 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
476 $aWordsetSearches = $aSearches;
478 // Add all words from this wordset
479 foreach($aWordset as $iToken => $sToken)
481 //echo "<br><b>$sToken</b>";
482 $aNewWordsetSearches = array();
484 foreach($aWordsetSearches as $aCurrentSearch)
487 //var_dump($aCurrentSearch);
490 // If the token is valid
491 if (isset($aValidTokens[' '.$sToken]))
493 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
495 $aSearch = $aCurrentSearch;
496 $aSearch['iSearchRank']++;
497 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
499 if ($aSearch['sCountryCode'] === false)
501 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
502 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
503 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
504 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
507 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
509 if ($aSearch['fLat'] === '')
511 $aSearch['fLat'] = $aSearchTerm['lat'];
512 $aSearch['fLon'] = $aSearchTerm['lon'];
513 $aSearch['fRadius'] = $aSearchTerm['radius'];
514 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
517 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
519 if ($aSearch['sHouseNumber'] === '')
521 $aSearch['sHouseNumber'] = $sToken;
522 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
524 // Fall back to not searching for this item (better than nothing)
525 $aSearch = $aCurrentSearch;
526 $aSearch['iSearchRank'] += 1;
527 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
531 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
533 if ($aSearch['sClass'] === '')
535 $aSearch['sOperator'] = $aSearchTerm['operator'];
536 $aSearch['sClass'] = $aSearchTerm['class'];
537 $aSearch['sType'] = $aSearchTerm['type'];
538 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
539 else $aSearch['sOperator'] = 'near'; // near = in for the moment
541 // Do we have a shortcut id?
542 if ($aSearch['sOperator'] == 'name')
544 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
545 if ($iAmenityID = $oDB->getOne($sSQL))
547 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
548 $aSearch['aName'][$iAmenityID] = $iAmenityID;
549 $aSearch['sClass'] = '';
550 $aSearch['sType'] = '';
553 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
556 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
558 if (sizeof($aSearch['aName']))
560 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
562 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
566 $aSearch['iSearchRank'] += 1000; // skip;
571 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
572 // $aSearch['iNamePhrase'] = $iPhrase;
574 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
578 if (isset($aValidTokens[$sToken]))
580 // Allow searching for a word - but at extra cost
581 foreach($aValidTokens[$sToken] as $aSearchTerm)
583 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
585 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
587 $aSearch = $aCurrentSearch;
588 $aSearch['iSearchRank'] += 1;
589 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
590 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
593 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
595 $aSearch = $aCurrentSearch;
596 $aSearch['iSearchRank'] += 2;
597 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
598 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
599 $aSearch['iNamePhrase'] = $iPhrase;
600 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
607 // Allow skipping a word - but at EXTREAM cost
608 //$aSearch = $aCurrentSearch;
609 //$aSearch['iSearchRank']+=100;
610 //$aNewWordsetSearches[] = $aSearch;
614 usort($aNewWordsetSearches, 'bySearchRank');
615 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
617 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
619 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
620 usort($aNewPhraseSearches, 'bySearchRank');
622 $aSearchHash = array();
623 foreach($aNewPhraseSearches as $iSearch => $aSearch)
625 $sHash = serialize($aSearch);
626 if (isset($aSearchHash[$sHash]))
628 unset($aNewPhraseSearches[$iSearch]);
632 $aSearchHash[$sHash] = 1;
636 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
639 // Re-group the searches by their score, junk anything over 20 as just not worth trying
640 $aGroupedSearches = array();
641 foreach($aNewPhraseSearches as $aSearch)
643 if ($aSearch['iSearchRank'] < $iMaxRank)
645 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
646 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
649 ksort($aGroupedSearches);
652 $aSearches = array();
653 foreach($aGroupedSearches as $iScore => $aNewSearches)
655 $iSearchCount += sizeof($aNewSearches);
656 $aSearches = array_merge($aSearches, $aNewSearches);
657 if ($iSearchCount > 50) break;
660 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
666 // Re-group the searches by their score, junk anything over 20 as just not worth trying
667 $aGroupedSearches = array();
668 foreach($aSearches as $aSearch)
670 if ($aSearch['iSearchRank'] < $iMaxRank)
672 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
673 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
676 ksort($aGroupedSearches);
679 if (CONST_Debug) var_Dump($aGroupedSearches);
683 $aCopyGroupedSearches = $aGroupedSearches;
684 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
686 foreach($aSearches as $iSearch => $aSearch)
688 if (sizeof($aSearch['aAddress']))
690 $iReverseItem = array_pop($aSearch['aAddress']);
691 if (isset($aPossibleMainWordIDs[$iReverseItem]))
693 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
694 $aSearch['aName'] = array($iReverseItem);
695 $aGroupedSearches[$iGroup][] = $aSearch;
697 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
698 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
704 // Filter out duplicate searches
705 $aSearchHash = array();
706 foreach($aGroupedSearches as $iGroup => $aSearches)
708 foreach($aSearches as $iSearch => $aSearch)
710 $sHash = serialize($aSearch);
711 if (isset($aSearchHash[$sHash]))
713 unset($aGroupedSearches[$iGroup][$iSearch]);
714 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
718 $aSearchHash[$sHash] = 1;
723 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
727 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
730 foreach($aSearches as $aSearch)
734 // Must have a location term
735 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
737 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
739 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
741 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
742 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
743 $sSQL .= " order by st_area(geometry) desc limit 1";
744 $aPlaceIDs = $oDB->getCol($sSQL);
749 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
750 if (!$aSearch['sClass']) continue;
751 if (CONST_Debug) var_dump('<hr>',$aSearch);
752 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
754 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
755 if ($oDB->getOne($sSQL))
757 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
758 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
759 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
760 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
761 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
762 $sSQL .= " limit $iLimit";
763 if (CONST_Debug) var_dump($sSQL);
764 $aPlaceIDs = $oDB->getCol($sSQL);
766 if (!sizeof($aPlaceIDs))
768 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
769 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
770 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
771 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
772 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
773 $sSQL .= " limit $iLimit";
774 if (CONST_Debug) var_dump($sSQL);
775 $aPlaceIDs = $oDB->getCol($sSQL);
780 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
781 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
782 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
783 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
784 $sSQL .= " limit $iLimit";
785 if (CONST_Debug) var_dump($sSQL);
786 $aPlaceIDs = $oDB->getCol($sSQL);
792 if (CONST_Debug) var_dump('<hr>',$aSearch);
793 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
794 $aPlaceIDs = array();
796 // First we need a position, either aName or fLat or both
800 // TODO: filter out the pointless search terms (2 letter name tokens and less)
801 // they might be right - but they are just too darned expensive to run
802 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
803 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
804 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
805 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
806 if ($aSearch['fLon'] && $aSearch['fLat'])
808 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
809 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
811 if (sizeof($aExcludePlaceIDs))
813 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
815 if ($sCountryCodesSQL)
817 $aTerms[] = "country_code in ($sCountryCodesSQL)";
820 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
821 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
823 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
825 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
826 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
827 $aOrder[] = "$sImportanceSQL DESC";
831 $sSQL = "select place_id";
832 $sSQL .= " from search_name";
833 $sSQL .= " where ".join(' and ',$aTerms);
834 $sSQL .= " order by ".join(', ',$aOrder);
835 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
836 $sSQL .= " limit 50";
837 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
840 $sSQL .= " limit ".$iLimit;
842 if (CONST_Debug) var_dump($sSQL);
843 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
844 if (PEAR::IsError($aViewBoxPlaceIDs))
846 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
848 //var_dump($aViewBoxPlaceIDs);
849 // Did we have an viewbox matches?
850 $aPlaceIDs = array();
851 $bViewBoxMatch = false;
852 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
854 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
855 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
856 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
857 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
858 $aPlaceIDs[] = $aViewBoxRow['place_id'];
861 //var_Dump($aPlaceIDs);
864 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
866 $aRoadPlaceIDs = $aPlaceIDs;
867 $sPlaceIDs = join(',',$aPlaceIDs);
869 // Now they are indexed look for a house attached to a street we found
870 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
871 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
872 if (sizeof($aExcludePlaceIDs))
874 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
876 $sSQL .= " limit $iLimit";
877 if (CONST_Debug) var_dump($sSQL);
878 $aPlaceIDs = $oDB->getCol($sSQL);
880 // If not try the aux fallback table
881 if (!sizeof($aPlaceIDs))
883 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
884 if (sizeof($aExcludePlaceIDs))
886 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
888 // $sSQL .= " limit $iLimit";
889 if (CONST_Debug) var_dump($sSQL);
890 $aPlaceIDs = $oDB->getCol($sSQL);
893 if (!sizeof($aPlaceIDs))
895 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
896 if (sizeof($aExcludePlaceIDs))
898 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
900 // $sSQL .= " limit $iLimit";
901 if (CONST_Debug) var_dump($sSQL);
902 $aPlaceIDs = $oDB->getCol($sSQL);
905 // Fallback to the road
906 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
908 $aPlaceIDs = $aRoadPlaceIDs;
913 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
915 $sPlaceIDs = join(',',$aPlaceIDs);
917 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
919 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
920 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
921 $sSQL = " and linked_place_id is null";
922 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
923 $sSQL .= " order by rank_search asc limit $iLimit";
924 if (CONST_Debug) var_dump($sSQL);
925 $aPlaceIDs = $oDB->getCol($sSQL);
928 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
930 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
931 $bCacheTable = $oDB->getOne($sSQL);
933 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
935 if (CONST_Debug) var_dump($sSQL);
936 $iMaxRank = ((int)$oDB->getOne($sSQL));
938 // For state / country level searches the normal radius search doesn't work very well
940 if ($iMaxRank < 9 && $bCacheTable)
942 // Try and get a polygon to search in instead
943 $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";
944 if (CONST_Debug) var_dump($sSQL);
945 $sPlaceGeom = $oDB->getOne($sSQL);
955 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
956 if (CONST_Debug) var_dump($sSQL);
957 $aPlaceIDs = $oDB->getCol($sSQL);
958 $sPlaceIDs = join(',',$aPlaceIDs);
961 if ($sPlaceIDs || $sPlaceGeom)
967 // More efficient - can make the range bigger
971 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
972 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
973 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
975 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
976 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
979 $sSQL .= ",placex as f where ";
980 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
985 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
987 if (sizeof($aExcludePlaceIDs))
989 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
991 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
992 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
993 if ($iOffset) $sSQL .= " offset $iOffset";
994 $sSQL .= " limit $iLimit";
995 if (CONST_Debug) var_dump($sSQL);
996 $aPlaceIDs = $oDB->getCol($sSQL);
1000 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1003 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1004 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1006 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1007 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1008 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1009 if (sizeof($aExcludePlaceIDs))
1011 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1013 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1014 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1015 if ($iOffset) $sSQL .= " offset $iOffset";
1016 $sSQL .= " limit $iLimit";
1017 if (CONST_Debug) var_dump($sSQL);
1018 $aPlaceIDs = $oDB->getCol($sSQL);
1026 if (PEAR::IsError($aPlaceIDs))
1028 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1031 if (CONST_Debug) var_Dump($aPlaceIDs);
1033 foreach($aPlaceIDs as $iPlaceID)
1035 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1037 if ($iQueryLoop > 20) break;
1040 if (sizeof($aResultPlaceIDs)) break;
1041 if ($iGroupLoop > 4) break;
1042 if ($iQueryLoop > 30) break;
1045 // Did we find anything?
1046 if (sizeof($aResultPlaceIDs))
1048 //var_Dump($aResultPlaceIDs);exit;
1049 // Get the details for display (is this a redundant extra step?)
1050 $sPlaceIDs = join(',',$aResultPlaceIDs);
1051 $sOrderSQL = 'CASE ';
1052 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1054 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1056 $sOrderSQL .= ' ELSE 10000000 END';
1057 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1058 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1059 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1060 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1061 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1062 // $sSQL .= $sOrderSQL." as porder, ";
1063 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1064 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1065 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1066 $sSQL .= "and linked_place_id is null ";
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 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1108 } // end if ($sQuery)
1111 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1113 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1114 $aResultPlaceIDs = array($iPlaceID);
1116 // TODO: this needs refactoring!
1118 // Get the details for display (is this a redundant extra step?)
1119 $sPlaceIDs = join(',',$aResultPlaceIDs);
1120 $sOrderSQL = 'CASE ';
1121 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1123 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1125 $sOrderSQL .= ' ELSE 10000000 END';
1126 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1127 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1128 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1129 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1130 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1131 // $sSQL .= $sOrderSQL." as porder, ";
1132 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1133 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1134 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1135 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1136 if (!$bDeDupe) $sSQL .= ",place_id";
1137 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1138 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1139 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1141 $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,";
1142 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1143 $sSQL .= "null as placename,";
1144 $sSQL .= "null as ref,";
1145 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1146 // $sSQL .= $sOrderSQL." as porder, ";
1147 $sSQL .= "-0.15 as importance ";
1148 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1149 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1150 $sSQL .= "group by place_id";
1151 if (!$bDeDupe) $sSQL .= ",place_id";
1153 $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,";
1154 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1155 $sSQL .= "null as placename,";
1156 $sSQL .= "null as ref,";
1157 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1158 // $sSQL .= $sOrderSQL." as porder, ";
1159 $sSQL .= "-0.10 as importance ";
1160 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1161 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1162 $sSQL .= "group by place_id";
1163 if (!$bDeDupe) $sSQL .= ",place_id";
1164 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1165 $sSQL .= "order by importance desc";
1166 // $sSQL .= "order by rank_search,rank_address,porder asc";
1167 if (CONST_Debug) var_dump('<hr>',$sSQL);
1168 $aSearchResults = $oDB->getAll($sSQL);
1169 //var_dump($sSQL,$aSearchResults);exit;
1171 if (PEAR::IsError($aSearchResults))
1173 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1179 $sSearchResult = '';
1180 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1182 $sSearchResult = 'No Results Found';
1184 //var_Dump($aSearchResults);
1186 $aClassType = getClassTypesWithImportance();
1187 $aRecheckWords = preg_split('/\b/',$sQuery);
1188 foreach($aRecheckWords as $i => $sWord)
1190 if (!$sWord) unset($aRecheckWords[$i]);
1192 foreach($aSearchResults as $iResNum => $aResult)
1194 if (CONST_Search_AreaPolygons)
1196 // Get the bounding box and outline polygon
1197 $sSQL = "select place_id,numfeatures,area,outline,";
1198 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1199 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1200 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1202 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1203 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1204 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1205 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1206 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1207 $aPointPolygon = $oDB->getRow($sSQL);
1208 if (PEAR::IsError($aPointPolygon))
1210 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1212 if ($aPointPolygon['place_id'])
1214 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1215 $aResult['lat'] = $aPointPolygon['centrelat'];
1216 $aResult['lon'] = $aPointPolygon['centrelon'];
1218 // Translate geometary string to point array
1219 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1221 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1223 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1225 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1227 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1230 $iSteps = ($fRadius * 40000)^2;
1231 $fStepSize = (2*pi())/$iSteps;
1232 $aPolyPoints = array();
1233 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1235 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1237 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1238 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1239 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1240 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1243 // Output data suitable for display (points and a bounding box)
1244 if ($bShowPolygons && isset($aPolyPoints))
1246 $aResult['aPolyPoints'] = array();
1247 foreach($aPolyPoints as $aPoint)
1249 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1252 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1256 if (!isset($aResult['aBoundingBox']))
1259 $fDiameter = 0.0001;
1261 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1262 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1264 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1266 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1267 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1269 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1271 $fRadius = $fDiameter / 2;
1273 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1274 $fStepSize = (2*pi())/$iSteps;
1275 $aPolyPoints = array();
1276 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1278 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1280 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1281 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1282 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1283 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1285 // Output data suitable for display (points and a bounding box)
1288 $aResult['aPolyPoints'] = array();
1289 foreach($aPolyPoints as $aPoint)
1291 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1294 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1297 // Is there an icon set for this type of result?
1298 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1299 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1301 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1304 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1305 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1307 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1310 if ($bShowAddressDetails)
1312 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1313 //var_dump($aResult['address']);
1317 // Adjust importance for the number of exact string matches in the result
1318 $aResult['importance'] = max(0.001,$aResult['importance']);
1320 $sAddress = $aResult['langaddress'];
1321 foreach($aRecheckWords as $i => $sWord)
1323 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1325 $aResult['importance'] = $aResult['importance'] + ($iCountWords*0.1); // 0.1 is a completely arbitrary number but something in the range 0.1 to 0.5 would seem right
1327 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1329 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1330 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1332 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1334 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1335 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1337 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1341 $aResult['importance'] = 1000000000000000;
1344 $aResult['name'] = $aResult['langaddress'];
1345 $aResult['foundorder'] = $iResNum;
1346 $aSearchResults[$iResNum] = $aResult;
1348 uasort($aSearchResults, 'byImportance');
1350 //var_dump($aSearchResults);exit;
1352 $aOSMIDDone = array();
1353 $aClassTypeNameDone = array();
1354 $aToFilter = $aSearchResults;
1355 $aSearchResults = array();
1358 foreach($aToFilter as $iResNum => $aResult)
1360 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1361 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1364 $fLat = $aResult['lat'];
1365 $fLon = $aResult['lon'];
1366 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1369 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1370 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1372 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1373 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1374 $aSearchResults[] = $aResult;
1377 // Absolute limit on number of results
1378 if (sizeof($aSearchResults) >= $iLimit) break;
1381 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1383 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1385 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1390 logEnd($oDB, $hLog, sizeof($aToFilter));
1392 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1393 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1394 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1395 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1396 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1397 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1400 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1402 $sMoreURL .= '&q='.urlencode($sQuery);
1404 if (CONST_Debug) exit;
1406 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');