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 if ($sOutputFormat == 'html') {
36 $bAsText = $bShowPolygons;
37 $bShowPolygons = false;
42 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
43 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
44 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
45 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
46 if ((($bShowPolygons?1:0)
51 ) > CONST_PolygonOutput_MaximumTypes) {
52 if (CONST_PolygonOutput_MaximumTypes) {
53 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
55 userError("Polygon output is disabled");
61 // Show address breakdown
62 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
65 $aLangPrefOrder = getPreferredLanguages();
66 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
67 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
68 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
70 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
72 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
74 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
76 $iExcludedPlaceID = (int)$iExcludedPlaceID;
77 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
81 // Only certain ranks of feature
82 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
84 if (isset($_GET['featuretype']))
86 switch($_GET['featuretype'])
89 $iMinAddressRank = $iMaxAddressRank = 4;
92 $iMinAddressRank = $iMaxAddressRank = 8;
95 $iMinAddressRank = 14;
96 $iMaxAddressRank = 16;
100 $iMaxAddressRank = 20;
105 if (isset($_GET['countrycodes']))
107 $aCountryCodes = array();
108 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
110 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
112 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
115 $sCountryCodesSQL = join(',', $aCountryCodes);
119 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
120 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
122 $sQuery = substr($_SERVER['PATH_INFO'], 1);
124 // reverse order of '/' separated string
125 $aPhrases = explode('/', $sQuery);
126 $aPhrases = array_reverse($aPhrases);
127 $sQuery = join(', ',$aPhrases);
130 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
132 if (!isset($_GET[$sKey])) return false;
133 $sValue = trim($_GET[$sKey]);
134 if (!$sValue) return false;
135 $aStructuredQuery[$sKey] = $sValue;
136 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
137 $iMinAddressRank = $iNewMinAddressRank;
138 $iMaxAddressRank = $iNewMaxAddressRank;
144 $aStructuredOptions = array(
145 array('amenity', 26, 30),
146 array('street', 26, 30),
147 array('city', 14, 24),
148 array('county', 9, 13),
149 array('state', 8, 8),
150 array('country', 4, 4),
151 array('postalcode', 16, 25),
153 $aStructuredQuery = array();
154 foreach($aStructuredOptions as $aStructuredOption)
156 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
158 if (sizeof($aStructuredQuery) > 0) {
159 $sQuery = join(', ', $aStructuredQuery);
164 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
166 // Hack to make it handle "new york, ny" (and variants) correctly
167 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
168 if (isset($aLangPrefOrder['name:en']))
170 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
171 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
172 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
175 // If we have a view box create the SQL
176 // Small is the actual view box, Large is double (on each axis) that
177 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
178 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
180 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
181 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
183 if (isset($_GET['viewbox']) && $_GET['viewbox'])
185 $aCoOrdinates = explode(',',$_GET['viewbox']);
186 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
187 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
188 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
189 $aCoOrdinates[0] += $fHeight;
190 $aCoOrdinates[2] -= $fHeight;
191 $aCoOrdinates[1] += $fWidth;
192 $aCoOrdinates[3] -= $fWidth;
193 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
195 $bBoundingBoxSearch = false;
197 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
199 $aPoints = explode(',',$_GET['route']);
200 if (sizeof($aPoints) % 2 != 0)
202 userError("Uneven number of points");
205 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
207 foreach($aPoints as $i => $fPoint)
211 if ($i != 1) $sViewboxCentreSQL .= ",";
212 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
216 $fPrevCoord = (float)$fPoint;
219 $sViewboxCentreSQL .= ")'::geometry,4326)";
221 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
222 $sViewboxSmallSQL = $oDB->getOne($sSQL);
223 if (PEAR::isError($sViewboxSmallSQL))
225 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
227 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
229 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
230 $sViewboxLargeSQL = $oDB->getOne($sSQL);
231 if (PEAR::isError($sViewboxLargeSQL))
233 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
235 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
236 $bBoundingBoxSearch = true;
239 // Do we have anything that looks like a lat/lon pair?
240 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
242 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
243 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
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));
251 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
253 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
254 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
255 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
257 $_GET['nearlat'] = $fQueryLat;
258 $_GET['nearlon'] = $fQueryLon;
259 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
262 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
264 $fQueryLat = $aData[2];
265 $fQueryLon = $aData[3];
266 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
268 $_GET['nearlat'] = $fQueryLat;
269 $_GET['nearlon'] = $fQueryLon;
270 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
274 if ($sQuery || $aStructuredQuery)
276 // Start with a blank search
278 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
279 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
282 $sNearPointSQL = false;
283 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
285 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
286 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
287 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
288 $aSearches[0]['fRadius'] = 0.1;
291 $bSpecialTerms = false;
292 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
293 $aSpecialTerms = array();
294 foreach($aSpecialTermsRaw as $aSpecialTerm)
296 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
297 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
300 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
301 $aSpecialTerms = array();
302 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
304 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
305 unset($aStructuredQuery['amenity']);
307 foreach($aSpecialTermsRaw as $aSpecialTerm)
309 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
310 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
311 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
312 $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';
313 if (CONST_Debug) var_Dump($sSQL);
314 $aSearchWords = $oDB->getAll($sSQL);
315 $aNewSearches = array();
316 foreach($aSearches as $aSearch)
318 foreach($aSearchWords as $aSearchTerm)
320 $aNewSearch = $aSearch;
321 if ($aSearchTerm['country_code'])
323 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
324 $aNewSearches[] = $aNewSearch;
325 $bSpecialTerms = true;
327 if ($aSearchTerm['class'])
329 $aNewSearch['sClass'] = $aSearchTerm['class'];
330 $aNewSearch['sType'] = $aSearchTerm['type'];
331 $aNewSearches[] = $aNewSearch;
332 $bSpecialTerms = true;
336 $aSearches = $aNewSearches;
339 // Split query into phrases
340 // Commas are used to reduce the search space by indicating where phrases split
341 if (sizeof($aStructuredQuery) > 0)
343 $aPhrases = $aStructuredQuery;
344 $bStructuredPhrases = true;
348 $aPhrases = explode(',',$sQuery);
349 $bStructuredPhrases = false;
353 // Convert each phrase to standard form
354 // Create a list of standard words
355 // Get all 'sets' of words
356 // Generate a complete list of all
358 foreach($aPhrases as $iPhrase => $sPhrase)
360 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
361 if (PEAR::isError($aPhrase))
363 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
364 if (CONST_Debug) var_dump($aPhrase);
367 if (trim($aPhrase['string']))
369 $aPhrases[$iPhrase] = $aPhrase;
370 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
371 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
372 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
376 unset($aPhrases[$iPhrase]);
380 // reindex phrases - we make assumptions later on
381 $aPhraseTypes = array_keys($aPhrases);
382 $aPhrases = array_values($aPhrases);
384 if (sizeof($aTokens))
387 // Check which tokens we have, get the ID numbers
388 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
389 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
390 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
391 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
393 if (CONST_Debug) var_Dump($sSQL);
395 $aValidTokens = array();
396 if (sizeof($aTokens))
397 $aDatabaseWords = $oDB->getAll($sSQL);
399 $aDatabaseWords = array();
400 if (PEAR::IsError($aDatabaseWords))
402 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
404 $aPossibleMainWordIDs = array();
405 foreach($aDatabaseWords as $aToken)
407 if (isset($aValidTokens[$aToken['word_token']]))
409 $aValidTokens[$aToken['word_token']][] = $aToken;
413 $aValidTokens[$aToken['word_token']] = array($aToken);
415 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
417 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
419 $aSuggestion = array();
420 $bSuggestion = false;
421 if (CONST_Suggestions_Enabled)
423 foreach($aPhrases as $iPhrase => $aPhrase)
425 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
427 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
428 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
429 $aRow = $aSuggestionWords[0];
430 if ($aRow && $aRow['word'])
432 $aSuggestion[] = $aRow['word'];
437 $aSuggestion[] = $aPhrase['string'];
442 $aSuggestion[] = $aPhrase['string'];
446 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
448 // Try and calculate GB postcodes we might be missing
449 foreach($aTokens as $sToken)
451 // Source of gb postcodes is now definitive - always use
452 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
454 if (substr($aData[1],-2,1) != ' ')
456 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
457 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
459 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
460 if ($aGBPostcodeLocation)
462 $aValidTokens[$sToken] = $aGBPostcodeLocation;
467 foreach($aTokens as $sToken)
469 // Unknown single word token with a number - assume it is a house number
470 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
472 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
476 // Any words that have failed completely?
479 // Start the search process
480 $aResultPlaceIDs = array();
483 Calculate all searches using aValidTokens i.e.
485 'Wodsworth Road, Sheffield' =>
489 0 1 (wodsworth)(road)
492 Score how good the search is so they can be ordered
494 foreach($aPhrases as $iPhrase => $sPhrase)
496 $aNewPhraseSearches = array();
497 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
498 else $sPhraseType = '';
500 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
502 $aWordsetSearches = $aSearches;
504 // Add all words from this wordset
505 foreach($aWordset as $iToken => $sToken)
507 //echo "<br><b>$sToken</b>";
508 $aNewWordsetSearches = array();
510 foreach($aWordsetSearches as $aCurrentSearch)
513 //var_dump($aCurrentSearch);
516 // If the token is valid
517 if (isset($aValidTokens[' '.$sToken]))
519 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
521 $aSearch = $aCurrentSearch;
522 $aSearch['iSearchRank']++;
523 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
525 if ($aSearch['sCountryCode'] === false)
527 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
528 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
529 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
530 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
533 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
535 if ($aSearch['fLat'] === '')
537 $aSearch['fLat'] = $aSearchTerm['lat'];
538 $aSearch['fLon'] = $aSearchTerm['lon'];
539 $aSearch['fRadius'] = $aSearchTerm['radius'];
540 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
543 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
545 if ($aSearch['sHouseNumber'] === '')
547 $aSearch['sHouseNumber'] = $sToken;
548 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
550 // Fall back to not searching for this item (better than nothing)
551 $aSearch = $aCurrentSearch;
552 $aSearch['iSearchRank'] += 1;
553 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
557 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
559 if ($aSearch['sClass'] === '')
561 $aSearch['sOperator'] = $aSearchTerm['operator'];
562 $aSearch['sClass'] = $aSearchTerm['class'];
563 $aSearch['sType'] = $aSearchTerm['type'];
564 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
565 else $aSearch['sOperator'] = 'near'; // near = in for the moment
567 // Do we have a shortcut id?
568 if ($aSearch['sOperator'] == 'name')
570 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
571 if ($iAmenityID = $oDB->getOne($sSQL))
573 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
574 $aSearch['aName'][$iAmenityID] = $iAmenityID;
575 $aSearch['sClass'] = '';
576 $aSearch['sType'] = '';
579 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
582 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
584 if (sizeof($aSearch['aName']))
586 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
588 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
592 $aSearch['iSearchRank'] += 1000; // skip;
597 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
598 // $aSearch['iNamePhrase'] = $iPhrase;
600 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
604 if (isset($aValidTokens[$sToken]))
606 // Allow searching for a word - but at extra cost
607 foreach($aValidTokens[$sToken] as $aSearchTerm)
609 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
611 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
613 $aSearch = $aCurrentSearch;
614 $aSearch['iSearchRank'] += 1;
615 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
616 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
619 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
621 $aSearch = $aCurrentSearch;
622 $aSearch['iSearchRank'] += 2;
623 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
624 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
625 $aSearch['iNamePhrase'] = $iPhrase;
626 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
633 // Allow skipping a word - but at EXTREAM cost
634 //$aSearch = $aCurrentSearch;
635 //$aSearch['iSearchRank']+=100;
636 //$aNewWordsetSearches[] = $aSearch;
640 usort($aNewWordsetSearches, 'bySearchRank');
641 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
643 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
645 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
646 usort($aNewPhraseSearches, 'bySearchRank');
648 $aSearchHash = array();
649 foreach($aNewPhraseSearches as $iSearch => $aSearch)
651 $sHash = serialize($aSearch);
652 if (isset($aSearchHash[$sHash]))
654 unset($aNewPhraseSearches[$iSearch]);
658 $aSearchHash[$sHash] = 1;
662 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
665 // Re-group the searches by their score, junk anything over 20 as just not worth trying
666 $aGroupedSearches = array();
667 foreach($aNewPhraseSearches as $aSearch)
669 if ($aSearch['iSearchRank'] < $iMaxRank)
671 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
672 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
675 ksort($aGroupedSearches);
678 $aSearches = array();
679 foreach($aGroupedSearches as $iScore => $aNewSearches)
681 $iSearchCount += sizeof($aNewSearches);
682 $aSearches = array_merge($aSearches, $aNewSearches);
683 if ($iSearchCount > 50) break;
686 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
692 // Re-group the searches by their score, junk anything over 20 as just not worth trying
693 $aGroupedSearches = array();
694 foreach($aSearches as $aSearch)
696 if ($aSearch['iSearchRank'] < $iMaxRank)
698 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
699 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
702 ksort($aGroupedSearches);
705 if (CONST_Debug) var_Dump($aGroupedSearches);
709 $aCopyGroupedSearches = $aGroupedSearches;
710 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
712 foreach($aSearches as $iSearch => $aSearch)
714 if (sizeof($aSearch['aAddress']))
716 $iReverseItem = array_pop($aSearch['aAddress']);
717 if (isset($aPossibleMainWordIDs[$iReverseItem]))
719 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
720 $aSearch['aName'] = array($iReverseItem);
721 $aGroupedSearches[$iGroup][] = $aSearch;
723 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
724 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
730 // Filter out duplicate searches
731 $aSearchHash = array();
732 foreach($aGroupedSearches as $iGroup => $aSearches)
734 foreach($aSearches as $iSearch => $aSearch)
736 $sHash = serialize($aSearch);
737 if (isset($aSearchHash[$sHash]))
739 unset($aGroupedSearches[$iGroup][$iSearch]);
740 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
744 $aSearchHash[$sHash] = 1;
749 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
753 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
756 foreach($aSearches as $aSearch)
760 // Must have a location term
761 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
763 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
765 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
767 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
768 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
769 $sSQL .= " order by st_area(geometry) desc limit 1";
770 $aPlaceIDs = $oDB->getCol($sSQL);
775 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
776 if (!$aSearch['sClass']) continue;
777 if (CONST_Debug) var_dump('<hr>',$aSearch);
778 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
779 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
780 if ($oDB->getOne($sSQL))
782 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
783 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
784 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
785 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
786 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
787 $sSQL .= " limit $iLimit";
788 if (CONST_Debug) var_dump($sSQL);
789 $aPlaceIDs = $oDB->getCol($sSQL);
791 if (!sizeof($aPlaceIDs))
793 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
794 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
795 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
796 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
797 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
798 $sSQL .= " limit $iLimit";
799 if (CONST_Debug) var_dump($sSQL);
800 $aPlaceIDs = $oDB->getCol($sSQL);
805 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
806 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
807 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
808 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
809 $sSQL .= " limit $iLimit";
810 if (CONST_Debug) var_dump($sSQL);
811 $aPlaceIDs = $oDB->getCol($sSQL);
817 if (CONST_Debug) var_dump('<hr>',$aSearch);
818 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
819 $aPlaceIDs = array();
821 // First we need a position, either aName or fLat or both
825 // TODO: filter out the pointless search terms (2 letter name tokens and less)
826 // they might be right - but they are just too darned expensive to run
827 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
828 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
829 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
830 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
831 if ($aSearch['fLon'] && $aSearch['fLat'])
833 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
834 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
836 if (sizeof($aExcludePlaceIDs))
838 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
840 if ($sCountryCodesSQL)
842 $aTerms[] = "country_code in ($sCountryCodesSQL)";
845 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
846 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
848 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
850 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
851 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
852 $aOrder[] = "$sImportanceSQL DESC";
856 $sSQL = "select place_id";
857 $sSQL .= " from search_name";
858 $sSQL .= " where ".join(' and ',$aTerms);
859 $sSQL .= " order by ".join(', ',$aOrder);
860 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
861 $sSQL .= " limit 50";
862 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
865 $sSQL .= " limit ".$iLimit;
867 if (CONST_Debug) var_dump($sSQL);
868 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
869 if (PEAR::IsError($aViewBoxPlaceIDs))
871 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
873 //var_dump($aViewBoxPlaceIDs);
874 // Did we have an viewbox matches?
875 $aPlaceIDs = array();
876 $bViewBoxMatch = false;
877 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
879 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
880 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
881 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
882 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
883 $aPlaceIDs[] = $aViewBoxRow['place_id'];
886 //var_Dump($aPlaceIDs);
889 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
891 $aRoadPlaceIDs = $aPlaceIDs;
892 $sPlaceIDs = join(',',$aPlaceIDs);
894 // Now they are indexed look for a house attached to a street we found
895 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
896 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
897 if (sizeof($aExcludePlaceIDs))
899 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
901 $sSQL .= " limit $iLimit";
902 if (CONST_Debug) var_dump($sSQL);
903 $aPlaceIDs = $oDB->getCol($sSQL);
905 // If not try the aux fallback table
906 if (!sizeof($aPlaceIDs))
908 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
909 if (sizeof($aExcludePlaceIDs))
911 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
913 // $sSQL .= " limit $iLimit";
914 if (CONST_Debug) var_dump($sSQL);
915 $aPlaceIDs = $oDB->getCol($sSQL);
918 if (!sizeof($aPlaceIDs))
920 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
921 if (sizeof($aExcludePlaceIDs))
923 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
925 // $sSQL .= " limit $iLimit";
926 if (CONST_Debug) var_dump($sSQL);
927 $aPlaceIDs = $oDB->getCol($sSQL);
930 // Fallback to the road
931 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
933 $aPlaceIDs = $aRoadPlaceIDs;
938 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
940 $sPlaceIDs = join(',',$aPlaceIDs);
942 $aClassPlaceIDs = array();
944 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
946 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
947 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
948 $sSQL .= " and linked_place_id is null";
949 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
950 $sSQL .= " order by rank_search asc limit $iLimit";
951 if (CONST_Debug) var_dump($sSQL);
952 $aClassPlaceIDs = $oDB->getCol($sSQL);
955 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
957 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
958 $bCacheTable = $oDB->getOne($sSQL);
960 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
962 if (CONST_Debug) var_dump($sSQL);
963 $iMaxRank = ((int)$oDB->getOne($sSQL));
965 // For state / country level searches the normal radius search doesn't work very well
967 if ($iMaxRank < 9 && $bCacheTable)
969 // Try and get a polygon to search in instead
970 $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";
971 if (CONST_Debug) var_dump($sSQL);
972 $sPlaceGeom = $oDB->getOne($sSQL);
982 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
983 if (CONST_Debug) var_dump($sSQL);
984 $aPlaceIDs = $oDB->getCol($sSQL);
985 $sPlaceIDs = join(',',$aPlaceIDs);
988 if ($sPlaceIDs || $sPlaceGeom)
994 // More efficient - can make the range bigger
998 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
999 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1000 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1002 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1003 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1006 $sSQL .= ",placex as f where ";
1007 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1012 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1014 if (sizeof($aExcludePlaceIDs))
1016 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1018 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1019 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1020 if ($iOffset) $sSQL .= " offset $iOffset";
1021 $sSQL .= " limit $iLimit";
1022 if (CONST_Debug) var_dump($sSQL);
1023 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1027 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1030 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1031 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1033 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1034 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1035 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1036 if (sizeof($aExcludePlaceIDs))
1038 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1040 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1041 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1042 if ($iOffset) $sSQL .= " offset $iOffset";
1043 $sSQL .= " limit $iLimit";
1044 if (CONST_Debug) var_dump($sSQL);
1045 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1050 $aPlaceIDs = $aClassPlaceIDs;
1056 if (PEAR::IsError($aPlaceIDs))
1058 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1061 if (CONST_Debug) var_Dump($aPlaceIDs);
1063 foreach($aPlaceIDs as $iPlaceID)
1065 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1067 if ($iQueryLoop > 20) break;
1071 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1072 if ($iGroupLoop > 4) break;
1073 if ($iQueryLoop > 30) break;
1076 // Did we find anything?
1077 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1079 //var_Dump($aResultPlaceIDs);exit;
1080 // Get the details for display (is this a redundant extra step?)
1081 $sPlaceIDs = join(',',$aResultPlaceIDs);
1082 $sOrderSQL = 'CASE ';
1083 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1085 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1087 $sOrderSQL .= ' ELSE 10000000 END';
1088 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1089 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1090 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1091 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1092 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1093 // $sSQL .= $sOrderSQL." as porder, ";
1094 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1095 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1096 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1097 $sSQL .= "and linked_place_id is null ";
1098 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1099 if (!$bDeDupe) $sSQL .= ",place_id";
1100 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1101 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1102 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1104 $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,";
1105 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1106 $sSQL .= "null as placename,";
1107 $sSQL .= "null as ref,";
1108 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1109 // $sSQL .= $sOrderSQL." as porder, ";
1110 $sSQL .= "-0.15 as importance ";
1111 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1112 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1113 $sSQL .= "group by place_id";
1114 if (!$bDeDupe) $sSQL .= ",place_id";
1116 $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,";
1117 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1118 $sSQL .= "null as placename,";
1119 $sSQL .= "null as ref,";
1120 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1121 // $sSQL .= $sOrderSQL." as porder, ";
1122 $sSQL .= "-0.10 as importance ";
1123 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1124 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1125 $sSQL .= "group by place_id";
1126 if (!$bDeDupe) $sSQL .= ",place_id";
1127 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1128 $sSQL .= "order by importance desc";
1129 // $sSQL .= "order by rank_search,rank_address,porder asc";
1130 if (CONST_Debug) var_dump('<hr>',$sSQL);
1131 $aSearchResults = $oDB->getAll($sSQL);
1132 //var_dump($sSQL,$aSearchResults);exit;
1134 if (PEAR::IsError($aSearchResults))
1136 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1139 } // end if ($sQuery)
1142 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1144 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1145 $aResultPlaceIDs = array($iPlaceID);
1147 // TODO: this needs refactoring!
1149 // Get the details for display (is this a redundant extra step?)
1150 $sPlaceIDs = join(',',$aResultPlaceIDs);
1151 $sOrderSQL = 'CASE ';
1152 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1154 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1156 $sOrderSQL .= ' ELSE 10000000 END';
1157 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1158 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1159 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1160 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1161 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1162 // $sSQL .= $sOrderSQL." as porder, ";
1163 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1164 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1165 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1166 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1167 if (!$bDeDupe) $sSQL .= ",place_id";
1168 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1169 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1170 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1172 $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,";
1173 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1174 $sSQL .= "null as placename,";
1175 $sSQL .= "null as ref,";
1176 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1177 // $sSQL .= $sOrderSQL." as porder, ";
1178 $sSQL .= "-0.15 as importance ";
1179 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1180 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1181 $sSQL .= "group by place_id";
1182 if (!$bDeDupe) $sSQL .= ",place_id";
1184 $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,";
1185 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1186 $sSQL .= "null as placename,";
1187 $sSQL .= "null as ref,";
1188 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1189 // $sSQL .= $sOrderSQL." as porder, ";
1190 $sSQL .= "-0.10 as importance ";
1191 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1192 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1193 $sSQL .= "group by place_id";
1194 if (!$bDeDupe) $sSQL .= ",place_id";
1195 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1196 $sSQL .= "order by importance desc";
1197 // $sSQL .= "order by rank_search,rank_address,porder asc";
1198 if (CONST_Debug) var_dump('<hr>',$sSQL);
1199 $aSearchResults = $oDB->getAll($sSQL);
1200 //var_dump($sSQL,$aSearchResults);exit;
1202 if (PEAR::IsError($aSearchResults))
1204 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1210 $sSearchResult = '';
1211 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1213 $sSearchResult = 'No Results Found';
1215 //var_Dump($aSearchResults);
1217 $aClassType = getClassTypesWithImportance();
1218 $aRecheckWords = preg_split('/\b/',$sQuery);
1219 foreach($aRecheckWords as $i => $sWord)
1221 if (!$sWord) unset($aRecheckWords[$i]);
1223 foreach($aSearchResults as $iResNum => $aResult)
1225 if (CONST_Search_AreaPolygons)
1227 // Get the bounding box and outline polygon
1228 $sSQL = "select place_id,numfeatures,area,outline,";
1229 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1230 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1231 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1233 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1234 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1235 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1236 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1237 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1238 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1239 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1240 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1241 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1242 $aPointPolygon = $oDB->getRow($sSQL);
1243 if (PEAR::IsError($aPointPolygon))
1245 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1247 if ($aPointPolygon['place_id'])
1249 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1250 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1251 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1252 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1254 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1255 $aResult['lat'] = $aPointPolygon['centrelat'];
1256 $aResult['lon'] = $aPointPolygon['centrelon'];
1260 // Translate geometary string to point array
1261 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1263 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1265 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1267 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1269 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1272 $iSteps = ($fRadius * 40000)^2;
1273 $fStepSize = (2*pi())/$iSteps;
1274 $aPolyPoints = array();
1275 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1277 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1279 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1280 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1281 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1282 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1286 // Output data suitable for display (points and a bounding box)
1287 if ($bShowPolygons && isset($aPolyPoints))
1289 $aResult['aPolyPoints'] = array();
1290 foreach($aPolyPoints as $aPoint)
1292 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1295 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1299 if (!isset($aResult['aBoundingBox']))
1302 $fDiameter = 0.0001;
1304 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1305 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1307 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1309 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1310 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1312 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1314 $fRadius = $fDiameter / 2;
1316 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1317 $fStepSize = (2*pi())/$iSteps;
1318 $aPolyPoints = array();
1319 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1321 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1323 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1324 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1325 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1326 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1328 // Output data suitable for display (points and a bounding box)
1331 $aResult['aPolyPoints'] = array();
1332 foreach($aPolyPoints as $aPoint)
1334 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1337 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1340 // Is there an icon set for this type of result?
1341 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1342 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1344 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1347 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1348 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1350 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1353 if ($bShowAddressDetails)
1355 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1356 //var_dump($aResult['address']);
1360 // Adjust importance for the number of exact string matches in the result
1361 $aResult['importance'] = max(0.001,$aResult['importance']);
1363 $sAddress = $aResult['langaddress'];
1364 foreach($aRecheckWords as $i => $sWord)
1366 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1368 $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
1370 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1372 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1373 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1375 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1377 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1378 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1380 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1384 $aResult['importance'] = 1000000000000000;
1387 $aResult['name'] = $aResult['langaddress'];
1388 $aResult['foundorder'] = $iResNum;
1389 $aSearchResults[$iResNum] = $aResult;
1391 uasort($aSearchResults, 'byImportance');
1393 //var_dump($aSearchResults);exit;
1395 $aOSMIDDone = array();
1396 $aClassTypeNameDone = array();
1397 $aToFilter = $aSearchResults;
1398 $aSearchResults = array();
1401 foreach($aToFilter as $iResNum => $aResult)
1403 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1404 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1407 $fLat = $aResult['lat'];
1408 $fLon = $aResult['lon'];
1409 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1412 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1413 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1415 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1416 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1417 $aSearchResults[] = $aResult;
1420 // Absolute limit on number of results
1421 if (sizeof($aSearchResults) >= $iLimit) break;
1424 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1426 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1428 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1433 logEnd($oDB, $hLog, sizeof($aToFilter));
1435 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1436 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1437 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1438 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1439 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1440 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1443 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1445 $sMoreURL .= '&q='.urlencode($sQuery);
1447 if (CONST_Debug) exit;
1449 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');