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 = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
35 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
36 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
37 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
38 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
39 if ((($bShowPolygons?1:0)
44 ) > CONST_PolygonOutput_MaximumTypes) {
45 if (CONST_PolygonOutput_MaximumTypes) {
46 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
48 userError("Polygon output is disabled");
53 // Show address breakdown
54 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
57 $aLangPrefOrder = getPreferredLanguages();
58 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
59 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
60 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
62 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
64 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
66 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
68 $iExcludedPlaceID = (int)$iExcludedPlaceID;
69 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
73 // Only certain ranks of feature
74 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
76 if (isset($_GET['featuretype']))
78 switch($_GET['featuretype'])
81 $iMinAddressRank = $iMaxAddressRank = 4;
84 $iMinAddressRank = $iMaxAddressRank = 8;
87 $iMinAddressRank = 14;
88 $iMaxAddressRank = 16;
92 $iMaxAddressRank = 20;
97 if (isset($_GET['countrycodes']))
99 $aCountryCodes = array();
100 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
102 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
104 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
107 $sCountryCodesSQL = join(',', $aCountryCodes);
111 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
112 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
114 $sQuery = substr($_SERVER['PATH_INFO'], 1);
116 // reverse order of '/' separated string
117 $aPhrases = explode('/', $sQuery);
118 $aPhrases = array_reverse($aPhrases);
119 $sQuery = join(', ',$aPhrases);
122 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
124 if (!isset($_GET[$sKey])) return false;
125 $sValue = trim($_GET[$sKey]);
126 if (!$sValue) return false;
127 $aStructuredQuery[$sKey] = $sValue;
128 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
129 $iMinAddressRank = $iNewMinAddressRank;
130 $iMaxAddressRank = $iNewMaxAddressRank;
136 $aStructuredOptions = array(
137 array('amenity', 26, 30),
138 array('street', 26, 30),
139 array('city', 14, 24),
140 array('county', 9, 13),
141 array('state', 8, 8),
142 array('country', 4, 4),
143 array('postalcode', 16, 25),
145 $aStructuredQuery = array();
146 foreach($aStructuredOptions as $aStructuredOption)
148 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
150 if (sizeof($aStructuredQuery) > 0) {
151 $sQuery = join(', ', $aStructuredQuery);
156 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
158 // Hack to make it handle "new york, ny" (and variants) correctly
159 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
160 if (isset($aLangPrefOrder['name:en']))
162 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
163 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
164 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
167 // If we have a view box create the SQL
168 // Small is the actual view box, Large is double (on each axis) that
169 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
170 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
172 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
173 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
175 if (isset($_GET['viewbox']) && $_GET['viewbox'])
177 $aCoOrdinates = explode(',',$_GET['viewbox']);
178 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
179 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
180 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
181 $aCoOrdinates[0] += $fHeight;
182 $aCoOrdinates[2] -= $fHeight;
183 $aCoOrdinates[1] += $fWidth;
184 $aCoOrdinates[3] -= $fWidth;
185 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
187 $bBoundingBoxSearch = false;
189 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
191 $aPoints = explode(',',$_GET['route']);
192 if (sizeof($aPoints) % 2 != 0)
194 userError("Uneven number of points");
197 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
199 foreach($aPoints as $i => $fPoint)
203 if ($i != 1) $sViewboxCentreSQL .= ",";
204 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
208 $fPrevCoord = (float)$fPoint;
211 $sViewboxCentreSQL .= ")'::geometry,4326)";
213 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
214 $sViewboxSmallSQL = $oDB->getOne($sSQL);
215 if (PEAR::isError($sViewboxSmallSQL))
217 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
219 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
221 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
222 $sViewboxLargeSQL = $oDB->getOne($sSQL);
223 if (PEAR::isError($sViewboxLargeSQL))
225 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
227 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
230 // Do we have anything that looks like a lat/lon pair?
231 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
233 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
234 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
235 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
237 $_GET['nearlat'] = $fQueryLat;
238 $_GET['nearlon'] = $fQueryLon;
239 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
242 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
244 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
245 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
246 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
248 $_GET['nearlat'] = $fQueryLat;
249 $_GET['nearlon'] = $fQueryLon;
250 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
253 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
255 $fQueryLat = $aData[2];
256 $fQueryLon = $aData[3];
257 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
259 $_GET['nearlat'] = $fQueryLat;
260 $_GET['nearlon'] = $fQueryLon;
261 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
265 if ($sQuery || $aStructuredQuery)
267 // Start with a blank search
269 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
270 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
273 $sNearPointSQL = false;
274 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
276 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
277 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
278 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
279 $aSearches[0]['fRadius'] = 0.1;
282 $bSpecialTerms = false;
283 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
284 $aSpecialTerms = array();
285 foreach($aSpecialTermsRaw as $aSpecialTerm)
287 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
288 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
291 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
292 $aSpecialTerms = array();
293 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
295 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
296 unset($aStructuredQuery['amenity']);
298 foreach($aSpecialTermsRaw as $aSpecialTerm)
300 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
301 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
302 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
303 $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';
304 if (CONST_Debug) var_Dump($sSQL);
305 $aSearchWords = $oDB->getAll($sSQL);
306 $aNewSearches = array();
307 foreach($aSearches as $aSearch)
309 foreach($aSearchWords as $aSearchTerm)
311 $aNewSearch = $aSearch;
312 if ($aSearchTerm['country_code'])
314 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
315 $aNewSearches[] = $aNewSearch;
316 $bSpecialTerms = true;
318 if ($aSearchTerm['class'])
320 $aNewSearch['sClass'] = $aSearchTerm['class'];
321 $aNewSearch['sType'] = $aSearchTerm['type'];
322 $aNewSearches[] = $aNewSearch;
323 $bSpecialTerms = true;
327 $aSearches = $aNewSearches;
330 // Split query into phrases
331 // Commas are used to reduce the search space by indicating where phrases split
332 if (sizeof($aStructuredQuery) > 0)
334 $aPhrases = $aStructuredQuery;
335 $bStructuredPhrases = true;
339 $aPhrases = explode(',',$sQuery);
340 $bStructuredPhrases = false;
344 // Convert each phrase to standard form
345 // Create a list of standard words
346 // Get all 'sets' of words
347 // Generate a complete list of all
349 foreach($aPhrases as $iPhrase => $sPhrase)
351 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
352 if (PEAR::isError($aPhrase))
354 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
355 if (CONST_Debug) var_dump($aPhrase);
358 if (trim($aPhrase['string']))
360 $aPhrases[$iPhrase] = $aPhrase;
361 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
362 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
363 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
367 unset($aPhrases[$iPhrase]);
371 // reindex phrases - we make assumptions later on
372 $aPhraseTypes = array_keys($aPhrases);
373 $aPhrases = array_values($aPhrases);
375 if (sizeof($aTokens))
378 // Check which tokens we have, get the ID numbers
379 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
380 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
381 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
382 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
384 if (CONST_Debug) var_Dump($sSQL);
386 $aValidTokens = array();
387 if (sizeof($aTokens))
388 $aDatabaseWords = $oDB->getAll($sSQL);
390 $aDatabaseWords = array();
391 if (PEAR::IsError($aDatabaseWords))
393 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
395 $aPossibleMainWordIDs = array();
396 foreach($aDatabaseWords as $aToken)
398 if (isset($aValidTokens[$aToken['word_token']]))
400 $aValidTokens[$aToken['word_token']][] = $aToken;
404 $aValidTokens[$aToken['word_token']] = array($aToken);
406 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
408 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
410 $aSuggestion = array();
411 $bSuggestion = false;
412 if (CONST_Suggestions_Enabled)
414 foreach($aPhrases as $iPhrase => $aPhrase)
416 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
418 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
419 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
420 $aRow = $aSuggestionWords[0];
421 if ($aRow && $aRow['word'])
423 $aSuggestion[] = $aRow['word'];
428 $aSuggestion[] = $aPhrase['string'];
433 $aSuggestion[] = $aPhrase['string'];
437 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
439 // Try and calculate GB postcodes we might be missing
440 foreach($aTokens as $sToken)
442 // Source of gb postcodes is now definitive - always use
443 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
445 if (substr($aData[1],-2,1) != ' ')
447 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
448 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
450 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
451 if ($aGBPostcodeLocation)
453 $aValidTokens[$sToken] = $aGBPostcodeLocation;
458 foreach($aTokens as $sToken)
460 // Unknown single word token with a number - assume it is a house number
461 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
463 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
467 // Any words that have failed completely?
470 // Start the search process
471 $aResultPlaceIDs = array();
474 Calculate all searches using aValidTokens i.e.
476 'Wodsworth Road, Sheffield' =>
480 0 1 (wodsworth)(road)
483 Score how good the search is so they can be ordered
485 foreach($aPhrases as $iPhrase => $sPhrase)
487 $aNewPhraseSearches = array();
488 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
489 else $sPhraseType = '';
491 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
493 $aWordsetSearches = $aSearches;
495 // Add all words from this wordset
496 foreach($aWordset as $iToken => $sToken)
498 //echo "<br><b>$sToken</b>";
499 $aNewWordsetSearches = array();
501 foreach($aWordsetSearches as $aCurrentSearch)
504 //var_dump($aCurrentSearch);
507 // If the token is valid
508 if (isset($aValidTokens[' '.$sToken]))
510 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
512 $aSearch = $aCurrentSearch;
513 $aSearch['iSearchRank']++;
514 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
516 if ($aSearch['sCountryCode'] === false)
518 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
519 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
520 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
521 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
524 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
526 if ($aSearch['fLat'] === '')
528 $aSearch['fLat'] = $aSearchTerm['lat'];
529 $aSearch['fLon'] = $aSearchTerm['lon'];
530 $aSearch['fRadius'] = $aSearchTerm['radius'];
531 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
534 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
536 if ($aSearch['sHouseNumber'] === '')
538 $aSearch['sHouseNumber'] = $sToken;
539 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
541 // Fall back to not searching for this item (better than nothing)
542 $aSearch = $aCurrentSearch;
543 $aSearch['iSearchRank'] += 1;
544 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
548 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
550 if ($aSearch['sClass'] === '')
552 $aSearch['sOperator'] = $aSearchTerm['operator'];
553 $aSearch['sClass'] = $aSearchTerm['class'];
554 $aSearch['sType'] = $aSearchTerm['type'];
555 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
556 else $aSearch['sOperator'] = 'near'; // near = in for the moment
558 // Do we have a shortcut id?
559 if ($aSearch['sOperator'] == 'name')
561 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
562 if ($iAmenityID = $oDB->getOne($sSQL))
564 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
565 $aSearch['aName'][$iAmenityID] = $iAmenityID;
566 $aSearch['sClass'] = '';
567 $aSearch['sType'] = '';
570 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
573 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
575 if (sizeof($aSearch['aName']))
577 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
579 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
583 $aSearch['iSearchRank'] += 1000; // skip;
588 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
589 // $aSearch['iNamePhrase'] = $iPhrase;
591 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
595 if (isset($aValidTokens[$sToken]))
597 // Allow searching for a word - but at extra cost
598 foreach($aValidTokens[$sToken] as $aSearchTerm)
600 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
602 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
604 $aSearch = $aCurrentSearch;
605 $aSearch['iSearchRank'] += 1;
606 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
607 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
610 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
612 $aSearch = $aCurrentSearch;
613 $aSearch['iSearchRank'] += 2;
614 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
615 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
616 $aSearch['iNamePhrase'] = $iPhrase;
617 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
624 // Allow skipping a word - but at EXTREAM cost
625 //$aSearch = $aCurrentSearch;
626 //$aSearch['iSearchRank']+=100;
627 //$aNewWordsetSearches[] = $aSearch;
631 usort($aNewWordsetSearches, 'bySearchRank');
632 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
634 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
636 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
637 usort($aNewPhraseSearches, 'bySearchRank');
639 $aSearchHash = array();
640 foreach($aNewPhraseSearches as $iSearch => $aSearch)
642 $sHash = serialize($aSearch);
643 if (isset($aSearchHash[$sHash]))
645 unset($aNewPhraseSearches[$iSearch]);
649 $aSearchHash[$sHash] = 1;
653 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
656 // Re-group the searches by their score, junk anything over 20 as just not worth trying
657 $aGroupedSearches = array();
658 foreach($aNewPhraseSearches as $aSearch)
660 if ($aSearch['iSearchRank'] < $iMaxRank)
662 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
663 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
666 ksort($aGroupedSearches);
669 $aSearches = array();
670 foreach($aGroupedSearches as $iScore => $aNewSearches)
672 $iSearchCount += sizeof($aNewSearches);
673 $aSearches = array_merge($aSearches, $aNewSearches);
674 if ($iSearchCount > 50) break;
677 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
683 // Re-group the searches by their score, junk anything over 20 as just not worth trying
684 $aGroupedSearches = array();
685 foreach($aSearches as $aSearch)
687 if ($aSearch['iSearchRank'] < $iMaxRank)
689 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
690 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
693 ksort($aGroupedSearches);
696 if (CONST_Debug) var_Dump($aGroupedSearches);
700 $aCopyGroupedSearches = $aGroupedSearches;
701 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
703 foreach($aSearches as $iSearch => $aSearch)
705 if (sizeof($aSearch['aAddress']))
707 $iReverseItem = array_pop($aSearch['aAddress']);
708 if (isset($aPossibleMainWordIDs[$iReverseItem]))
710 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
711 $aSearch['aName'] = array($iReverseItem);
712 $aGroupedSearches[$iGroup][] = $aSearch;
714 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
715 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
721 // Filter out duplicate searches
722 $aSearchHash = array();
723 foreach($aGroupedSearches as $iGroup => $aSearches)
725 foreach($aSearches as $iSearch => $aSearch)
727 $sHash = serialize($aSearch);
728 if (isset($aSearchHash[$sHash]))
730 unset($aGroupedSearches[$iGroup][$iSearch]);
731 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
735 $aSearchHash[$sHash] = 1;
740 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
744 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
747 foreach($aSearches as $aSearch)
751 // Must have a location term
752 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
754 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
756 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
758 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
759 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
760 $sSQL .= " order by st_area(geometry) desc limit 1";
761 $aPlaceIDs = $oDB->getCol($sSQL);
766 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
767 if (!$aSearch['sClass']) continue;
768 if (CONST_Debug) var_dump('<hr>',$aSearch);
769 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
770 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
771 if ($oDB->getOne($sSQL))
773 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
774 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
775 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
776 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
777 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
778 $sSQL .= " limit $iLimit";
779 if (CONST_Debug) var_dump($sSQL);
780 $aPlaceIDs = $oDB->getCol($sSQL);
782 if (!sizeof($aPlaceIDs))
784 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
785 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
786 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
787 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
788 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
789 $sSQL .= " limit $iLimit";
790 if (CONST_Debug) var_dump($sSQL);
791 $aPlaceIDs = $oDB->getCol($sSQL);
796 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
797 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
798 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
799 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
800 $sSQL .= " limit $iLimit";
801 if (CONST_Debug) var_dump($sSQL);
802 $aPlaceIDs = $oDB->getCol($sSQL);
808 if (CONST_Debug) var_dump('<hr>',$aSearch);
809 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
810 $aPlaceIDs = array();
812 // First we need a position, either aName or fLat or both
816 // TODO: filter out the pointless search terms (2 letter name tokens and less)
817 // they might be right - but they are just too darned expensive to run
818 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
819 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
820 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
821 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
822 if ($aSearch['fLon'] && $aSearch['fLat'])
824 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
825 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
827 if (sizeof($aExcludePlaceIDs))
829 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
831 if ($sCountryCodesSQL)
833 $aTerms[] = "country_code in ($sCountryCodesSQL)";
836 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
837 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
839 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
841 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
842 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
843 $aOrder[] = "$sImportanceSQL DESC";
847 $sSQL = "select place_id";
848 $sSQL .= " from search_name";
849 $sSQL .= " where ".join(' and ',$aTerms);
850 $sSQL .= " order by ".join(', ',$aOrder);
851 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
852 $sSQL .= " limit 50";
853 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
856 $sSQL .= " limit ".$iLimit;
858 if (CONST_Debug) var_dump($sSQL);
859 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
860 if (PEAR::IsError($aViewBoxPlaceIDs))
862 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
864 //var_dump($aViewBoxPlaceIDs);
865 // Did we have an viewbox matches?
866 $aPlaceIDs = array();
867 $bViewBoxMatch = false;
868 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
870 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
871 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
872 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
873 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
874 $aPlaceIDs[] = $aViewBoxRow['place_id'];
877 //var_Dump($aPlaceIDs);
880 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
882 $aRoadPlaceIDs = $aPlaceIDs;
883 $sPlaceIDs = join(',',$aPlaceIDs);
885 // Now they are indexed look for a house attached to a street we found
886 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
887 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
888 if (sizeof($aExcludePlaceIDs))
890 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
892 $sSQL .= " limit $iLimit";
893 if (CONST_Debug) var_dump($sSQL);
894 $aPlaceIDs = $oDB->getCol($sSQL);
896 // If not try the aux fallback table
897 if (!sizeof($aPlaceIDs))
899 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
900 if (sizeof($aExcludePlaceIDs))
902 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
904 // $sSQL .= " limit $iLimit";
905 if (CONST_Debug) var_dump($sSQL);
906 $aPlaceIDs = $oDB->getCol($sSQL);
909 if (!sizeof($aPlaceIDs))
911 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
912 if (sizeof($aExcludePlaceIDs))
914 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
916 // $sSQL .= " limit $iLimit";
917 if (CONST_Debug) var_dump($sSQL);
918 $aPlaceIDs = $oDB->getCol($sSQL);
921 // Fallback to the road
922 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
924 $aPlaceIDs = $aRoadPlaceIDs;
929 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
931 $sPlaceIDs = join(',',$aPlaceIDs);
933 $aResultPlaceIDs = array();
935 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
937 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
938 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
939 $sSQL .= " and linked_place_id is null";
940 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
941 $sSQL .= " order by rank_search asc limit $iLimit";
942 if (CONST_Debug) var_dump($sSQL);
943 $aResultPlaceIDs = $oDB->getCol($sSQL);
946 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
948 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
949 $bCacheTable = $oDB->getOne($sSQL);
951 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
953 if (CONST_Debug) var_dump($sSQL);
954 $iMaxRank = ((int)$oDB->getOne($sSQL));
956 // For state / country level searches the normal radius search doesn't work very well
958 if ($iMaxRank < 9 && $bCacheTable)
960 // Try and get a polygon to search in instead
961 $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";
962 if (CONST_Debug) var_dump($sSQL);
963 $sPlaceGeom = $oDB->getOne($sSQL);
973 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
974 if (CONST_Debug) var_dump($sSQL);
975 $aPlaceIDs = $oDB->getCol($sSQL);
976 $sPlaceIDs = join(',',$aPlaceIDs);
979 if ($sPlaceIDs || $sPlaceGeom)
985 // More efficient - can make the range bigger
989 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
990 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
991 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
993 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
994 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
997 $sSQL .= ",placex as f where ";
998 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1003 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1005 if (sizeof($aExcludePlaceIDs))
1007 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1009 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1010 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1011 if ($iOffset) $sSQL .= " offset $iOffset";
1012 $sSQL .= " limit $iLimit";
1013 if (CONST_Debug) var_dump($sSQL);
1014 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $oDB->getCol($sSQL));
1018 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1021 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1022 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1024 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1025 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1026 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1027 if (sizeof($aExcludePlaceIDs))
1029 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1031 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1032 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1033 if ($iOffset) $sSQL .= " offset $iOffset";
1034 $sSQL .= " limit $iLimit";
1035 if (CONST_Debug) var_dump($sSQL);
1036 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $oDB->getCol($sSQL));
1041 $aPlaceIDs = $aResultPlaceIDs;
1047 if (PEAR::IsError($aPlaceIDs))
1049 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1052 if (CONST_Debug) var_Dump($aPlaceIDs);
1054 foreach($aPlaceIDs as $iPlaceID)
1056 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1058 if ($iQueryLoop > 20) break;
1061 if (sizeof($aResultPlaceIDs)) break;
1062 if ($iGroupLoop > 4) break;
1063 if ($iQueryLoop > 30) break;
1066 // Did we find anything?
1067 if (sizeof($aResultPlaceIDs))
1069 //var_Dump($aResultPlaceIDs);exit;
1070 // Get the details for display (is this a redundant extra step?)
1071 $sPlaceIDs = join(',',$aResultPlaceIDs);
1072 $sOrderSQL = 'CASE ';
1073 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1075 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1077 $sOrderSQL .= ' ELSE 10000000 END';
1078 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1079 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1080 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1081 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1082 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1083 // $sSQL .= $sOrderSQL." as porder, ";
1084 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1085 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1086 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1087 $sSQL .= "and linked_place_id is null ";
1088 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1089 if (!$bDeDupe) $sSQL .= ",place_id";
1090 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1091 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1092 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1094 $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,";
1095 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1096 $sSQL .= "null as placename,";
1097 $sSQL .= "null as ref,";
1098 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1099 // $sSQL .= $sOrderSQL." as porder, ";
1100 $sSQL .= "-0.15 as importance ";
1101 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1102 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1103 $sSQL .= "group by place_id";
1104 if (!$bDeDupe) $sSQL .= ",place_id";
1106 $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,";
1107 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1108 $sSQL .= "null as placename,";
1109 $sSQL .= "null as ref,";
1110 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1111 // $sSQL .= $sOrderSQL." as porder, ";
1112 $sSQL .= "-0.10 as importance ";
1113 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1114 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1115 $sSQL .= "group by place_id";
1116 if (!$bDeDupe) $sSQL .= ",place_id";
1117 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1118 $sSQL .= "order by importance desc";
1119 // $sSQL .= "order by rank_search,rank_address,porder asc";
1120 if (CONST_Debug) var_dump('<hr>',$sSQL);
1121 $aSearchResults = $oDB->getAll($sSQL);
1122 //var_dump($sSQL,$aSearchResults);exit;
1124 if (PEAR::IsError($aSearchResults))
1126 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1129 } // end if ($sQuery)
1132 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1134 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1135 $aResultPlaceIDs = array($iPlaceID);
1137 // TODO: this needs refactoring!
1139 // Get the details for display (is this a redundant extra step?)
1140 $sPlaceIDs = join(',',$aResultPlaceIDs);
1141 $sOrderSQL = 'CASE ';
1142 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1144 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1146 $sOrderSQL .= ' ELSE 10000000 END';
1147 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1148 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1149 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1150 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1151 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1152 // $sSQL .= $sOrderSQL." as porder, ";
1153 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1154 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1155 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1156 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1157 if (!$bDeDupe) $sSQL .= ",place_id";
1158 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1159 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1160 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1162 $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,";
1163 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1164 $sSQL .= "null as placename,";
1165 $sSQL .= "null as ref,";
1166 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1167 // $sSQL .= $sOrderSQL." as porder, ";
1168 $sSQL .= "-0.15 as importance ";
1169 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1170 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1171 $sSQL .= "group by place_id";
1172 if (!$bDeDupe) $sSQL .= ",place_id";
1174 $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,";
1175 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1176 $sSQL .= "null as placename,";
1177 $sSQL .= "null as ref,";
1178 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1179 // $sSQL .= $sOrderSQL." as porder, ";
1180 $sSQL .= "-0.10 as importance ";
1181 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1182 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1183 $sSQL .= "group by place_id";
1184 if (!$bDeDupe) $sSQL .= ",place_id";
1185 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1186 $sSQL .= "order by importance desc";
1187 // $sSQL .= "order by rank_search,rank_address,porder asc";
1188 if (CONST_Debug) var_dump('<hr>',$sSQL);
1189 $aSearchResults = $oDB->getAll($sSQL);
1190 //var_dump($sSQL,$aSearchResults);exit;
1192 if (PEAR::IsError($aSearchResults))
1194 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1200 $sSearchResult = '';
1201 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1203 $sSearchResult = 'No Results Found';
1205 //var_Dump($aSearchResults);
1207 $aClassType = getClassTypesWithImportance();
1208 $aRecheckWords = preg_split('/\b/',$sQuery);
1209 foreach($aRecheckWords as $i => $sWord)
1211 if (!$sWord) unset($aRecheckWords[$i]);
1213 foreach($aSearchResults as $iResNum => $aResult)
1215 if (CONST_Search_AreaPolygons)
1217 // Get the bounding box and outline polygon
1218 $sSQL = "select place_id,numfeatures,area,outline,";
1219 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1220 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1221 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1223 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1224 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1225 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1226 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1227 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1228 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1229 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1230 if ($bAsText) $sSQL .= ",ST_AsText(geometry) as astext";
1231 if ($bShowPolygons) $sSQL .= ",ST_AsText(geometry) as outlinestring";
1232 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1233 $aPointPolygon = $oDB->getRow($sSQL);
1234 if (PEAR::IsError($aPointPolygon))
1236 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1238 if ($aPointPolygon['place_id'])
1240 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1241 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1242 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1243 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1245 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1246 $aResult['lat'] = $aPointPolygon['centrelat'];
1247 $aResult['lon'] = $aPointPolygon['centrelon'];
1251 // Translate geometary string to point array
1252 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1254 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1256 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1258 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1260 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1263 $iSteps = ($fRadius * 40000)^2;
1264 $fStepSize = (2*pi())/$iSteps;
1265 $aPolyPoints = array();
1266 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1268 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1270 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1271 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1272 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1273 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1277 // Output data suitable for display (points and a bounding box)
1278 if ($bShowPolygons && isset($aPolyPoints))
1280 $aResult['aPolyPoints'] = array();
1281 foreach($aPolyPoints as $aPoint)
1283 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1286 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1290 if (!isset($aResult['aBoundingBox']))
1293 $fDiameter = 0.0001;
1295 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1296 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1298 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1300 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1301 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1303 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1305 $fRadius = $fDiameter / 2;
1307 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1308 $fStepSize = (2*pi())/$iSteps;
1309 $aPolyPoints = array();
1310 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1312 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1314 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1315 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1316 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1317 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1319 // Output data suitable for display (points and a bounding box)
1322 $aResult['aPolyPoints'] = array();
1323 foreach($aPolyPoints as $aPoint)
1325 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1328 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1331 // Is there an icon set for this type of result?
1332 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1333 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1335 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1338 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1339 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1341 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1344 if ($bShowAddressDetails)
1346 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1347 //var_dump($aResult['address']);
1351 // Adjust importance for the number of exact string matches in the result
1352 $aResult['importance'] = max(0.001,$aResult['importance']);
1354 $sAddress = $aResult['langaddress'];
1355 foreach($aRecheckWords as $i => $sWord)
1357 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1359 $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
1361 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1363 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1364 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1366 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1368 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1369 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1371 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1375 $aResult['importance'] = 1000000000000000;
1378 $aResult['name'] = $aResult['langaddress'];
1379 $aResult['foundorder'] = $iResNum;
1380 $aSearchResults[$iResNum] = $aResult;
1382 uasort($aSearchResults, 'byImportance');
1384 //var_dump($aSearchResults);exit;
1386 $aOSMIDDone = array();
1387 $aClassTypeNameDone = array();
1388 $aToFilter = $aSearchResults;
1389 $aSearchResults = array();
1392 foreach($aToFilter as $iResNum => $aResult)
1394 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1395 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1398 $fLat = $aResult['lat'];
1399 $fLon = $aResult['lon'];
1400 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1403 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1404 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1406 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1407 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1408 $aSearchResults[] = $aResult;
1411 // Absolute limit on number of results
1412 if (sizeof($aSearchResults) >= $iLimit) break;
1415 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1417 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1419 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1424 logEnd($oDB, $hLog, sizeof($aToFilter));
1426 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1427 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1428 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1429 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1430 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1431 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1434 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1436 $sMoreURL .= '&q='.urlencode($sQuery);
1438 if (CONST_Debug) exit;
1440 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');