3 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
4 require_once(CONST_BasePath.'/lib/log.php');
6 ini_set('memory_limit', '200M');
10 $fLat = CONST_Default_Lat;
11 $fLon = CONST_Default_Lon;
12 $iZoom = CONST_Default_Zoom;
13 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
14 $sOutputFormat = 'html';
15 $aSearchResults = array();
16 $aExcludePlaceIDs = array();
17 $sCountryCodesSQL = false;
18 $sSuggestion = $sSuggestionURL = false;
19 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
20 $bReverseInPlan = false;
21 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
22 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
24 if ($iLimit > 100) $iLimit = 100;
26 $iMaxAddressRank = 30;
29 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
31 $sOutputFormat = $_GET['format'];
34 // Show / use polygons
35 $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
37 // Show address breakdown
38 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
41 $aLangPrefOrder = getPreferredLanguages();
42 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
43 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
44 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
46 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
48 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
50 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
52 $iExcludedPlaceID = (int)$iExcludedPlaceID;
53 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
57 // Only certain ranks of feature
58 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
60 if (isset($_GET['featuretype']))
62 switch($_GET['featuretype'])
65 $iMinAddressRank = $iMaxAddressRank = 4;
68 $iMinAddressRank = $iMaxAddressRank = 8;
71 $iMinAddressRank = 14;
72 $iMaxAddressRank = 16;
76 $iMaxAddressRank = 20;
81 if (isset($_GET['countrycodes']))
83 $aCountryCodes = array();
84 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
86 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
88 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
91 $sCountryCodesSQL = join(',', $aCountryCodes);
95 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
96 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
98 $sQuery = substr($_SERVER['PATH_INFO'], 1);
100 // reverse order of '/' separated string
101 $aPhrases = explode('/', $sQuery);
102 $aPhrases = array_reverse($aPhrases);
103 $sQuery = join(', ',$aPhrases);
106 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
108 if (!isset($_GET[$sKey])) return false;
109 $sValue = trim($_GET[$sKey]);
110 if (!$sValue) return false;
111 $aStructuredQuery[$sKey] = $sValue;
112 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
113 $iMinAddressRank = $iNewMinAddressRank;
114 $iMaxAddressRank = $iNewMaxAddressRank;
120 $aStructuredOptions = array(
121 array('amenity', 26, 30),
122 array('street', 26, 30),
123 array('city', 14, 24),
124 array('county', 9, 13),
125 array('state', 8, 8),
126 array('country', 4, 4),
127 array('postalcode', 16, 25),
129 $aStructuredQuery = array();
130 foreach($aStructuredOptions as $aStructuredOption)
132 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
134 if (sizeof($aStructuredQuery) > 0) {
135 $sQuery = join(', ', $aStructuredQuery);
140 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
142 // Hack to make it handle "new york, ny" (and variants) correctly
143 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
144 if (isset($aLangPrefOrder['name:en']))
146 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
147 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
148 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
151 // If we have a view box create the SQL
152 // Small is the actual view box, Large is double (on each axis) that
153 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
154 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
156 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
157 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
159 if (isset($_GET['viewbox']) && $_GET['viewbox'])
161 $aCoOrdinates = explode(',',$_GET['viewbox']);
162 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
163 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
164 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
165 $aCoOrdinates[0] += $fHeight;
166 $aCoOrdinates[2] -= $fHeight;
167 $aCoOrdinates[1] += $fWidth;
168 $aCoOrdinates[3] -= $fWidth;
169 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
171 $bBoundingBoxSearch = false;
173 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
175 $aPoints = explode(',',$_GET['route']);
176 if (sizeof($aPoints) % 2 != 0)
178 echo "Uneven number of points";
181 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
183 foreach($aPoints as $i => $fPoint)
187 if ($i != 1) $sViewboxCentreSQL .= ",";
188 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
192 $fPrevCoord = (float)$fPoint;
195 $sViewboxCentreSQL .= ")'::geometry,4326)";
197 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
198 $sViewboxSmallSQL = $oDB->getOne($sSQL);
199 if (PEAR::isError($sViewboxSmallSQL))
201 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
203 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
205 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
206 $sViewboxLargeSQL = $oDB->getOne($sSQL);
207 if (PEAR::isError($sViewboxLargeSQL))
209 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
211 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
214 // Do we have anything that looks like a lat/lon pair?
215 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
217 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
218 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
219 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
221 $_GET['nearlat'] = $fQueryLat;
222 $_GET['nearlon'] = $fQueryLon;
223 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
226 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
228 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
229 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
230 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
232 $_GET['nearlat'] = $fQueryLat;
233 $_GET['nearlon'] = $fQueryLon;
234 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
237 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
239 $fQueryLat = $aData[2];
240 $fQueryLon = $aData[3];
241 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
243 $_GET['nearlat'] = $fQueryLat;
244 $_GET['nearlon'] = $fQueryLon;
245 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
249 if ($sQuery || $aStructuredQuery)
251 // Start with a blank search
253 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
254 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
257 $sNearPointSQL = false;
258 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
260 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
261 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
262 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
263 $aSearches[0]['fRadius'] = 0.1;
266 $bSpecialTerms = false;
267 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
268 $aSpecialTerms = array();
269 foreach($aSpecialTermsRaw as $aSpecialTerm)
271 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
272 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
275 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
276 $aSpecialTerms = array();
277 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
279 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
280 unset($aStructuredQuery['amenity']);
282 foreach($aSpecialTermsRaw as $aSpecialTerm)
284 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
285 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
286 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
287 $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';
288 if (CONST_Debug) var_Dump($sSQL);
289 $aSearchWords = $oDB->getAll($sSQL);
290 $aNewSearches = array();
291 foreach($aSearches as $aSearch)
293 foreach($aSearchWords as $aSearchTerm)
295 $aNewSearch = $aSearch;
296 if ($aSearchTerm['country_code'])
298 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
299 $aNewSearches[] = $aNewSearch;
300 $bSpecialTerms = true;
302 if ($aSearchTerm['class'])
304 $aNewSearch['sClass'] = $aSearchTerm['class'];
305 $aNewSearch['sType'] = $aSearchTerm['type'];
306 $aNewSearches[] = $aNewSearch;
307 $bSpecialTerms = true;
311 $aSearches = $aNewSearches;
314 // Split query into phrases
315 // Commas are used to reduce the search space by indicating where phrases split
316 if (sizeof($aStructuredQuery) > 0)
318 $aPhrases = $aStructuredQuery;
319 $bStructuredPhrases = true;
323 $aPhrases = explode(',',$sQuery);
324 $bStructuredPhrases = false;
328 // Convert each phrase to standard form
329 // Create a list of standard words
330 // Get all 'sets' of words
331 // Generate a complete list of all
333 foreach($aPhrases as $iPhrase => $sPhrase)
335 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
336 if (PEAR::isError($aPhrase))
338 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
339 if (CONST_Debug) var_dump($aPhrase);
342 if (trim($aPhrase['string']))
344 $aPhrases[$iPhrase] = $aPhrase;
345 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
346 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
347 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
351 unset($aPhrases[$iPhrase]);
355 // reindex phrases - we make assumptions later on
356 $aPhraseTypes = array_keys($aPhrases);
357 $aPhrases = array_values($aPhrases);
359 if (sizeof($aTokens))
362 // Check which tokens we have, get the ID numbers
363 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
364 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
365 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
366 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
368 if (CONST_Debug) var_Dump($sSQL);
370 $aValidTokens = array();
371 if (sizeof($aTokens))
372 $aDatabaseWords = $oDB->getAll($sSQL);
374 $aDatabaseWords = array();
375 if (PEAR::IsError($aDatabaseWords))
377 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
379 $aPossibleMainWordIDs = array();
380 foreach($aDatabaseWords as $aToken)
382 if (isset($aValidTokens[$aToken['word_token']]))
384 $aValidTokens[$aToken['word_token']][] = $aToken;
388 $aValidTokens[$aToken['word_token']] = array($aToken);
390 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
392 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
394 $aSuggestion = array();
395 $bSuggestion = false;
396 if (CONST_Suggestions_Enabled)
398 foreach($aPhrases as $iPhrase => $aPhrase)
400 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
402 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
403 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
404 $aRow = $aSuggestionWords[0];
405 if ($aRow && $aRow['word'])
407 $aSuggestion[] = $aRow['word'];
412 $aSuggestion[] = $aPhrase['string'];
417 $aSuggestion[] = $aPhrase['string'];
421 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
423 // Try and calculate GB postcodes we might be missing
424 foreach($aTokens as $sToken)
426 // Source of gb postcodes is now definitive - always use
427 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
429 if (substr($aData[1],-2,1) != ' ')
431 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
432 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
434 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
435 if ($aGBPostcodeLocation)
437 $aValidTokens[$sToken] = $aGBPostcodeLocation;
442 foreach($aTokens as $sToken)
444 // Unknown single word token with a number - assume it is a house number
445 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
447 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
451 // Any words that have failed completely?
454 // Start the search process
455 $aResultPlaceIDs = array();
458 Calculate all searches using aValidTokens i.e.
460 'Wodsworth Road, Sheffield' =>
464 0 1 (wodsworth)(road)
467 Score how good the search is so they can be ordered
469 foreach($aPhrases as $iPhrase => $sPhrase)
471 $aNewPhraseSearches = array();
472 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
473 else $sPhraseType = '';
475 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
477 $aWordsetSearches = $aSearches;
479 // Add all words from this wordset
480 foreach($aWordset as $iToken => $sToken)
482 //echo "<br><b>$sToken</b>";
483 $aNewWordsetSearches = array();
485 foreach($aWordsetSearches as $aCurrentSearch)
488 //var_dump($aCurrentSearch);
491 // If the token is valid
492 if (isset($aValidTokens[' '.$sToken]))
494 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
496 $aSearch = $aCurrentSearch;
497 $aSearch['iSearchRank']++;
498 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
500 if ($aSearch['sCountryCode'] === false)
502 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
503 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
504 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
505 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
508 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
510 if ($aSearch['fLat'] === '')
512 $aSearch['fLat'] = $aSearchTerm['lat'];
513 $aSearch['fLon'] = $aSearchTerm['lon'];
514 $aSearch['fRadius'] = $aSearchTerm['radius'];
515 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
518 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
520 if ($aSearch['sHouseNumber'] === '')
522 $aSearch['sHouseNumber'] = $sToken;
523 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
525 // Fall back to not searching for this item (better than nothing)
526 $aSearch = $aCurrentSearch;
527 $aSearch['iSearchRank'] += 1;
528 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
532 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
534 if ($aSearch['sClass'] === '')
536 $aSearch['sOperator'] = $aSearchTerm['operator'];
537 $aSearch['sClass'] = $aSearchTerm['class'];
538 $aSearch['sType'] = $aSearchTerm['type'];
539 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
540 else $aSearch['sOperator'] = 'near'; // near = in for the moment
542 // Do we have a shortcut id?
543 if ($aSearch['sOperator'] == 'name')
545 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
546 if ($iAmenityID = $oDB->getOne($sSQL))
548 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
549 $aSearch['aName'][$iAmenityID] = $iAmenityID;
550 $aSearch['sClass'] = '';
551 $aSearch['sType'] = '';
554 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
557 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
559 if (sizeof($aSearch['aName']))
561 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
563 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
567 $aSearch['iSearchRank'] += 1000; // skip;
572 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
573 // $aSearch['iNamePhrase'] = $iPhrase;
575 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
579 if (isset($aValidTokens[$sToken]))
581 // Allow searching for a word - but at extra cost
582 foreach($aValidTokens[$sToken] as $aSearchTerm)
584 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
586 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
588 $aSearch = $aCurrentSearch;
589 $aSearch['iSearchRank'] += 1;
590 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
591 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
594 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
596 $aSearch = $aCurrentSearch;
597 $aSearch['iSearchRank'] += 2;
598 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
599 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
600 $aSearch['iNamePhrase'] = $iPhrase;
601 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
608 // Allow skipping a word - but at EXTREAM cost
609 //$aSearch = $aCurrentSearch;
610 //$aSearch['iSearchRank']+=100;
611 //$aNewWordsetSearches[] = $aSearch;
615 usort($aNewWordsetSearches, 'bySearchRank');
616 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
618 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
620 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
621 usort($aNewPhraseSearches, 'bySearchRank');
623 $aSearchHash = array();
624 foreach($aNewPhraseSearches as $iSearch => $aSearch)
626 $sHash = serialize($aSearch);
627 if (isset($aSearchHash[$sHash]))
629 unset($aNewPhraseSearches[$iSearch]);
633 $aSearchHash[$sHash] = 1;
637 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
640 // Re-group the searches by their score, junk anything over 20 as just not worth trying
641 $aGroupedSearches = array();
642 foreach($aNewPhraseSearches as $aSearch)
644 if ($aSearch['iSearchRank'] < $iMaxRank)
646 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
647 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
650 ksort($aGroupedSearches);
653 $aSearches = array();
654 foreach($aGroupedSearches as $iScore => $aNewSearches)
656 $iSearchCount += sizeof($aNewSearches);
657 $aSearches = array_merge($aSearches, $aNewSearches);
658 if ($iSearchCount > 50) break;
661 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
667 // Re-group the searches by their score, junk anything over 20 as just not worth trying
668 $aGroupedSearches = array();
669 foreach($aSearches as $aSearch)
671 if ($aSearch['iSearchRank'] < $iMaxRank)
673 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
674 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
677 ksort($aGroupedSearches);
680 if (CONST_Debug) var_Dump($aGroupedSearches);
684 $aCopyGroupedSearches = $aGroupedSearches;
685 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
687 foreach($aSearches as $iSearch => $aSearch)
689 if (sizeof($aSearch['aAddress']))
691 $iReverseItem = array_pop($aSearch['aAddress']);
692 if (isset($aPossibleMainWordIDs[$iReverseItem]))
694 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
695 $aSearch['aName'] = array($iReverseItem);
696 $aGroupedSearches[$iGroup][] = $aSearch;
698 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
699 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
705 // Filter out duplicate searches
706 $aSearchHash = array();
707 foreach($aGroupedSearches as $iGroup => $aSearches)
709 foreach($aSearches as $iSearch => $aSearch)
711 $sHash = serialize($aSearch);
712 if (isset($aSearchHash[$sHash]))
714 unset($aGroupedSearches[$iGroup][$iSearch]);
715 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
719 $aSearchHash[$sHash] = 1;
724 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
728 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
731 foreach($aSearches as $aSearch)
735 // Must have a location term
736 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
738 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
740 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
742 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
743 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
744 $sSQL .= " order by st_area(geometry) desc limit 1";
745 $aPlaceIDs = $oDB->getCol($sSQL);
750 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
751 if (!$aSearch['sClass']) continue;
752 if (CONST_Debug) var_dump('<hr>',$aSearch);
753 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
755 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
756 if ($oDB->getOne($sSQL))
758 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
759 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
760 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
761 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
762 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
763 $sSQL .= " limit $iLimit";
764 if (CONST_Debug) var_dump($sSQL);
765 $aPlaceIDs = $oDB->getCol($sSQL);
767 if (!sizeof($aPlaceIDs))
769 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
770 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
771 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
772 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
773 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
774 $sSQL .= " limit $iLimit";
775 if (CONST_Debug) var_dump($sSQL);
776 $aPlaceIDs = $oDB->getCol($sSQL);
781 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
782 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
783 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
784 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
785 $sSQL .= " limit $iLimit";
786 if (CONST_Debug) var_dump($sSQL);
787 $aPlaceIDs = $oDB->getCol($sSQL);
793 if (CONST_Debug) var_dump('<hr>',$aSearch);
794 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
795 $aPlaceIDs = array();
797 // First we need a position, either aName or fLat or both
801 // TODO: filter out the pointless search terms (2 letter name tokens and less)
802 // they might be right - but they are just too darned expensive to run
803 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
804 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
805 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
806 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
807 if ($aSearch['fLon'] && $aSearch['fLat'])
809 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
810 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
812 if (sizeof($aExcludePlaceIDs))
814 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
816 if ($sCountryCodesSQL)
818 $aTerms[] = "country_code in ($sCountryCodesSQL)";
821 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
822 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
824 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
826 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
827 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
828 $aOrder[] = "$sImportanceSQL DESC";
832 $sSQL = "select place_id";
833 $sSQL .= " from search_name";
834 $sSQL .= " where ".join(' and ',$aTerms);
835 $sSQL .= " order by ".join(', ',$aOrder);
836 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
837 $sSQL .= " limit 50";
838 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
841 $sSQL .= " limit ".$iLimit;
843 if (CONST_Debug) var_dump($sSQL);
844 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
845 if (PEAR::IsError($aViewBoxPlaceIDs))
847 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
849 //var_dump($aViewBoxPlaceIDs);
850 // Did we have an viewbox matches?
851 $aPlaceIDs = array();
852 $bViewBoxMatch = false;
853 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
855 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
856 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
857 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
858 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
859 $aPlaceIDs[] = $aViewBoxRow['place_id'];
862 //var_Dump($aPlaceIDs);
865 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
867 $aRoadPlaceIDs = $aPlaceIDs;
868 $sPlaceIDs = join(',',$aPlaceIDs);
870 // Now they are indexed look for a house attached to a street we found
871 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
872 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
873 if (sizeof($aExcludePlaceIDs))
875 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
877 $sSQL .= " limit $iLimit";
878 if (CONST_Debug) var_dump($sSQL);
879 $aPlaceIDs = $oDB->getCol($sSQL);
881 // If not try the aux fallback table
882 if (!sizeof($aPlaceIDs))
884 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
885 if (sizeof($aExcludePlaceIDs))
887 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
889 // $sSQL .= " limit $iLimit";
890 if (CONST_Debug) var_dump($sSQL);
891 $aPlaceIDs = $oDB->getCol($sSQL);
894 if (!sizeof($aPlaceIDs))
896 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
897 if (sizeof($aExcludePlaceIDs))
899 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
901 // $sSQL .= " limit $iLimit";
902 if (CONST_Debug) var_dump($sSQL);
903 $aPlaceIDs = $oDB->getCol($sSQL);
906 // Fallback to the road
907 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
909 $aPlaceIDs = $aRoadPlaceIDs;
914 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
916 $sPlaceIDs = join(',',$aPlaceIDs);
918 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
920 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
921 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
922 $sSQL = " and linked_place_id is null";
923 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
924 $sSQL .= " order by rank_search asc limit $iLimit";
925 if (CONST_Debug) var_dump($sSQL);
926 $aPlaceIDs = $oDB->getCol($sSQL);
929 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
931 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
932 $bCacheTable = $oDB->getOne($sSQL);
934 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
936 if (CONST_Debug) var_dump($sSQL);
937 $iMaxRank = ((int)$oDB->getOne($sSQL));
939 // For state / country level searches the normal radius search doesn't work very well
941 if ($iMaxRank < 9 && $bCacheTable)
943 // Try and get a polygon to search in instead
944 $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";
945 if (CONST_Debug) var_dump($sSQL);
946 $sPlaceGeom = $oDB->getOne($sSQL);
956 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
957 if (CONST_Debug) var_dump($sSQL);
958 $aPlaceIDs = $oDB->getCol($sSQL);
959 $sPlaceIDs = join(',',$aPlaceIDs);
962 if ($sPlaceIDs || $sPlaceGeom)
968 // More efficient - can make the range bigger
972 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
973 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
974 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
976 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
977 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
980 $sSQL .= ",placex as f where ";
981 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
986 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
988 if (sizeof($aExcludePlaceIDs))
990 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
992 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
993 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
994 if ($iOffset) $sSQL .= " offset $iOffset";
995 $sSQL .= " limit $iLimit";
996 if (CONST_Debug) var_dump($sSQL);
997 $aPlaceIDs = $oDB->getCol($sSQL);
1001 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1004 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1005 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1007 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1008 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1009 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1010 if (sizeof($aExcludePlaceIDs))
1012 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1014 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1015 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1016 if ($iOffset) $sSQL .= " offset $iOffset";
1017 $sSQL .= " limit $iLimit";
1018 if (CONST_Debug) var_dump($sSQL);
1019 $aPlaceIDs = $oDB->getCol($sSQL);
1027 if (PEAR::IsError($aPlaceIDs))
1029 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1032 if (CONST_Debug) var_Dump($aPlaceIDs);
1034 foreach($aPlaceIDs as $iPlaceID)
1036 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1038 if ($iQueryLoop > 20) break;
1041 if (sizeof($aResultPlaceIDs)) break;
1042 if ($iGroupLoop > 4) break;
1043 if ($iQueryLoop > 30) break;
1046 // Did we find anything?
1047 if (sizeof($aResultPlaceIDs))
1049 //var_Dump($aResultPlaceIDs);exit;
1050 // Get the details for display (is this a redundant extra step?)
1051 $sPlaceIDs = join(',',$aResultPlaceIDs);
1052 $sOrderSQL = 'CASE ';
1053 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1055 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1057 $sOrderSQL .= ' ELSE 10000000 END';
1058 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1059 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1060 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1061 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1062 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1063 // $sSQL .= $sOrderSQL." as porder, ";
1064 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1065 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1066 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1067 $sSQL .= "and linked_place_id is null ";
1068 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1069 if (!$bDeDupe) $sSQL .= ",place_id";
1070 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1071 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1072 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1074 $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,";
1075 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1076 $sSQL .= "null as placename,";
1077 $sSQL .= "null as ref,";
1078 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1079 // $sSQL .= $sOrderSQL." as porder, ";
1080 $sSQL .= "-0.15 as importance ";
1081 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1082 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1083 $sSQL .= "group by place_id";
1084 if (!$bDeDupe) $sSQL .= ",place_id";
1086 $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,";
1087 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1088 $sSQL .= "null as placename,";
1089 $sSQL .= "null as ref,";
1090 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1091 // $sSQL .= $sOrderSQL." as porder, ";
1092 $sSQL .= "-0.10 as importance ";
1093 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1094 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1095 $sSQL .= "group by place_id";
1096 if (!$bDeDupe) $sSQL .= ",place_id";
1097 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1098 $sSQL .= "order by importance desc";
1099 // $sSQL .= "order by rank_search,rank_address,porder asc";
1100 if (CONST_Debug) var_dump('<hr>',$sSQL);
1101 $aSearchResults = $oDB->getAll($sSQL);
1102 //var_dump($sSQL,$aSearchResults);exit;
1104 if (PEAR::IsError($aSearchResults))
1106 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1109 } // end if ($sQuery)
1112 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1114 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1115 $aResultPlaceIDs = array($iPlaceID);
1117 // TODO: this needs refactoring!
1119 // Get the details for display (is this a redundant extra step?)
1120 $sPlaceIDs = join(',',$aResultPlaceIDs);
1121 $sOrderSQL = 'CASE ';
1122 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1124 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1126 $sOrderSQL .= ' ELSE 10000000 END';
1127 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1128 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1129 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1130 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1131 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1132 // $sSQL .= $sOrderSQL." as porder, ";
1133 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1134 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1135 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1136 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1137 if (!$bDeDupe) $sSQL .= ",place_id";
1138 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1139 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1140 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1142 $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,";
1143 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1144 $sSQL .= "null as placename,";
1145 $sSQL .= "null as ref,";
1146 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1147 // $sSQL .= $sOrderSQL." as porder, ";
1148 $sSQL .= "-0.15 as importance ";
1149 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1150 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1151 $sSQL .= "group by place_id";
1152 if (!$bDeDupe) $sSQL .= ",place_id";
1154 $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,";
1155 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1156 $sSQL .= "null as placename,";
1157 $sSQL .= "null as ref,";
1158 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1159 // $sSQL .= $sOrderSQL." as porder, ";
1160 $sSQL .= "-0.10 as importance ";
1161 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1162 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1163 $sSQL .= "group by place_id";
1164 if (!$bDeDupe) $sSQL .= ",place_id";
1165 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1166 $sSQL .= "order by importance desc";
1167 // $sSQL .= "order by rank_search,rank_address,porder asc";
1168 if (CONST_Debug) var_dump('<hr>',$sSQL);
1169 $aSearchResults = $oDB->getAll($sSQL);
1170 //var_dump($sSQL,$aSearchResults);exit;
1172 if (PEAR::IsError($aSearchResults))
1174 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1180 $sSearchResult = '';
1181 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1183 $sSearchResult = 'No Results Found';
1185 //var_Dump($aSearchResults);
1187 $aClassType = getClassTypesWithImportance();
1188 $aRecheckWords = preg_split('/\b/',$sQuery);
1189 foreach($aRecheckWords as $i => $sWord)
1191 if (!$sWord) unset($aRecheckWords[$i]);
1193 foreach($aSearchResults as $iResNum => $aResult)
1195 if (CONST_Search_AreaPolygons)
1197 // Get the bounding box and outline polygon
1198 $sSQL = "select place_id,numfeatures,area,outline,";
1199 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1200 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1201 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1203 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1204 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1205 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1206 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon,";
1207 $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1208 $aPointPolygon = $oDB->getRow($sSQL);
1209 if (PEAR::IsError($aPointPolygon))
1211 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1213 if ($aPointPolygon['place_id'])
1215 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1216 $aResult['lat'] = $aPointPolygon['centrelat'];
1217 $aResult['lon'] = $aPointPolygon['centrelon'];
1219 // Translate geometary string to point array
1220 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1222 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1224 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1227 $iSteps = ($fRadius * 40000)^2;
1228 $fStepSize = (2*pi())/$iSteps;
1229 $aPolyPoints = array();
1230 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1232 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1234 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1235 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1236 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1237 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1240 // Output data suitable for display (points and a bounding box)
1241 if ($bShowPolygons && isset($aPolyPoints))
1243 $aResult['aPolyPoints'] = array();
1244 foreach($aPolyPoints as $aPoint)
1246 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1249 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1253 if (!isset($aResult['aBoundingBox']))
1256 $fDiameter = 0.0001;
1258 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1259 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1261 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1263 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1264 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1266 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1268 $fRadius = $fDiameter / 2;
1270 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1271 $fStepSize = (2*pi())/$iSteps;
1272 $aPolyPoints = array();
1273 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1275 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1277 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1278 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1279 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1280 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1282 // Output data suitable for display (points and a bounding box)
1285 $aResult['aPolyPoints'] = array();
1286 foreach($aPolyPoints as $aPoint)
1288 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1291 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1294 // Is there an icon set for this type of result?
1295 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1296 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1298 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1301 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1302 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1304 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1307 if ($bShowAddressDetails)
1309 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1310 //var_dump($aResult['address']);
1314 // Adjust importance for the number of exact string matches in the result
1315 $aResult['importance'] = max(0.001,$aResult['importance']);
1317 $sAddress = $aResult['langaddress'];
1318 foreach($aRecheckWords as $i => $sWord)
1320 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1322 $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
1324 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1326 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1327 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1329 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1331 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1332 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1334 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1338 $aResult['importance'] = 1000000000000000;
1341 $aResult['name'] = $aResult['langaddress'];
1342 $aResult['foundorder'] = $iResNum;
1343 $aSearchResults[$iResNum] = $aResult;
1345 uasort($aSearchResults, 'byImportance');
1347 //var_dump($aSearchResults);exit;
1349 $aOSMIDDone = array();
1350 $aClassTypeNameDone = array();
1351 $aToFilter = $aSearchResults;
1352 $aSearchResults = array();
1355 foreach($aToFilter as $iResNum => $aResult)
1357 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1358 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1361 $fLat = $aResult['lat'];
1362 $fLon = $aResult['lon'];
1363 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1366 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1367 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1369 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1370 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1371 $aSearchResults[] = $aResult;
1374 // Absolute limit on number of results
1375 if (sizeof($aSearchResults) >= $iLimit) break;
1378 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1380 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1382 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1387 logEnd($oDB, $hLog, sizeof($aToFilter));
1389 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1390 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1391 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1392 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1393 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1394 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1397 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1399 $sMoreURL .= '&q='.urlencode($sQuery);
1401 if (CONST_Debug) exit;
1403 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');