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";
228 $bBoundingBoxSearch = true;
231 // Do we have anything that looks like a lat/lon pair?
232 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
234 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
235 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
236 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
238 $_GET['nearlat'] = $fQueryLat;
239 $_GET['nearlon'] = $fQueryLon;
240 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
243 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
245 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
246 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
247 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
249 $_GET['nearlat'] = $fQueryLat;
250 $_GET['nearlon'] = $fQueryLon;
251 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
254 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
256 $fQueryLat = $aData[2];
257 $fQueryLon = $aData[3];
258 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
260 $_GET['nearlat'] = $fQueryLat;
261 $_GET['nearlon'] = $fQueryLon;
262 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
266 if ($sQuery || $aStructuredQuery)
268 // Start with a blank search
270 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
271 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
274 $sNearPointSQL = false;
275 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
277 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
278 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
279 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
280 $aSearches[0]['fRadius'] = 0.1;
283 $bSpecialTerms = false;
284 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
285 $aSpecialTerms = array();
286 foreach($aSpecialTermsRaw as $aSpecialTerm)
288 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
289 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
292 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
293 $aSpecialTerms = array();
294 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
296 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
297 unset($aStructuredQuery['amenity']);
299 foreach($aSpecialTermsRaw as $aSpecialTerm)
301 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
302 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
303 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
304 $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';
305 if (CONST_Debug) var_Dump($sSQL);
306 $aSearchWords = $oDB->getAll($sSQL);
307 $aNewSearches = array();
308 foreach($aSearches as $aSearch)
310 foreach($aSearchWords as $aSearchTerm)
312 $aNewSearch = $aSearch;
313 if ($aSearchTerm['country_code'])
315 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
316 $aNewSearches[] = $aNewSearch;
317 $bSpecialTerms = true;
319 if ($aSearchTerm['class'])
321 $aNewSearch['sClass'] = $aSearchTerm['class'];
322 $aNewSearch['sType'] = $aSearchTerm['type'];
323 $aNewSearches[] = $aNewSearch;
324 $bSpecialTerms = true;
328 $aSearches = $aNewSearches;
331 // Split query into phrases
332 // Commas are used to reduce the search space by indicating where phrases split
333 if (sizeof($aStructuredQuery) > 0)
335 $aPhrases = $aStructuredQuery;
336 $bStructuredPhrases = true;
340 $aPhrases = explode(',',$sQuery);
341 $bStructuredPhrases = false;
345 // Convert each phrase to standard form
346 // Create a list of standard words
347 // Get all 'sets' of words
348 // Generate a complete list of all
350 foreach($aPhrases as $iPhrase => $sPhrase)
352 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
353 if (PEAR::isError($aPhrase))
355 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
356 if (CONST_Debug) var_dump($aPhrase);
359 if (trim($aPhrase['string']))
361 $aPhrases[$iPhrase] = $aPhrase;
362 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
363 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
364 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
368 unset($aPhrases[$iPhrase]);
372 // reindex phrases - we make assumptions later on
373 $aPhraseTypes = array_keys($aPhrases);
374 $aPhrases = array_values($aPhrases);
376 if (sizeof($aTokens))
379 // Check which tokens we have, get the ID numbers
380 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
381 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
382 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
383 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
385 if (CONST_Debug) var_Dump($sSQL);
387 $aValidTokens = array();
388 if (sizeof($aTokens))
389 $aDatabaseWords = $oDB->getAll($sSQL);
391 $aDatabaseWords = array();
392 if (PEAR::IsError($aDatabaseWords))
394 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
396 $aPossibleMainWordIDs = array();
397 foreach($aDatabaseWords as $aToken)
399 if (isset($aValidTokens[$aToken['word_token']]))
401 $aValidTokens[$aToken['word_token']][] = $aToken;
405 $aValidTokens[$aToken['word_token']] = array($aToken);
407 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
409 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
411 $aSuggestion = array();
412 $bSuggestion = false;
413 if (CONST_Suggestions_Enabled)
415 foreach($aPhrases as $iPhrase => $aPhrase)
417 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
419 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
420 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
421 $aRow = $aSuggestionWords[0];
422 if ($aRow && $aRow['word'])
424 $aSuggestion[] = $aRow['word'];
429 $aSuggestion[] = $aPhrase['string'];
434 $aSuggestion[] = $aPhrase['string'];
438 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
440 // Try and calculate GB postcodes we might be missing
441 foreach($aTokens as $sToken)
443 // Source of gb postcodes is now definitive - always use
444 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
446 if (substr($aData[1],-2,1) != ' ')
448 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
449 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
451 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
452 if ($aGBPostcodeLocation)
454 $aValidTokens[$sToken] = $aGBPostcodeLocation;
459 foreach($aTokens as $sToken)
461 // Unknown single word token with a number - assume it is a house number
462 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
464 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
468 // Any words that have failed completely?
471 // Start the search process
472 $aResultPlaceIDs = array();
475 Calculate all searches using aValidTokens i.e.
477 'Wodsworth Road, Sheffield' =>
481 0 1 (wodsworth)(road)
484 Score how good the search is so they can be ordered
486 foreach($aPhrases as $iPhrase => $sPhrase)
488 $aNewPhraseSearches = array();
489 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
490 else $sPhraseType = '';
492 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
494 $aWordsetSearches = $aSearches;
496 // Add all words from this wordset
497 foreach($aWordset as $iToken => $sToken)
499 //echo "<br><b>$sToken</b>";
500 $aNewWordsetSearches = array();
502 foreach($aWordsetSearches as $aCurrentSearch)
505 //var_dump($aCurrentSearch);
508 // If the token is valid
509 if (isset($aValidTokens[' '.$sToken]))
511 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
513 $aSearch = $aCurrentSearch;
514 $aSearch['iSearchRank']++;
515 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
517 if ($aSearch['sCountryCode'] === false)
519 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
520 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
521 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
522 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
525 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
527 if ($aSearch['fLat'] === '')
529 $aSearch['fLat'] = $aSearchTerm['lat'];
530 $aSearch['fLon'] = $aSearchTerm['lon'];
531 $aSearch['fRadius'] = $aSearchTerm['radius'];
532 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
535 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
537 if ($aSearch['sHouseNumber'] === '')
539 $aSearch['sHouseNumber'] = $sToken;
540 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
542 // Fall back to not searching for this item (better than nothing)
543 $aSearch = $aCurrentSearch;
544 $aSearch['iSearchRank'] += 1;
545 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
549 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
551 if ($aSearch['sClass'] === '')
553 $aSearch['sOperator'] = $aSearchTerm['operator'];
554 $aSearch['sClass'] = $aSearchTerm['class'];
555 $aSearch['sType'] = $aSearchTerm['type'];
556 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
557 else $aSearch['sOperator'] = 'near'; // near = in for the moment
559 // Do we have a shortcut id?
560 if ($aSearch['sOperator'] == 'name')
562 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
563 if ($iAmenityID = $oDB->getOne($sSQL))
565 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
566 $aSearch['aName'][$iAmenityID] = $iAmenityID;
567 $aSearch['sClass'] = '';
568 $aSearch['sType'] = '';
571 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
574 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
576 if (sizeof($aSearch['aName']))
578 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
580 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
584 $aSearch['iSearchRank'] += 1000; // skip;
589 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
590 // $aSearch['iNamePhrase'] = $iPhrase;
592 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
596 if (isset($aValidTokens[$sToken]))
598 // Allow searching for a word - but at extra cost
599 foreach($aValidTokens[$sToken] as $aSearchTerm)
601 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
603 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
605 $aSearch = $aCurrentSearch;
606 $aSearch['iSearchRank'] += 1;
607 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
608 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
611 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
613 $aSearch = $aCurrentSearch;
614 $aSearch['iSearchRank'] += 2;
615 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
616 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
617 $aSearch['iNamePhrase'] = $iPhrase;
618 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
625 // Allow skipping a word - but at EXTREAM cost
626 //$aSearch = $aCurrentSearch;
627 //$aSearch['iSearchRank']+=100;
628 //$aNewWordsetSearches[] = $aSearch;
632 usort($aNewWordsetSearches, 'bySearchRank');
633 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
635 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
637 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
638 usort($aNewPhraseSearches, 'bySearchRank');
640 $aSearchHash = array();
641 foreach($aNewPhraseSearches as $iSearch => $aSearch)
643 $sHash = serialize($aSearch);
644 if (isset($aSearchHash[$sHash]))
646 unset($aNewPhraseSearches[$iSearch]);
650 $aSearchHash[$sHash] = 1;
654 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
657 // Re-group the searches by their score, junk anything over 20 as just not worth trying
658 $aGroupedSearches = array();
659 foreach($aNewPhraseSearches as $aSearch)
661 if ($aSearch['iSearchRank'] < $iMaxRank)
663 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
664 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
667 ksort($aGroupedSearches);
670 $aSearches = array();
671 foreach($aGroupedSearches as $iScore => $aNewSearches)
673 $iSearchCount += sizeof($aNewSearches);
674 $aSearches = array_merge($aSearches, $aNewSearches);
675 if ($iSearchCount > 50) break;
678 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
684 // Re-group the searches by their score, junk anything over 20 as just not worth trying
685 $aGroupedSearches = array();
686 foreach($aSearches as $aSearch)
688 if ($aSearch['iSearchRank'] < $iMaxRank)
690 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
691 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
694 ksort($aGroupedSearches);
697 if (CONST_Debug) var_Dump($aGroupedSearches);
701 $aCopyGroupedSearches = $aGroupedSearches;
702 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
704 foreach($aSearches as $iSearch => $aSearch)
706 if (sizeof($aSearch['aAddress']))
708 $iReverseItem = array_pop($aSearch['aAddress']);
709 if (isset($aPossibleMainWordIDs[$iReverseItem]))
711 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
712 $aSearch['aName'] = array($iReverseItem);
713 $aGroupedSearches[$iGroup][] = $aSearch;
715 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
716 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
722 // Filter out duplicate searches
723 $aSearchHash = array();
724 foreach($aGroupedSearches as $iGroup => $aSearches)
726 foreach($aSearches as $iSearch => $aSearch)
728 $sHash = serialize($aSearch);
729 if (isset($aSearchHash[$sHash]))
731 unset($aGroupedSearches[$iGroup][$iSearch]);
732 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
736 $aSearchHash[$sHash] = 1;
741 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
745 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
748 foreach($aSearches as $aSearch)
752 // Must have a location term
753 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
755 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
757 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
759 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
760 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
761 $sSQL .= " order by st_area(geometry) desc limit 1";
762 $aPlaceIDs = $oDB->getCol($sSQL);
767 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
768 if (!$aSearch['sClass']) continue;
769 if (CONST_Debug) var_dump('<hr>',$aSearch);
770 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
771 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
772 if ($oDB->getOne($sSQL))
774 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
775 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
776 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
777 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
778 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
779 $sSQL .= " limit $iLimit";
780 if (CONST_Debug) var_dump($sSQL);
781 $aPlaceIDs = $oDB->getCol($sSQL);
783 if (!sizeof($aPlaceIDs))
785 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
786 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
787 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
788 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
789 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
790 $sSQL .= " limit $iLimit";
791 if (CONST_Debug) var_dump($sSQL);
792 $aPlaceIDs = $oDB->getCol($sSQL);
797 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
798 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
799 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
800 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
801 $sSQL .= " limit $iLimit";
802 if (CONST_Debug) var_dump($sSQL);
803 $aPlaceIDs = $oDB->getCol($sSQL);
809 if (CONST_Debug) var_dump('<hr>',$aSearch);
810 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
811 $aPlaceIDs = array();
813 // First we need a position, either aName or fLat or both
817 // TODO: filter out the pointless search terms (2 letter name tokens and less)
818 // they might be right - but they are just too darned expensive to run
819 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
820 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
821 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
822 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
823 if ($aSearch['fLon'] && $aSearch['fLat'])
825 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
826 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
828 if (sizeof($aExcludePlaceIDs))
830 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
832 if ($sCountryCodesSQL)
834 $aTerms[] = "country_code in ($sCountryCodesSQL)";
837 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
838 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
840 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
842 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
843 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
844 $aOrder[] = "$sImportanceSQL DESC";
848 $sSQL = "select place_id";
849 $sSQL .= " from search_name";
850 $sSQL .= " where ".join(' and ',$aTerms);
851 $sSQL .= " order by ".join(', ',$aOrder);
852 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
853 $sSQL .= " limit 50";
854 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
857 $sSQL .= " limit ".$iLimit;
859 if (CONST_Debug) var_dump($sSQL);
860 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
861 if (PEAR::IsError($aViewBoxPlaceIDs))
863 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
865 //var_dump($aViewBoxPlaceIDs);
866 // Did we have an viewbox matches?
867 $aPlaceIDs = array();
868 $bViewBoxMatch = false;
869 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
871 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
872 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
873 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
874 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
875 $aPlaceIDs[] = $aViewBoxRow['place_id'];
878 //var_Dump($aPlaceIDs);
881 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
883 $aRoadPlaceIDs = $aPlaceIDs;
884 $sPlaceIDs = join(',',$aPlaceIDs);
886 // Now they are indexed look for a house attached to a street we found
887 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
888 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
889 if (sizeof($aExcludePlaceIDs))
891 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
893 $sSQL .= " limit $iLimit";
894 if (CONST_Debug) var_dump($sSQL);
895 $aPlaceIDs = $oDB->getCol($sSQL);
897 // If not try the aux fallback table
898 if (!sizeof($aPlaceIDs))
900 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
901 if (sizeof($aExcludePlaceIDs))
903 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
905 // $sSQL .= " limit $iLimit";
906 if (CONST_Debug) var_dump($sSQL);
907 $aPlaceIDs = $oDB->getCol($sSQL);
910 if (!sizeof($aPlaceIDs))
912 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
913 if (sizeof($aExcludePlaceIDs))
915 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
917 // $sSQL .= " limit $iLimit";
918 if (CONST_Debug) var_dump($sSQL);
919 $aPlaceIDs = $oDB->getCol($sSQL);
922 // Fallback to the road
923 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
925 $aPlaceIDs = $aRoadPlaceIDs;
930 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
932 $sPlaceIDs = join(',',$aPlaceIDs);
934 $aResultPlaceIDs = array();
936 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
938 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
939 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
940 $sSQL .= " and linked_place_id is null";
941 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
942 $sSQL .= " order by rank_search asc limit $iLimit";
943 if (CONST_Debug) var_dump($sSQL);
944 $aResultPlaceIDs = $oDB->getCol($sSQL);
947 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
949 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
950 $bCacheTable = $oDB->getOne($sSQL);
952 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
954 if (CONST_Debug) var_dump($sSQL);
955 $iMaxRank = ((int)$oDB->getOne($sSQL));
957 // For state / country level searches the normal radius search doesn't work very well
959 if ($iMaxRank < 9 && $bCacheTable)
961 // Try and get a polygon to search in instead
962 $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";
963 if (CONST_Debug) var_dump($sSQL);
964 $sPlaceGeom = $oDB->getOne($sSQL);
974 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
975 if (CONST_Debug) var_dump($sSQL);
976 $aPlaceIDs = $oDB->getCol($sSQL);
977 $sPlaceIDs = join(',',$aPlaceIDs);
980 if ($sPlaceIDs || $sPlaceGeom)
986 // More efficient - can make the range bigger
990 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
991 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
992 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
994 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
995 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
998 $sSQL .= ",placex as f where ";
999 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1004 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1006 if (sizeof($aExcludePlaceIDs))
1008 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1010 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1011 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1012 if ($iOffset) $sSQL .= " offset $iOffset";
1013 $sSQL .= " limit $iLimit";
1014 if (CONST_Debug) var_dump($sSQL);
1015 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $oDB->getCol($sSQL));
1019 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1022 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1023 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1025 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1026 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1027 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1028 if (sizeof($aExcludePlaceIDs))
1030 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1032 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1033 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1034 if ($iOffset) $sSQL .= " offset $iOffset";
1035 $sSQL .= " limit $iLimit";
1036 if (CONST_Debug) var_dump($sSQL);
1037 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $oDB->getCol($sSQL));
1042 $aPlaceIDs = $aResultPlaceIDs;
1048 if (PEAR::IsError($aPlaceIDs))
1050 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1053 if (CONST_Debug) var_Dump($aPlaceIDs);
1055 foreach($aPlaceIDs as $iPlaceID)
1057 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1059 if ($iQueryLoop > 20) break;
1062 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1063 if ($iGroupLoop > 4) break;
1064 if ($iQueryLoop > 30) break;
1067 // Did we find anything?
1068 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1070 //var_Dump($aResultPlaceIDs);exit;
1071 // Get the details for display (is this a redundant extra step?)
1072 $sPlaceIDs = join(',',$aResultPlaceIDs);
1073 $sOrderSQL = 'CASE ';
1074 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1076 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1078 $sOrderSQL .= ' ELSE 10000000 END';
1079 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1080 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1081 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1082 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1083 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1084 // $sSQL .= $sOrderSQL." as porder, ";
1085 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1086 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1087 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1088 $sSQL .= "and linked_place_id is null ";
1089 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1090 if (!$bDeDupe) $sSQL .= ",place_id";
1091 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1092 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1093 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1095 $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,";
1096 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1097 $sSQL .= "null as placename,";
1098 $sSQL .= "null as ref,";
1099 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1100 // $sSQL .= $sOrderSQL." as porder, ";
1101 $sSQL .= "-0.15 as importance ";
1102 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1103 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1104 $sSQL .= "group by place_id";
1105 if (!$bDeDupe) $sSQL .= ",place_id";
1107 $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,";
1108 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1109 $sSQL .= "null as placename,";
1110 $sSQL .= "null as ref,";
1111 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1112 // $sSQL .= $sOrderSQL." as porder, ";
1113 $sSQL .= "-0.10 as importance ";
1114 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1115 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1116 $sSQL .= "group by place_id";
1117 if (!$bDeDupe) $sSQL .= ",place_id";
1118 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1119 $sSQL .= "order by importance desc";
1120 // $sSQL .= "order by rank_search,rank_address,porder asc";
1121 if (CONST_Debug) var_dump('<hr>',$sSQL);
1122 $aSearchResults = $oDB->getAll($sSQL);
1123 //var_dump($sSQL,$aSearchResults);exit;
1125 if (PEAR::IsError($aSearchResults))
1127 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1130 } // end if ($sQuery)
1133 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1135 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1136 $aResultPlaceIDs = array($iPlaceID);
1138 // TODO: this needs refactoring!
1140 // Get the details for display (is this a redundant extra step?)
1141 $sPlaceIDs = join(',',$aResultPlaceIDs);
1142 $sOrderSQL = 'CASE ';
1143 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1145 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1147 $sOrderSQL .= ' ELSE 10000000 END';
1148 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1149 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1150 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1151 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1152 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1153 // $sSQL .= $sOrderSQL." as porder, ";
1154 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1155 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1156 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1157 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1158 if (!$bDeDupe) $sSQL .= ",place_id";
1159 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1160 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1161 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1163 $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,";
1164 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1165 $sSQL .= "null as placename,";
1166 $sSQL .= "null as ref,";
1167 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1168 // $sSQL .= $sOrderSQL." as porder, ";
1169 $sSQL .= "-0.15 as importance ";
1170 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1171 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1172 $sSQL .= "group by place_id";
1173 if (!$bDeDupe) $sSQL .= ",place_id";
1175 $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,";
1176 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1177 $sSQL .= "null as placename,";
1178 $sSQL .= "null as ref,";
1179 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1180 // $sSQL .= $sOrderSQL." as porder, ";
1181 $sSQL .= "-0.10 as importance ";
1182 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1183 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1184 $sSQL .= "group by place_id";
1185 if (!$bDeDupe) $sSQL .= ",place_id";
1186 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1187 $sSQL .= "order by importance desc";
1188 // $sSQL .= "order by rank_search,rank_address,porder asc";
1189 if (CONST_Debug) var_dump('<hr>',$sSQL);
1190 $aSearchResults = $oDB->getAll($sSQL);
1191 //var_dump($sSQL,$aSearchResults);exit;
1193 if (PEAR::IsError($aSearchResults))
1195 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1201 $sSearchResult = '';
1202 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1204 $sSearchResult = 'No Results Found';
1206 //var_Dump($aSearchResults);
1208 $aClassType = getClassTypesWithImportance();
1209 $aRecheckWords = preg_split('/\b/',$sQuery);
1210 foreach($aRecheckWords as $i => $sWord)
1212 if (!$sWord) unset($aRecheckWords[$i]);
1214 foreach($aSearchResults as $iResNum => $aResult)
1216 if (CONST_Search_AreaPolygons)
1218 // Get the bounding box and outline polygon
1219 $sSQL = "select place_id,numfeatures,area,outline,";
1220 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1221 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1222 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1224 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1225 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1226 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1227 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1228 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1229 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1230 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1231 if ($bAsText) $sSQL .= ",ST_AsText(geometry) as astext";
1232 if ($bShowPolygons) $sSQL .= ",ST_AsText(geometry) as outlinestring";
1233 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1234 $aPointPolygon = $oDB->getRow($sSQL);
1235 if (PEAR::IsError($aPointPolygon))
1237 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1239 if ($aPointPolygon['place_id'])
1241 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1242 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1243 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1244 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1246 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1247 $aResult['lat'] = $aPointPolygon['centrelat'];
1248 $aResult['lon'] = $aPointPolygon['centrelon'];
1252 // Translate geometary string to point array
1253 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1255 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1257 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1259 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1261 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1264 $iSteps = ($fRadius * 40000)^2;
1265 $fStepSize = (2*pi())/$iSteps;
1266 $aPolyPoints = array();
1267 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1269 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1271 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1272 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1273 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1274 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1278 // Output data suitable for display (points and a bounding box)
1279 if ($bShowPolygons && isset($aPolyPoints))
1281 $aResult['aPolyPoints'] = array();
1282 foreach($aPolyPoints as $aPoint)
1284 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1287 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1291 if (!isset($aResult['aBoundingBox']))
1294 $fDiameter = 0.0001;
1296 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1297 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1299 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1301 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1302 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1304 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1306 $fRadius = $fDiameter / 2;
1308 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1309 $fStepSize = (2*pi())/$iSteps;
1310 $aPolyPoints = array();
1311 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1313 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1315 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1316 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1317 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1318 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1320 // Output data suitable for display (points and a bounding box)
1323 $aResult['aPolyPoints'] = array();
1324 foreach($aPolyPoints as $aPoint)
1326 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1329 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1332 // Is there an icon set for this type of result?
1333 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1334 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1336 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1339 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1340 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1342 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1345 if ($bShowAddressDetails)
1347 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1348 //var_dump($aResult['address']);
1352 // Adjust importance for the number of exact string matches in the result
1353 $aResult['importance'] = max(0.001,$aResult['importance']);
1355 $sAddress = $aResult['langaddress'];
1356 foreach($aRecheckWords as $i => $sWord)
1358 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1360 $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
1362 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1364 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1365 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1367 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1369 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1370 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1372 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1376 $aResult['importance'] = 1000000000000000;
1379 $aResult['name'] = $aResult['langaddress'];
1380 $aResult['foundorder'] = $iResNum;
1381 $aSearchResults[$iResNum] = $aResult;
1383 uasort($aSearchResults, 'byImportance');
1385 //var_dump($aSearchResults);exit;
1387 $aOSMIDDone = array();
1388 $aClassTypeNameDone = array();
1389 $aToFilter = $aSearchResults;
1390 $aSearchResults = array();
1393 foreach($aToFilter as $iResNum => $aResult)
1395 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1396 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1399 $fLat = $aResult['lat'];
1400 $fLon = $aResult['lon'];
1401 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1404 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1405 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1407 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1408 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1409 $aSearchResults[] = $aResult;
1412 // Absolute limit on number of results
1413 if (sizeof($aSearchResults) >= $iLimit) break;
1416 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1418 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1420 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1425 logEnd($oDB, $hLog, sizeof($aToFilter));
1427 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1428 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1429 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1430 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1431 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1432 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1435 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1437 $sMoreURL .= '&q='.urlencode($sQuery);
1439 if (CONST_Debug) exit;
1441 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');