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 $aResultPlaceIDs = 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 $aResultPlaceIDs = $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 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $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 $aResultPlaceIDs = array_merge($aResultPlaceIDs, $oDB->getCol($sSQL));
1050 $aPlaceIDs = $aResultPlaceIDs;
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;
1070 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1071 if ($iGroupLoop > 4) break;
1072 if ($iQueryLoop > 30) break;
1075 // Did we find anything?
1076 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1078 //var_Dump($aResultPlaceIDs);exit;
1079 // Get the details for display (is this a redundant extra step?)
1080 $sPlaceIDs = join(',',$aResultPlaceIDs);
1081 $sOrderSQL = 'CASE ';
1082 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1084 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1086 $sOrderSQL .= ' ELSE 10000000 END';
1087 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1088 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1089 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1090 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1091 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1092 // $sSQL .= $sOrderSQL." as porder, ";
1093 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1094 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1095 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1096 $sSQL .= "and linked_place_id is null ";
1097 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1098 if (!$bDeDupe) $sSQL .= ",place_id";
1099 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1100 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1101 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1103 $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,";
1104 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1105 $sSQL .= "null as placename,";
1106 $sSQL .= "null as ref,";
1107 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1108 // $sSQL .= $sOrderSQL." as porder, ";
1109 $sSQL .= "-0.15 as importance ";
1110 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1111 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1112 $sSQL .= "group by place_id";
1113 if (!$bDeDupe) $sSQL .= ",place_id";
1115 $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,";
1116 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1117 $sSQL .= "null as placename,";
1118 $sSQL .= "null as ref,";
1119 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1120 // $sSQL .= $sOrderSQL." as porder, ";
1121 $sSQL .= "-0.10 as importance ";
1122 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1123 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1124 $sSQL .= "group by place_id";
1125 if (!$bDeDupe) $sSQL .= ",place_id";
1126 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1127 $sSQL .= "order by importance desc";
1128 // $sSQL .= "order by rank_search,rank_address,porder asc";
1129 if (CONST_Debug) var_dump('<hr>',$sSQL);
1130 $aSearchResults = $oDB->getAll($sSQL);
1131 //var_dump($sSQL,$aSearchResults);exit;
1133 if (PEAR::IsError($aSearchResults))
1135 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1138 } // end if ($sQuery)
1141 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1143 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1144 $aResultPlaceIDs = array($iPlaceID);
1146 // TODO: this needs refactoring!
1148 // Get the details for display (is this a redundant extra step?)
1149 $sPlaceIDs = join(',',$aResultPlaceIDs);
1150 $sOrderSQL = 'CASE ';
1151 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1153 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1155 $sOrderSQL .= ' ELSE 10000000 END';
1156 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1157 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1158 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1159 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1160 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1161 // $sSQL .= $sOrderSQL." as porder, ";
1162 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1163 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1164 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1165 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1166 if (!$bDeDupe) $sSQL .= ",place_id";
1167 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1168 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1169 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1171 $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,";
1172 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1173 $sSQL .= "null as placename,";
1174 $sSQL .= "null as ref,";
1175 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1176 // $sSQL .= $sOrderSQL." as porder, ";
1177 $sSQL .= "-0.15 as importance ";
1178 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1179 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1180 $sSQL .= "group by place_id";
1181 if (!$bDeDupe) $sSQL .= ",place_id";
1183 $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,";
1184 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1185 $sSQL .= "null as placename,";
1186 $sSQL .= "null as ref,";
1187 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1188 // $sSQL .= $sOrderSQL." as porder, ";
1189 $sSQL .= "-0.10 as importance ";
1190 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1191 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1192 $sSQL .= "group by place_id";
1193 if (!$bDeDupe) $sSQL .= ",place_id";
1194 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1195 $sSQL .= "order by importance desc";
1196 // $sSQL .= "order by rank_search,rank_address,porder asc";
1197 if (CONST_Debug) var_dump('<hr>',$sSQL);
1198 $aSearchResults = $oDB->getAll($sSQL);
1199 //var_dump($sSQL,$aSearchResults);exit;
1201 if (PEAR::IsError($aSearchResults))
1203 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1209 $sSearchResult = '';
1210 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1212 $sSearchResult = 'No Results Found';
1214 //var_Dump($aSearchResults);
1216 $aClassType = getClassTypesWithImportance();
1217 $aRecheckWords = preg_split('/\b/',$sQuery);
1218 foreach($aRecheckWords as $i => $sWord)
1220 if (!$sWord) unset($aRecheckWords[$i]);
1222 foreach($aSearchResults as $iResNum => $aResult)
1224 if (CONST_Search_AreaPolygons)
1226 // Get the bounding box and outline polygon
1227 $sSQL = "select place_id,numfeatures,area,outline,";
1228 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1229 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1230 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1232 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1233 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1234 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1235 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1236 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1237 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1238 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1239 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1240 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1241 $aPointPolygon = $oDB->getRow($sSQL);
1242 if (PEAR::IsError($aPointPolygon))
1244 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1246 if ($aPointPolygon['place_id'])
1248 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1249 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1250 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1251 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1253 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1254 $aResult['lat'] = $aPointPolygon['centrelat'];
1255 $aResult['lon'] = $aPointPolygon['centrelon'];
1259 // Translate geometary string to point array
1260 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1262 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1264 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1266 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1268 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1271 $iSteps = ($fRadius * 40000)^2;
1272 $fStepSize = (2*pi())/$iSteps;
1273 $aPolyPoints = array();
1274 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1276 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1278 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1279 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1280 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1281 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1285 // Output data suitable for display (points and a bounding box)
1286 if ($bShowPolygons && isset($aPolyPoints))
1288 $aResult['aPolyPoints'] = array();
1289 foreach($aPolyPoints as $aPoint)
1291 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1294 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1298 if (!isset($aResult['aBoundingBox']))
1301 $fDiameter = 0.0001;
1303 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1304 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1306 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1308 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1309 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1311 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1313 $fRadius = $fDiameter / 2;
1315 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1316 $fStepSize = (2*pi())/$iSteps;
1317 $aPolyPoints = array();
1318 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1320 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1322 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1323 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1324 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1325 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1327 // Output data suitable for display (points and a bounding box)
1330 $aResult['aPolyPoints'] = array();
1331 foreach($aPolyPoints as $aPoint)
1333 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1336 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1339 // Is there an icon set for this type of result?
1340 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1341 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1343 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1346 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1347 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1349 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1352 if ($bShowAddressDetails)
1354 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1355 //var_dump($aResult['address']);
1359 // Adjust importance for the number of exact string matches in the result
1360 $aResult['importance'] = max(0.001,$aResult['importance']);
1362 $sAddress = $aResult['langaddress'];
1363 foreach($aRecheckWords as $i => $sWord)
1365 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1367 $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
1369 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1371 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1372 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1374 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1376 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1377 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1379 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1383 $aResult['importance'] = 1000000000000000;
1386 $aResult['name'] = $aResult['langaddress'];
1387 $aResult['foundorder'] = $iResNum;
1388 $aSearchResults[$iResNum] = $aResult;
1390 uasort($aSearchResults, 'byImportance');
1392 //var_dump($aSearchResults);exit;
1394 $aOSMIDDone = array();
1395 $aClassTypeNameDone = array();
1396 $aToFilter = $aSearchResults;
1397 $aSearchResults = array();
1400 foreach($aToFilter as $iResNum => $aResult)
1402 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1403 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1406 $fLat = $aResult['lat'];
1407 $fLon = $aResult['lon'];
1408 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1411 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1412 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1414 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1415 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1416 $aSearchResults[] = $aResult;
1419 // Absolute limit on number of results
1420 if (sizeof($aSearchResults) >= $iLimit) break;
1423 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1425 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1427 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1432 logEnd($oDB, $hLog, sizeof($aToFilter));
1434 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1435 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1436 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1437 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1438 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1439 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1442 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1444 $sMoreURL .= '&q='.urlencode($sQuery);
1446 if (CONST_Debug) exit;
1448 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');