2 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
3 require_once(CONST_BasePath.'/lib/log.php');
5 ini_set('memory_limit', '200M');
9 $fLat = CONST_Default_Lat;
10 $fLon = CONST_Default_Lon;
11 $iZoom = CONST_Default_Zoom;
12 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
13 $sOutputFormat = 'html';
14 $aSearchResults = array();
15 $aExcludePlaceIDs = array();
16 $sCountryCodesSQL = false;
17 $sSuggestion = $sSuggestionURL = false;
18 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
19 $bReverseInPlan = false;
20 $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iLimit > 100) $iLimit = 100;
25 $iMaxAddressRank = 30;
28 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
30 $sOutputFormat = $_GET['format'];
33 // Show / use polygons
34 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
35 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
36 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
37 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
38 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
39 if ((($bShowPolygons?1:0)
45 echo "Select only one polgyon output option";
49 // Show address breakdown
50 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
53 $aLangPrefOrder = getPreferredLanguages();
54 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
55 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
56 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
58 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
60 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
62 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
64 $iExcludedPlaceID = (int)$iExcludedPlaceID;
65 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
69 // Only certain ranks of feature
70 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
72 if (isset($_GET['featuretype']))
74 switch($_GET['featuretype'])
77 $iMinAddressRank = $iMaxAddressRank = 4;
80 $iMinAddressRank = $iMaxAddressRank = 8;
83 $iMinAddressRank = 14;
84 $iMaxAddressRank = 16;
88 $iMaxAddressRank = 20;
93 if (isset($_GET['countrycodes']))
95 $aCountryCodes = array();
96 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
98 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
100 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
103 $sCountryCodesSQL = join(',', $aCountryCodes);
107 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
108 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
110 $sQuery = substr($_SERVER['PATH_INFO'], 1);
112 // reverse order of '/' separated string
113 $aPhrases = explode('/', $sQuery);
114 $aPhrases = array_reverse($aPhrases);
115 $sQuery = join(', ',$aPhrases);
118 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
120 if (!isset($_GET[$sKey])) return false;
121 $sValue = trim($_GET[$sKey]);
122 if (!$sValue) return false;
123 $aStructuredQuery[$sKey] = $sValue;
124 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
125 $iMinAddressRank = $iNewMinAddressRank;
126 $iMaxAddressRank = $iNewMaxAddressRank;
132 $aStructuredOptions = array(
133 array('amenity', 26, 30),
134 array('street', 26, 30),
135 array('city', 14, 24),
136 array('county', 9, 13),
137 array('state', 8, 8),
138 array('country', 4, 4),
139 array('postalcode', 16, 25),
141 $aStructuredQuery = array();
142 foreach($aStructuredOptions as $aStructuredOption)
144 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
146 if (sizeof($aStructuredQuery) > 0) {
147 $sQuery = join(', ', $aStructuredQuery);
152 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
154 // Hack to make it handle "new york, ny" (and variants) correctly
155 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
156 if (isset($aLangPrefOrder['name:en']))
158 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
159 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
160 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
163 // If we have a view box create the SQL
164 // Small is the actual view box, Large is double (on each axis) that
165 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
166 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
168 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
169 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
171 if (isset($_GET['viewbox']) && $_GET['viewbox'])
173 $aCoOrdinates = explode(',',$_GET['viewbox']);
174 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
175 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
176 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
177 $aCoOrdinates[0] += $fHeight;
178 $aCoOrdinates[2] -= $fHeight;
179 $aCoOrdinates[1] += $fWidth;
180 $aCoOrdinates[3] -= $fWidth;
181 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
183 $bBoundingBoxSearch = false;
185 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
187 $aPoints = explode(',',$_GET['route']);
188 if (sizeof($aPoints) % 2 != 0)
190 echo "Uneven number of points";
193 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
195 foreach($aPoints as $i => $fPoint)
199 if ($i != 1) $sViewboxCentreSQL .= ",";
200 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
204 $fPrevCoord = (float)$fPoint;
207 $sViewboxCentreSQL .= ")'::geometry,4326)";
209 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
210 $sViewboxSmallSQL = $oDB->getOne($sSQL);
211 if (PEAR::isError($sViewboxSmallSQL))
213 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
215 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
217 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
218 $sViewboxLargeSQL = $oDB->getOne($sSQL);
219 if (PEAR::isError($sViewboxLargeSQL))
221 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
223 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
226 // Do we have anything that looks like a lat/lon pair?
227 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
229 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
230 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
231 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
233 $_GET['nearlat'] = $fQueryLat;
234 $_GET['nearlon'] = $fQueryLon;
235 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
238 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
240 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
241 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
242 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
244 $_GET['nearlat'] = $fQueryLat;
245 $_GET['nearlon'] = $fQueryLon;
246 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
249 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
251 $fQueryLat = $aData[2];
252 $fQueryLon = $aData[3];
253 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
255 $_GET['nearlat'] = $fQueryLat;
256 $_GET['nearlon'] = $fQueryLon;
257 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
261 if ($sQuery || $aStructuredQuery)
263 // Start with a blank search
265 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
266 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
269 $sNearPointSQL = false;
270 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
272 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
273 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
274 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
275 $aSearches[0]['fRadius'] = 0.1;
278 $bSpecialTerms = false;
279 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
280 $aSpecialTerms = array();
281 foreach($aSpecialTermsRaw as $aSpecialTerm)
283 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
284 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
287 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
288 $aSpecialTerms = array();
289 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
291 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
292 unset($aStructuredQuery['amenity']);
294 foreach($aSpecialTermsRaw as $aSpecialTerm)
296 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
297 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
298 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
299 $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';
300 if (CONST_Debug) var_Dump($sSQL);
301 $aSearchWords = $oDB->getAll($sSQL);
302 $aNewSearches = array();
303 foreach($aSearches as $aSearch)
305 foreach($aSearchWords as $aSearchTerm)
307 $aNewSearch = $aSearch;
308 if ($aSearchTerm['country_code'])
310 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
311 $aNewSearches[] = $aNewSearch;
312 $bSpecialTerms = true;
314 if ($aSearchTerm['class'])
316 $aNewSearch['sClass'] = $aSearchTerm['class'];
317 $aNewSearch['sType'] = $aSearchTerm['type'];
318 $aNewSearches[] = $aNewSearch;
319 $bSpecialTerms = true;
323 $aSearches = $aNewSearches;
326 // Split query into phrases
327 // Commas are used to reduce the search space by indicating where phrases split
328 if (sizeof($aStructuredQuery) > 0)
330 $aPhrases = $aStructuredQuery;
331 $bStructuredPhrases = true;
335 $aPhrases = explode(',',$sQuery);
336 $bStructuredPhrases = false;
340 // Convert each phrase to standard form
341 // Create a list of standard words
342 // Get all 'sets' of words
343 // Generate a complete list of all
345 foreach($aPhrases as $iPhrase => $sPhrase)
347 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
348 if (PEAR::isError($aPhrase))
350 echo "Illegal query string (not an UTF-8 string): ".$sPhrase;
351 if (CONST_Debug) var_dump($aPhrase);
354 if (trim($aPhrase['string']))
356 $aPhrases[$iPhrase] = $aPhrase;
357 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
358 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
359 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
363 unset($aPhrases[$iPhrase]);
367 // reindex phrases - we make assumptions later on
368 $aPhraseTypes = array_keys($aPhrases);
369 $aPhrases = array_values($aPhrases);
371 if (sizeof($aTokens))
374 // Check which tokens we have, get the ID numbers
375 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
376 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
377 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
378 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
380 if (CONST_Debug) var_Dump($sSQL);
382 $aValidTokens = array();
383 if (sizeof($aTokens))
384 $aDatabaseWords = $oDB->getAll($sSQL);
386 $aDatabaseWords = array();
387 if (PEAR::IsError($aDatabaseWords))
389 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
391 $aPossibleMainWordIDs = array();
392 foreach($aDatabaseWords as $aToken)
394 if (isset($aValidTokens[$aToken['word_token']]))
396 $aValidTokens[$aToken['word_token']][] = $aToken;
400 $aValidTokens[$aToken['word_token']] = array($aToken);
402 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
404 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
406 $aSuggestion = array();
407 $bSuggestion = false;
408 if (CONST_Suggestions_Enabled)
410 foreach($aPhrases as $iPhrase => $aPhrase)
412 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
414 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
415 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
416 $aRow = $aSuggestionWords[0];
417 if ($aRow && $aRow['word'])
419 $aSuggestion[] = $aRow['word'];
424 $aSuggestion[] = $aPhrase['string'];
429 $aSuggestion[] = $aPhrase['string'];
433 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
435 // Try and calculate GB postcodes we might be missing
436 foreach($aTokens as $sToken)
438 // Source of gb postcodes is now definitive - always use
439 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
441 if (substr($aData[1],-2,1) != ' ')
443 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
444 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
446 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
447 if ($aGBPostcodeLocation)
449 $aValidTokens[$sToken] = $aGBPostcodeLocation;
454 foreach($aTokens as $sToken)
456 // Unknown single word token with a number - assume it is a house number
457 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
459 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
463 // Any words that have failed completely?
466 // Start the search process
467 $aResultPlaceIDs = array();
470 Calculate all searches using aValidTokens i.e.
472 'Wodsworth Road, Sheffield' =>
476 0 1 (wodsworth)(road)
479 Score how good the search is so they can be ordered
481 foreach($aPhrases as $iPhrase => $sPhrase)
483 $aNewPhraseSearches = array();
484 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
485 else $sPhraseType = '';
487 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
489 $aWordsetSearches = $aSearches;
491 // Add all words from this wordset
492 foreach($aWordset as $iToken => $sToken)
494 //echo "<br><b>$sToken</b>";
495 $aNewWordsetSearches = array();
497 foreach($aWordsetSearches as $aCurrentSearch)
500 //var_dump($aCurrentSearch);
503 // If the token is valid
504 if (isset($aValidTokens[' '.$sToken]))
506 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
508 $aSearch = $aCurrentSearch;
509 $aSearch['iSearchRank']++;
510 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
512 if ($aSearch['sCountryCode'] === false)
514 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
515 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
516 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
517 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
520 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
522 if ($aSearch['fLat'] === '')
524 $aSearch['fLat'] = $aSearchTerm['lat'];
525 $aSearch['fLon'] = $aSearchTerm['lon'];
526 $aSearch['fRadius'] = $aSearchTerm['radius'];
527 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
530 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
532 if ($aSearch['sHouseNumber'] === '')
534 $aSearch['sHouseNumber'] = $sToken;
535 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
537 // Fall back to not searching for this item (better than nothing)
538 $aSearch = $aCurrentSearch;
539 $aSearch['iSearchRank'] += 1;
540 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
544 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
546 if ($aSearch['sClass'] === '')
548 $aSearch['sOperator'] = $aSearchTerm['operator'];
549 $aSearch['sClass'] = $aSearchTerm['class'];
550 $aSearch['sType'] = $aSearchTerm['type'];
551 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
552 else $aSearch['sOperator'] = 'near'; // near = in for the moment
554 // Do we have a shortcut id?
555 if ($aSearch['sOperator'] == 'name')
557 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
558 if ($iAmenityID = $oDB->getOne($sSQL))
560 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
561 $aSearch['aName'][$iAmenityID] = $iAmenityID;
562 $aSearch['sClass'] = '';
563 $aSearch['sType'] = '';
566 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
569 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
571 if (sizeof($aSearch['aName']))
573 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
575 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
579 $aSearch['iSearchRank'] += 1000; // skip;
584 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
585 // $aSearch['iNamePhrase'] = $iPhrase;
587 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
591 if (isset($aValidTokens[$sToken]))
593 // Allow searching for a word - but at extra cost
594 foreach($aValidTokens[$sToken] as $aSearchTerm)
596 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
598 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
600 $aSearch = $aCurrentSearch;
601 $aSearch['iSearchRank'] += 1;
602 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
603 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
606 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
608 $aSearch = $aCurrentSearch;
609 $aSearch['iSearchRank'] += 2;
610 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
611 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
612 $aSearch['iNamePhrase'] = $iPhrase;
613 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
620 // Allow skipping a word - but at EXTREAM cost
621 //$aSearch = $aCurrentSearch;
622 //$aSearch['iSearchRank']+=100;
623 //$aNewWordsetSearches[] = $aSearch;
627 usort($aNewWordsetSearches, 'bySearchRank');
628 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
630 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
632 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
633 usort($aNewPhraseSearches, 'bySearchRank');
635 $aSearchHash = array();
636 foreach($aNewPhraseSearches as $iSearch => $aSearch)
638 $sHash = serialize($aSearch);
639 if (isset($aSearchHash[$sHash]))
641 unset($aNewPhraseSearches[$iSearch]);
645 $aSearchHash[$sHash] = 1;
649 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
652 // Re-group the searches by their score, junk anything over 20 as just not worth trying
653 $aGroupedSearches = array();
654 foreach($aNewPhraseSearches as $aSearch)
656 if ($aSearch['iSearchRank'] < $iMaxRank)
658 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
659 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
662 ksort($aGroupedSearches);
665 $aSearches = array();
666 foreach($aGroupedSearches as $iScore => $aNewSearches)
668 $iSearchCount += sizeof($aNewSearches);
669 $aSearches = array_merge($aSearches, $aNewSearches);
670 if ($iSearchCount > 50) break;
673 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
679 // Re-group the searches by their score, junk anything over 20 as just not worth trying
680 $aGroupedSearches = array();
681 foreach($aSearches as $aSearch)
683 if ($aSearch['iSearchRank'] < $iMaxRank)
685 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
686 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
689 ksort($aGroupedSearches);
692 if (CONST_Debug) var_Dump($aGroupedSearches);
696 $aCopyGroupedSearches = $aGroupedSearches;
697 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
699 foreach($aSearches as $iSearch => $aSearch)
701 if (sizeof($aSearch['aAddress']))
703 $iReverseItem = array_pop($aSearch['aAddress']);
704 if (isset($aPossibleMainWordIDs[$iReverseItem]))
706 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
707 $aSearch['aName'] = array($iReverseItem);
708 $aGroupedSearches[$iGroup][] = $aSearch;
710 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
711 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
717 // Filter out duplicate searches
718 $aSearchHash = array();
719 foreach($aGroupedSearches as $iGroup => $aSearches)
721 foreach($aSearches as $iSearch => $aSearch)
723 $sHash = serialize($aSearch);
724 if (isset($aSearchHash[$sHash]))
726 unset($aGroupedSearches[$iGroup][$iSearch]);
727 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
731 $aSearchHash[$sHash] = 1;
736 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
740 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
743 foreach($aSearches as $aSearch)
747 // Must have a location term
748 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
750 if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
752 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
754 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
755 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
756 $sSQL .= " order by st_area(geometry) desc limit 1";
757 $aPlaceIDs = $oDB->getCol($sSQL);
762 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
763 if (!$aSearch['sClass']) continue;
764 if (CONST_Debug) var_dump('<hr>',$aSearch);
765 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
767 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
768 if ($oDB->getOne($sSQL))
770 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
771 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
772 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid) and linked_place_id is null";
773 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
774 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
775 $sSQL .= " limit $iLimit";
776 if (CONST_Debug) var_dump($sSQL);
777 $aPlaceIDs = $oDB->getCol($sSQL);
779 if (!sizeof($aPlaceIDs))
781 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
782 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
783 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid) and linked_place_id is null";
784 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
785 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
786 $sSQL .= " limit $iLimit";
787 if (CONST_Debug) var_dump($sSQL);
788 $aPlaceIDs = $oDB->getCol($sSQL);
793 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
794 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
795 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
796 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
797 $sSQL .= " limit $iLimit";
798 if (CONST_Debug) var_dump($sSQL);
799 $aPlaceIDs = $oDB->getCol($sSQL);
805 if (CONST_Debug) var_dump('<hr>',$aSearch);
806 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
807 $aPlaceIDs = array();
809 // First we need a position, either aName or fLat or both
813 // TODO: filter out the pointless search terms (2 letter name tokens and less)
814 // they might be right - but they are just too darned expensive to run
815 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
816 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
817 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
818 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
819 if ($aSearch['fLon'] && $aSearch['fLat'])
821 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
822 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
824 if (sizeof($aExcludePlaceIDs))
826 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
828 if ($sCountryCodesSQL)
830 $aTerms[] = "country_code in ($sCountryCodesSQL)";
833 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
834 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
836 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
838 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
839 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
840 $aOrder[] = "$sImportanceSQL DESC";
844 $sSQL = "select place_id";
845 $sSQL .= " from search_name";
846 $sSQL .= " where ".join(' and ',$aTerms);
847 $sSQL .= " order by ".join(', ',$aOrder);
848 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
849 $sSQL .= " limit 50";
850 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
853 $sSQL .= " limit ".$iLimit;
855 if (CONST_Debug) var_dump($sSQL);
856 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
857 if (PEAR::IsError($aViewBoxPlaceIDs))
859 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
861 //var_dump($aViewBoxPlaceIDs);
862 // Did we have an viewbox matches?
863 $aPlaceIDs = array();
864 $bViewBoxMatch = false;
865 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
867 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
868 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
869 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
870 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
871 $aPlaceIDs[] = $aViewBoxRow['place_id'];
874 //var_Dump($aPlaceIDs);
877 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
879 $aRoadPlaceIDs = $aPlaceIDs;
880 $sPlaceIDs = join(',',$aPlaceIDs);
882 // Now they are indexed look for a house attached to a street we found
883 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
884 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
885 if (sizeof($aExcludePlaceIDs))
887 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
889 $sSQL .= " limit $iLimit";
890 if (CONST_Debug) var_dump($sSQL);
891 $aPlaceIDs = $oDB->getCol($sSQL);
893 // If not try the aux fallback table
894 if (!sizeof($aPlaceIDs))
896 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
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);
906 if (!sizeof($aPlaceIDs))
908 $sSQL = "select place_id from location_property_tiger 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 // Fallback to the road
919 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
921 $aPlaceIDs = $aRoadPlaceIDs;
926 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
928 $sPlaceIDs = join(',',$aPlaceIDs);
930 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
932 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
933 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
934 $sSQL = " and linked_place_id is null";
935 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
936 $sSQL .= " order by rank_search asc limit $iLimit";
937 if (CONST_Debug) var_dump($sSQL);
938 $aPlaceIDs = $oDB->getCol($sSQL);
941 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
943 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
944 $bCacheTable = $oDB->getOne($sSQL);
946 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
948 if (CONST_Debug) var_dump($sSQL);
949 $iMaxRank = ((int)$oDB->getOne($sSQL));
951 // For state / country level searches the normal radius search doesn't work very well
953 if ($iMaxRank < 9 && $bCacheTable)
955 // Try and get a polygon to search in instead
956 $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";
957 if (CONST_Debug) var_dump($sSQL);
958 $sPlaceGeom = $oDB->getOne($sSQL);
968 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
969 if (CONST_Debug) var_dump($sSQL);
970 $aPlaceIDs = $oDB->getCol($sSQL);
971 $sPlaceIDs = join(',',$aPlaceIDs);
974 if ($sPlaceIDs || $sPlaceGeom)
980 // More efficient - can make the range bigger
984 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
985 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
986 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
988 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
989 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
992 $sSQL .= ",placex as f where ";
993 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
998 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1000 if (sizeof($aExcludePlaceIDs))
1002 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1004 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1005 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1006 if ($iOffset) $sSQL .= " offset $iOffset";
1007 $sSQL .= " limit $iLimit";
1008 if (CONST_Debug) var_dump($sSQL);
1009 $aPlaceIDs = $oDB->getCol($sSQL);
1013 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1016 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1017 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1019 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1020 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1021 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1022 if (sizeof($aExcludePlaceIDs))
1024 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1026 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1027 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1028 if ($iOffset) $sSQL .= " offset $iOffset";
1029 $sSQL .= " limit $iLimit";
1030 if (CONST_Debug) var_dump($sSQL);
1031 $aPlaceIDs = $oDB->getCol($sSQL);
1039 if (PEAR::IsError($aPlaceIDs))
1041 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1044 if (CONST_Debug) var_Dump($aPlaceIDs);
1046 foreach($aPlaceIDs as $iPlaceID)
1048 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1050 if ($iQueryLoop > 20) break;
1053 if (sizeof($aResultPlaceIDs)) break;
1054 if ($iGroupLoop > 4) break;
1055 if ($iQueryLoop > 30) break;
1058 // Did we find anything?
1059 if (sizeof($aResultPlaceIDs))
1061 //var_Dump($aResultPlaceIDs);exit;
1062 // Get the details for display (is this a redundant extra step?)
1063 $sPlaceIDs = join(',',$aResultPlaceIDs);
1064 $sOrderSQL = 'CASE ';
1065 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1067 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1069 $sOrderSQL .= ' ELSE 10000000 END';
1070 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1071 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1072 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1073 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1074 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1075 // $sSQL .= $sOrderSQL." as porder, ";
1076 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1077 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1078 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1079 $sSQL .= "and linked_place_id is null ";
1080 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1081 if (!$bDeDupe) $sSQL .= ",place_id";
1082 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1083 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1084 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1086 $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,";
1087 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1088 $sSQL .= "null as placename,";
1089 $sSQL .= "null as ref,";
1090 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1091 // $sSQL .= $sOrderSQL." as porder, ";
1092 $sSQL .= "-0.15 as importance ";
1093 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1094 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1095 $sSQL .= "group by place_id";
1096 if (!$bDeDupe) $sSQL .= ",place_id";
1098 $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,";
1099 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1100 $sSQL .= "null as placename,";
1101 $sSQL .= "null as ref,";
1102 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1103 // $sSQL .= $sOrderSQL." as porder, ";
1104 $sSQL .= "-0.10 as importance ";
1105 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1106 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1107 $sSQL .= "group by place_id";
1108 if (!$bDeDupe) $sSQL .= ",place_id";
1109 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1110 $sSQL .= "order by importance desc";
1111 // $sSQL .= "order by rank_search,rank_address,porder asc";
1112 if (CONST_Debug) var_dump('<hr>',$sSQL);
1113 $aSearchResults = $oDB->getAll($sSQL);
1114 //var_dump($sSQL,$aSearchResults);exit;
1116 if (PEAR::IsError($aSearchResults))
1118 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1121 } // end if ($sQuery)
1124 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1126 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1127 $aResultPlaceIDs = array($iPlaceID);
1129 // TODO: this needs refactoring!
1131 // Get the details for display (is this a redundant extra step?)
1132 $sPlaceIDs = join(',',$aResultPlaceIDs);
1133 $sOrderSQL = 'CASE ';
1134 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1136 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1138 $sOrderSQL .= ' ELSE 10000000 END';
1139 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1140 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1141 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1142 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1143 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1144 // $sSQL .= $sOrderSQL." as porder, ";
1145 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1146 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1147 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1148 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1149 if (!$bDeDupe) $sSQL .= ",place_id";
1150 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1151 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1152 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1154 $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,";
1155 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1156 $sSQL .= "null as placename,";
1157 $sSQL .= "null as ref,";
1158 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1159 // $sSQL .= $sOrderSQL." as porder, ";
1160 $sSQL .= "-0.15 as importance ";
1161 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1162 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1163 $sSQL .= "group by place_id";
1164 if (!$bDeDupe) $sSQL .= ",place_id";
1166 $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,";
1167 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1168 $sSQL .= "null as placename,";
1169 $sSQL .= "null as ref,";
1170 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1171 // $sSQL .= $sOrderSQL." as porder, ";
1172 $sSQL .= "-0.10 as importance ";
1173 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1174 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1175 $sSQL .= "group by place_id";
1176 if (!$bDeDupe) $sSQL .= ",place_id";
1177 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1178 $sSQL .= "order by importance desc";
1179 // $sSQL .= "order by rank_search,rank_address,porder asc";
1180 if (CONST_Debug) var_dump('<hr>',$sSQL);
1181 $aSearchResults = $oDB->getAll($sSQL);
1182 //var_dump($sSQL,$aSearchResults);exit;
1184 if (PEAR::IsError($aSearchResults))
1186 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1192 $sSearchResult = '';
1193 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1195 $sSearchResult = 'No Results Found';
1197 //var_Dump($aSearchResults);
1199 $aClassType = getClassTypesWithImportance();
1200 $aRecheckWords = preg_split('/\b/',$sQuery);
1201 foreach($aRecheckWords as $i => $sWord)
1203 if (!$sWord) unset($aRecheckWords[$i]);
1205 foreach($aSearchResults as $iResNum => $aResult)
1207 if (CONST_Search_AreaPolygons)
1209 // Get the bounding box and outline polygon
1210 $sSQL = "select place_id,numfeatures,area,outline,";
1211 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1212 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1213 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1215 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1216 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1217 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1218 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1219 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1220 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1221 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1222 if ($bAsText) $sSQL .= ",ST_AsText(geometry) as astext";
1223 if ($bShowPolygons) $sSQL .= ",ST_AsText(geometry) as outlinestring";
1224 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1225 $aPointPolygon = $oDB->getRow($sSQL);
1226 if (PEAR::IsError($aPointPolygon))
1228 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1230 if ($aPointPolygon['place_id'])
1232 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1233 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1234 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1235 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1237 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1238 $aResult['lat'] = $aPointPolygon['centrelat'];
1239 $aResult['lon'] = $aPointPolygon['centrelon'];
1243 // Translate geometary string to point array
1244 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1246 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1248 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
1250 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1252 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
1255 $iSteps = ($fRadius * 40000)^2;
1256 $fStepSize = (2*pi())/$iSteps;
1257 $aPolyPoints = array();
1258 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1260 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1262 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1263 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1264 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1265 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1269 // Output data suitable for display (points and a bounding box)
1270 if ($bShowPolygons && isset($aPolyPoints))
1272 $aResult['aPolyPoints'] = array();
1273 foreach($aPolyPoints as $aPoint)
1275 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1278 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1282 if (!isset($aResult['aBoundingBox']))
1285 $fDiameter = 0.0001;
1287 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1288 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1290 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1292 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1293 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1295 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1297 $fRadius = $fDiameter / 2;
1299 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1300 $fStepSize = (2*pi())/$iSteps;
1301 $aPolyPoints = array();
1302 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1304 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1306 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1307 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1308 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1309 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1311 // Output data suitable for display (points and a bounding box)
1314 $aResult['aPolyPoints'] = array();
1315 foreach($aPolyPoints as $aPoint)
1317 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1320 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1323 // Is there an icon set for this type of result?
1324 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1325 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1327 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1330 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1331 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1333 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1336 if ($bShowAddressDetails)
1338 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1339 //var_dump($aResult['address']);
1343 // Adjust importance for the number of exact string matches in the result
1344 $aResult['importance'] = max(0.001,$aResult['importance']);
1346 $sAddress = $aResult['langaddress'];
1347 foreach($aRecheckWords as $i => $sWord)
1349 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1351 $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
1353 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1355 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1356 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1358 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1360 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1361 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1363 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1367 $aResult['importance'] = 1000000000000000;
1370 $aResult['name'] = $aResult['langaddress'];
1371 $aResult['foundorder'] = $iResNum;
1372 $aSearchResults[$iResNum] = $aResult;
1374 uasort($aSearchResults, 'byImportance');
1376 //var_dump($aSearchResults);exit;
1378 $aOSMIDDone = array();
1379 $aClassTypeNameDone = array();
1380 $aToFilter = $aSearchResults;
1381 $aSearchResults = array();
1384 foreach($aToFilter as $iResNum => $aResult)
1386 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1387 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1390 $fLat = $aResult['lat'];
1391 $fLon = $aResult['lon'];
1392 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1395 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1396 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1398 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1399 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1400 $aSearchResults[] = $aResult;
1403 // Absolute limit on number of results
1404 if (sizeof($aSearchResults) >= $iLimit) break;
1407 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1409 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1411 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1416 logEnd($oDB, $hLog, sizeof($aToFilter));
1418 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1419 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1420 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1421 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1422 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1423 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1426 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1428 $sMoreURL .= '&q='.urlencode($sQuery);
1430 if (CONST_Debug) exit;
1432 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');