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'];
40 // Show address breakdown
41 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
44 $aLangPrefOrder = getPreferredLanguages();
45 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
46 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
47 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
49 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
51 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
53 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
55 $iExcludedPlaceID = (int)$iExcludedPlaceID;
56 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
60 // Only certain ranks of feature
61 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
63 if (isset($_GET['featuretype']))
65 switch($_GET['featuretype'])
68 $iMinAddressRank = $iMaxAddressRank = 4;
71 $iMinAddressRank = $iMaxAddressRank = 8;
74 $iMinAddressRank = 14;
75 $iMaxAddressRank = 16;
79 $iMaxAddressRank = 20;
84 if (isset($_GET['countrycodes']))
86 $aCountryCodes = array();
87 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
89 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
91 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
94 $sCountryCodesSQL = join(',', $aCountryCodes);
98 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
99 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
101 $sQuery = substr($_SERVER['PATH_INFO'], 1);
103 // reverse order of '/' separated string
104 $aPhrases = explode('/', $sQuery);
105 $aPhrases = array_reverse($aPhrases);
106 $sQuery = join(', ',$aPhrases);
109 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
111 if (!isset($_GET[$sKey])) return false;
112 $sValue = trim($_GET[$sKey]);
113 if (!$sValue) return false;
114 $aStructuredQuery[$sKey] = $sValue;
115 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
116 $iMinAddressRank = $iNewMinAddressRank;
117 $iMaxAddressRank = $iNewMaxAddressRank;
123 $aStructuredOptions = array(
124 array('amenity', 26, 30),
125 array('street', 26, 30),
126 array('city', 14, 24),
127 array('county', 9, 13),
128 array('state', 8, 8),
129 array('country', 4, 4),
130 array('postalcode', 16, 25),
132 $aStructuredQuery = array();
133 foreach($aStructuredOptions as $aStructuredOption)
135 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
137 if (sizeof($aStructuredQuery) > 0) {
138 $sQuery = join(', ', $aStructuredQuery);
143 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
145 // Hack to make it handle "new york, ny" (and variants) correctly
146 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
147 if (isset($aLangPrefOrder['name:en']))
149 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
150 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
151 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
154 // If we have a view box create the SQL
155 // Small is the actual view box, Large is double (on each axis) that
156 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
157 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
159 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
160 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
162 if (isset($_GET['viewbox']) && $_GET['viewbox'])
164 $aCoOrdinates = explode(',',$_GET['viewbox']);
165 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
166 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
167 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
168 $aCoOrdinates[0] += $fHeight;
169 $aCoOrdinates[2] -= $fHeight;
170 $aCoOrdinates[1] += $fWidth;
171 $aCoOrdinates[3] -= $fWidth;
172 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
174 $bBoundingBoxSearch = false;
176 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
178 $aPoints = explode(',',$_GET['route']);
179 if (sizeof($aPoints) % 2 != 0)
181 echo "Uneven number of points";
184 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
186 foreach($aPoints as $i => $fPoint)
190 if ($i != 1) $sViewboxCentreSQL .= ",";
191 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
195 $fPrevCoord = (float)$fPoint;
198 $sViewboxCentreSQL .= ")'::geometry,4326)";
200 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
201 $sViewboxSmallSQL = $oDB->getOne($sSQL);
202 if (PEAR::isError($sViewboxSmallSQL))
204 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
206 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
208 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
209 $sViewboxLargeSQL = $oDB->getOne($sSQL);
210 if (PEAR::isError($sViewboxLargeSQL))
212 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
214 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
217 // Do we have anything that looks like a lat/lon pair?
218 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
220 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
221 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
222 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
224 $_GET['nearlat'] = $fQueryLat;
225 $_GET['nearlon'] = $fQueryLon;
226 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
229 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
231 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
232 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
233 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
235 $_GET['nearlat'] = $fQueryLat;
236 $_GET['nearlon'] = $fQueryLon;
237 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
240 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
242 $fQueryLat = $aData[2];
243 $fQueryLon = $aData[3];
244 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
246 $_GET['nearlat'] = $fQueryLat;
247 $_GET['nearlon'] = $fQueryLon;
248 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
252 if ($sQuery || $aStructuredQuery)
254 // Start with a blank search
256 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
257 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
260 $sNearPointSQL = false;
261 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
263 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
264 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
265 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
266 $aSearches[0]['fRadius'] = 0.1;
269 $bSpecialTerms = false;
270 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
271 $aSpecialTerms = array();
272 foreach($aSpecialTermsRaw as $aSpecialTerm)
274 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
275 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
278 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
279 $aSpecialTerms = array();
280 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
282 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
283 unset($aStructuredQuery['amenity']);
285 foreach($aSpecialTermsRaw as $aSpecialTerm)
287 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
288 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
289 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
290 $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';
291 if (CONST_Debug) var_Dump($sSQL);
292 $aSearchWords = $oDB->getAll($sSQL);
293 $aNewSearches = array();
294 foreach($aSearches as $aSearch)
296 foreach($aSearchWords as $aSearchTerm)
298 $aNewSearch = $aSearch;
299 if ($aSearchTerm['country_code'])
301 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
302 $aNewSearches[] = $aNewSearch;
303 $bSpecialTerms = true;
305 if ($aSearchTerm['class'])
307 $aNewSearch['sClass'] = $aSearchTerm['class'];
308 $aNewSearch['sType'] = $aSearchTerm['type'];
309 $aNewSearches[] = $aNewSearch;
310 $bSpecialTerms = true;
314 $aSearches = $aNewSearches;
317 // Split query into phrases
318 // Commas are used to reduce the search space by indicating where phrases split
319 if (sizeof($aStructuredQuery) > 0)
321 $aPhrases = $aStructuredQuery;
322 $bStructuredPhrases = true;
326 $aPhrases = explode(',',$sQuery);
327 $bStructuredPhrases = false;
331 // Convert each phrase to standard form
332 // Create a list of standard words
333 // Get all 'sets' of words
334 // Generate a complete list of all
336 foreach($aPhrases as $iPhrase => $sPhrase)
338 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
339 if (PEAR::isError($aPhrase))
341 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
342 if (CONST_Debug) var_dump($aPhrase);
345 if (trim($aPhrase['string']))
347 $aPhrases[$iPhrase] = $aPhrase;
348 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
349 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
350 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
354 unset($aPhrases[$iPhrase]);
358 // reindex phrases - we make assumptions later on
359 $aPhraseTypes = array_keys($aPhrases);
360 $aPhrases = array_values($aPhrases);
362 if (sizeof($aTokens))
365 // Check which tokens we have, get the ID numbers
366 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
367 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
368 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
369 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
371 if (CONST_Debug) var_Dump($sSQL);
373 $aValidTokens = array();
374 if (sizeof($aTokens))
375 $aDatabaseWords = $oDB->getAll($sSQL);
377 $aDatabaseWords = array();
378 if (PEAR::IsError($aDatabaseWords))
380 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
382 $aPossibleMainWordIDs = array();
383 foreach($aDatabaseWords as $aToken)
385 if (isset($aValidTokens[$aToken['word_token']]))
387 $aValidTokens[$aToken['word_token']][] = $aToken;
391 $aValidTokens[$aToken['word_token']] = array($aToken);
393 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
395 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
397 $aSuggestion = array();
398 $bSuggestion = false;
399 if (CONST_Suggestions_Enabled)
401 foreach($aPhrases as $iPhrase => $aPhrase)
403 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
405 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
406 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
407 $aRow = $aSuggestionWords[0];
408 if ($aRow && $aRow['word'])
410 $aSuggestion[] = $aRow['word'];
415 $aSuggestion[] = $aPhrase['string'];
420 $aSuggestion[] = $aPhrase['string'];
424 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
426 // Try and calculate GB postcodes we might be missing
427 foreach($aTokens as $sToken)
429 // Source of gb postcodes is now definitive - always use
430 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
432 if (substr($aData[1],-2,1) != ' ')
434 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
435 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
437 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
438 if ($aGBPostcodeLocation)
440 $aValidTokens[$sToken] = $aGBPostcodeLocation;
445 foreach($aTokens as $sToken)
447 // Unknown single word token with a number - assume it is a house number
448 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
450 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
454 // Any words that have failed completely?
457 // Start the search process
458 $aResultPlaceIDs = array();
461 Calculate all searches using aValidTokens i.e.
463 'Wodsworth Road, Sheffield' =>
467 0 1 (wodsworth)(road)
470 Score how good the search is so they can be ordered
472 foreach($aPhrases as $iPhrase => $sPhrase)
474 $aNewPhraseSearches = array();
475 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
476 else $sPhraseType = '';
478 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
480 $aWordsetSearches = $aSearches;
482 // Add all words from this wordset
483 foreach($aWordset as $iToken => $sToken)
485 //echo "<br><b>$sToken</b>";
486 $aNewWordsetSearches = array();
488 foreach($aWordsetSearches as $aCurrentSearch)
491 //var_dump($aCurrentSearch);
494 // If the token is valid
495 if (isset($aValidTokens[' '.$sToken]))
497 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
499 $aSearch = $aCurrentSearch;
500 $aSearch['iSearchRank']++;
501 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
503 if ($aSearch['sCountryCode'] === false)
505 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
506 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
507 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
508 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
511 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
513 if ($aSearch['fLat'] === '')
515 $aSearch['fLat'] = $aSearchTerm['lat'];
516 $aSearch['fLon'] = $aSearchTerm['lon'];
517 $aSearch['fRadius'] = $aSearchTerm['radius'];
518 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
521 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
523 if ($aSearch['sHouseNumber'] === '')
525 $aSearch['sHouseNumber'] = $sToken;
526 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
528 // Fall back to not searching for this item (better than nothing)
529 $aSearch = $aCurrentSearch;
530 $aSearch['iSearchRank'] += 1;
531 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
535 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
537 if ($aSearch['sClass'] === '')
539 $aSearch['sOperator'] = $aSearchTerm['operator'];
540 $aSearch['sClass'] = $aSearchTerm['class'];
541 $aSearch['sType'] = $aSearchTerm['type'];
542 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
543 else $aSearch['sOperator'] = 'near'; // near = in for the moment
545 // Do we have a shortcut id?
546 if ($aSearch['sOperator'] == 'name')
548 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
549 if ($iAmenityID = $oDB->getOne($sSQL))
551 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
552 $aSearch['aName'][$iAmenityID] = $iAmenityID;
553 $aSearch['sClass'] = '';
554 $aSearch['sType'] = '';
557 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
560 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
562 if (sizeof($aSearch['aName']))
564 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
566 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
570 $aSearch['iSearchRank'] += 1000; // skip;
575 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
576 // $aSearch['iNamePhrase'] = $iPhrase;
578 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
582 if (isset($aValidTokens[$sToken]))
584 // Allow searching for a word - but at extra cost
585 foreach($aValidTokens[$sToken] as $aSearchTerm)
587 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
589 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
591 $aSearch = $aCurrentSearch;
592 $aSearch['iSearchRank'] += 1;
593 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
594 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
597 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
599 $aSearch = $aCurrentSearch;
600 $aSearch['iSearchRank'] += 2;
601 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
602 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
603 $aSearch['iNamePhrase'] = $iPhrase;
604 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
611 // Allow skipping a word - but at EXTREAM cost
612 //$aSearch = $aCurrentSearch;
613 //$aSearch['iSearchRank']+=100;
614 //$aNewWordsetSearches[] = $aSearch;
618 usort($aNewWordsetSearches, 'bySearchRank');
619 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
621 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
623 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
624 usort($aNewPhraseSearches, 'bySearchRank');
626 $aSearchHash = array();
627 foreach($aNewPhraseSearches as $iSearch => $aSearch)
629 $sHash = serialize($aSearch);
630 if (isset($aSearchHash[$sHash]))
632 unset($aNewPhraseSearches[$iSearch]);
636 $aSearchHash[$sHash] = 1;
640 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
643 // Re-group the searches by their score, junk anything over 20 as just not worth trying
644 $aGroupedSearches = array();
645 foreach($aNewPhraseSearches as $aSearch)
647 if ($aSearch['iSearchRank'] < $iMaxRank)
649 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
650 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
653 ksort($aGroupedSearches);
656 $aSearches = array();
657 foreach($aGroupedSearches as $iScore => $aNewSearches)
659 $iSearchCount += sizeof($aNewSearches);
660 $aSearches = array_merge($aSearches, $aNewSearches);
661 if ($iSearchCount > 50) break;
664 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
670 // Re-group the searches by their score, junk anything over 20 as just not worth trying
671 $aGroupedSearches = array();
672 foreach($aSearches as $aSearch)
674 if ($aSearch['iSearchRank'] < $iMaxRank)
676 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
677 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
680 ksort($aGroupedSearches);
683 if (CONST_Debug) var_Dump($aGroupedSearches);
687 $aCopyGroupedSearches = $aGroupedSearches;
688 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
690 foreach($aSearches as $iSearch => $aSearch)
692 if (sizeof($aSearch['aAddress']))
694 $iReverseItem = array_pop($aSearch['aAddress']);
695 if (isset($aPossibleMainWordIDs[$iReverseItem]))
697 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
698 $aSearch['aName'] = array($iReverseItem);
699 $aGroupedSearches[$iGroup][] = $aSearch;
701 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
702 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
708 // Filter out duplicate searches
709 $aSearchHash = array();
710 foreach($aGroupedSearches as $iGroup => $aSearches)
712 foreach($aSearches as $iSearch => $aSearch)
714 $sHash = serialize($aSearch);
715 if (isset($aSearchHash[$sHash]))
717 unset($aGroupedSearches[$iGroup][$iSearch]);
718 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
722 $aSearchHash[$sHash] = 1;
727 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
731 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
734 foreach($aSearches as $aSearch)
738 // Must have a location term
739 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
741 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
743 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
745 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
746 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
747 $sSQL .= " order by st_area(geometry) desc limit 1";
748 $aPlaceIDs = $oDB->getCol($sSQL);
753 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
754 if (!$aSearch['sClass']) continue;
755 if (CONST_Debug) var_dump('<hr>',$aSearch);
756 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
758 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
759 if ($oDB->getOne($sSQL))
761 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
762 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
763 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
764 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
765 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
766 $sSQL .= " limit $iLimit";
767 if (CONST_Debug) var_dump($sSQL);
768 $aPlaceIDs = $oDB->getCol($sSQL);
770 if (!sizeof($aPlaceIDs))
772 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
773 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
774 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
775 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
776 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
777 $sSQL .= " limit $iLimit";
778 if (CONST_Debug) var_dump($sSQL);
779 $aPlaceIDs = $oDB->getCol($sSQL);
784 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
785 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
786 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
787 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
788 $sSQL .= " limit $iLimit";
789 if (CONST_Debug) var_dump($sSQL);
790 $aPlaceIDs = $oDB->getCol($sSQL);
796 if (CONST_Debug) var_dump('<hr>',$aSearch);
797 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
798 $aPlaceIDs = array();
800 // First we need a position, either aName or fLat or both
804 // TODO: filter out the pointless search terms (2 letter name tokens and less)
805 // they might be right - but they are just too darned expensive to run
806 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
807 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
808 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
809 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
810 if ($aSearch['fLon'] && $aSearch['fLat'])
812 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
813 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
815 if (sizeof($aExcludePlaceIDs))
817 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
819 if ($sCountryCodesSQL)
821 $aTerms[] = "country_code in ($sCountryCodesSQL)";
824 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
825 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
827 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
829 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
830 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
831 $aOrder[] = "$sImportanceSQL DESC";
835 $sSQL = "select place_id";
836 $sSQL .= " from search_name";
837 $sSQL .= " where ".join(' and ',$aTerms);
838 $sSQL .= " order by ".join(', ',$aOrder);
839 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
840 $sSQL .= " limit 50";
841 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
844 $sSQL .= " limit ".$iLimit;
846 if (CONST_Debug) var_dump($sSQL);
847 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
848 if (PEAR::IsError($aViewBoxPlaceIDs))
850 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
852 //var_dump($aViewBoxPlaceIDs);
853 // Did we have an viewbox matches?
854 $aPlaceIDs = array();
855 $bViewBoxMatch = false;
856 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
858 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
859 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
860 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
861 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
862 $aPlaceIDs[] = $aViewBoxRow['place_id'];
865 //var_Dump($aPlaceIDs);
868 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
870 $aRoadPlaceIDs = $aPlaceIDs;
871 $sPlaceIDs = join(',',$aPlaceIDs);
873 // Now they are indexed look for a house attached to a street we found
874 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
875 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
876 if (sizeof($aExcludePlaceIDs))
878 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
880 $sSQL .= " limit $iLimit";
881 if (CONST_Debug) var_dump($sSQL);
882 $aPlaceIDs = $oDB->getCol($sSQL);
884 // If not try the aux fallback table
885 if (!sizeof($aPlaceIDs))
887 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
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);
897 if (!sizeof($aPlaceIDs))
899 $sSQL = "select place_id from location_property_tiger 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 // Fallback to the road
910 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
912 $aPlaceIDs = $aRoadPlaceIDs;
917 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
919 $sPlaceIDs = join(',',$aPlaceIDs);
921 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
923 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
924 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
925 $sSQL = " and linked_place_id is null";
926 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
927 $sSQL .= " order by rank_search asc limit $iLimit";
928 if (CONST_Debug) var_dump($sSQL);
929 $aPlaceIDs = $oDB->getCol($sSQL);
932 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
934 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
935 $bCacheTable = $oDB->getOne($sSQL);
937 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
939 if (CONST_Debug) var_dump($sSQL);
940 $iMaxRank = ((int)$oDB->getOne($sSQL));
942 // For state / country level searches the normal radius search doesn't work very well
944 if ($iMaxRank < 9 && $bCacheTable)
946 // Try and get a polygon to search in instead
947 $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";
948 if (CONST_Debug) var_dump($sSQL);
949 $sPlaceGeom = $oDB->getOne($sSQL);
959 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
960 if (CONST_Debug) var_dump($sSQL);
961 $aPlaceIDs = $oDB->getCol($sSQL);
962 $sPlaceIDs = join(',',$aPlaceIDs);
965 if ($sPlaceIDs || $sPlaceGeom)
971 // More efficient - can make the range bigger
975 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
976 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
977 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
979 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
980 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
983 $sSQL .= ",placex as f where ";
984 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
989 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
991 if (sizeof($aExcludePlaceIDs))
993 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
995 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
996 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
997 if ($iOffset) $sSQL .= " offset $iOffset";
998 $sSQL .= " limit $iLimit";
999 if (CONST_Debug) var_dump($sSQL);
1000 $aPlaceIDs = $oDB->getCol($sSQL);
1004 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1007 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1008 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1010 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1011 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1012 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1013 if (sizeof($aExcludePlaceIDs))
1015 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1017 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1018 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1019 if ($iOffset) $sSQL .= " offset $iOffset";
1020 $sSQL .= " limit $iLimit";
1021 if (CONST_Debug) var_dump($sSQL);
1022 $aPlaceIDs = $oDB->getCol($sSQL);
1030 if (PEAR::IsError($aPlaceIDs))
1032 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1035 if (CONST_Debug) var_Dump($aPlaceIDs);
1037 foreach($aPlaceIDs as $iPlaceID)
1039 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1041 if ($iQueryLoop > 20) break;
1044 if (sizeof($aResultPlaceIDs)) break;
1045 if ($iGroupLoop > 4) break;
1046 if ($iQueryLoop > 30) break;
1049 // Did we find anything?
1050 if (sizeof($aResultPlaceIDs))
1052 //var_Dump($aResultPlaceIDs);exit;
1053 // Get the details for display (is this a redundant extra step?)
1054 $sPlaceIDs = join(',',$aResultPlaceIDs);
1055 $sOrderSQL = 'CASE ';
1056 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1058 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1060 $sOrderSQL .= ' ELSE 10000000 END';
1061 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1062 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1063 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1064 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1065 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1066 // $sSQL .= $sOrderSQL." as porder, ";
1067 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1068 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1069 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1070 $sSQL .= "and linked_place_id is null ";
1071 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1072 if (!$bDeDupe) $sSQL .= ",place_id";
1073 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1074 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1075 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1077 $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,";
1078 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1079 $sSQL .= "null as placename,";
1080 $sSQL .= "null as ref,";
1081 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1082 // $sSQL .= $sOrderSQL." as porder, ";
1083 $sSQL .= "-0.15 as importance ";
1084 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1085 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1086 $sSQL .= "group by place_id";
1087 if (!$bDeDupe) $sSQL .= ",place_id";
1089 $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,";
1090 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1091 $sSQL .= "null as placename,";
1092 $sSQL .= "null as ref,";
1093 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1094 // $sSQL .= $sOrderSQL." as porder, ";
1095 $sSQL .= "-0.10 as importance ";
1096 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1097 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1098 $sSQL .= "group by place_id";
1099 if (!$bDeDupe) $sSQL .= ",place_id";
1100 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1101 $sSQL .= "order by importance desc";
1102 // $sSQL .= "order by rank_search,rank_address,porder asc";
1103 if (CONST_Debug) var_dump('<hr>',$sSQL);
1104 $aSearchResults = $oDB->getAll($sSQL);
1105 //var_dump($sSQL,$aSearchResults);exit;
1107 if (PEAR::IsError($aSearchResults))
1109 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1112 } // end if ($sQuery)
1115 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1117 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1118 $aResultPlaceIDs = array($iPlaceID);
1120 // TODO: this needs refactoring!
1122 // Get the details for display (is this a redundant extra step?)
1123 $sPlaceIDs = join(',',$aResultPlaceIDs);
1124 $sOrderSQL = 'CASE ';
1125 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1127 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1129 $sOrderSQL .= ' ELSE 10000000 END';
1130 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1131 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1132 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1133 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1134 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1135 // $sSQL .= $sOrderSQL." as porder, ";
1136 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1137 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1138 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1139 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1140 if (!$bDeDupe) $sSQL .= ",place_id";
1141 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1142 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1143 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1145 $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,";
1146 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1147 $sSQL .= "null as placename,";
1148 $sSQL .= "null as ref,";
1149 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1150 // $sSQL .= $sOrderSQL." as porder, ";
1151 $sSQL .= "-0.15 as importance ";
1152 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1153 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1154 $sSQL .= "group by place_id";
1155 if (!$bDeDupe) $sSQL .= ",place_id";
1157 $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,";
1158 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1159 $sSQL .= "null as placename,";
1160 $sSQL .= "null as ref,";
1161 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1162 // $sSQL .= $sOrderSQL." as porder, ";
1163 $sSQL .= "-0.10 as importance ";
1164 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1165 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1166 $sSQL .= "group by place_id";
1167 if (!$bDeDupe) $sSQL .= ",place_id";
1168 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1169 $sSQL .= "order by importance desc";
1170 // $sSQL .= "order by rank_search,rank_address,porder asc";
1171 if (CONST_Debug) var_dump('<hr>',$sSQL);
1172 $aSearchResults = $oDB->getAll($sSQL);
1173 //var_dump($sSQL,$aSearchResults);exit;
1175 if (PEAR::IsError($aSearchResults))
1177 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1183 $sSearchResult = '';
1184 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1186 $sSearchResult = 'No Results Found';
1188 //var_Dump($aSearchResults);
1190 $aClassType = getClassTypesWithImportance();
1191 $aRecheckWords = preg_split('/\b/',$sQuery);
1192 foreach($aRecheckWords as $i => $sWord)
1194 if (!$sWord) unset($aRecheckWords[$i]);
1196 foreach($aSearchResults as $iResNum => $aResult)
1198 if (CONST_Search_AreaPolygons)
1200 // Get the bounding box and outline polygon
1201 $sSQL = "select place_id,numfeatures,area,outline,";
1202 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1203 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1204 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1206 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1207 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1208 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1209 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1210 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1211 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1212 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1213 if ($bAsText) $sSQL .= ",ST_AsText(geometry) as astext";
1214 if ($bShowPolygons) $sSQL .= ",ST_AsText(geometry) as outlinestring";
1215 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1216 $aPointPolygon = $oDB->getRow($sSQL);
1217 if (PEAR::IsError($aPointPolygon))
1219 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1221 if ($aPointPolygon['place_id'])
1223 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1224 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1225 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1226 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1228 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1229 $aResult['lat'] = $aPointPolygon['centrelat'];
1230 $aResult['lon'] = $aPointPolygon['centrelon'];
1234 // Translate geometary string to point array
1235 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1237 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1239 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1241 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1243 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1246 $iSteps = ($fRadius * 40000)^2;
1247 $fStepSize = (2*pi())/$iSteps;
1248 $aPolyPoints = array();
1249 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1251 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1253 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1254 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1255 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1256 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1260 // Output data suitable for display (points and a bounding box)
1261 if ($bShowPolygons && isset($aPolyPoints))
1263 $aResult['aPolyPoints'] = array();
1264 foreach($aPolyPoints as $aPoint)
1266 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1269 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1273 if (!isset($aResult['aBoundingBox']))
1276 $fDiameter = 0.0001;
1278 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1279 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1281 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1283 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1284 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1286 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1288 $fRadius = $fDiameter / 2;
1290 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1291 $fStepSize = (2*pi())/$iSteps;
1292 $aPolyPoints = array();
1293 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1295 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1297 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1298 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1299 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1300 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1302 // Output data suitable for display (points and a bounding box)
1305 $aResult['aPolyPoints'] = array();
1306 foreach($aPolyPoints as $aPoint)
1308 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1311 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1314 // Is there an icon set for this type of result?
1315 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1316 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1318 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1321 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1322 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1324 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1327 if ($bShowAddressDetails)
1329 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1330 //var_dump($aResult['address']);
1334 // Adjust importance for the number of exact string matches in the result
1335 $aResult['importance'] = max(0.001,$aResult['importance']);
1337 $sAddress = $aResult['langaddress'];
1338 foreach($aRecheckWords as $i => $sWord)
1340 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1342 $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
1344 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1346 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1347 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1349 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1351 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1352 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1354 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1358 $aResult['importance'] = 1000000000000000;
1361 $aResult['name'] = $aResult['langaddress'];
1362 $aResult['foundorder'] = $iResNum;
1363 $aSearchResults[$iResNum] = $aResult;
1365 uasort($aSearchResults, 'byImportance');
1367 //var_dump($aSearchResults);exit;
1369 $aOSMIDDone = array();
1370 $aClassTypeNameDone = array();
1371 $aToFilter = $aSearchResults;
1372 $aSearchResults = array();
1375 foreach($aToFilter as $iResNum => $aResult)
1377 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1378 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1381 $fLat = $aResult['lat'];
1382 $fLon = $aResult['lon'];
1383 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1386 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1387 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1389 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1390 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1391 $aSearchResults[] = $aResult;
1394 // Absolute limit on number of results
1395 if (sizeof($aSearchResults) >= $iLimit) break;
1398 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1400 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1402 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1407 logEnd($oDB, $hLog, sizeof($aToFilter));
1409 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1410 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1411 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1412 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1413 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1414 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1417 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1419 $sMoreURL .= '&q='.urlencode($sQuery);
1421 if (CONST_Debug) exit;
1423 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');