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 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
21 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
23 if ($iFinalLimit > 50) $iFinalLimit = 50;
24 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
26 $iMaxAddressRank = 30;
29 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
31 $sOutputFormat = $_GET['format'];
34 // Show / use polygons
35 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
36 if ($sOutputFormat == 'html') {
37 $bAsText = $bShowPolygons;
38 $bShowPolygons = false;
43 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
44 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
45 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
46 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
47 if ((($bShowPolygons?1:0)
52 ) > CONST_PolygonOutput_MaximumTypes) {
53 if (CONST_PolygonOutput_MaximumTypes) {
54 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
56 userError("Polygon output is disabled");
62 // Show address breakdown
63 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
66 $aLangPrefOrder = getPreferredLanguages();
67 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
68 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
69 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
70 if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
72 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
74 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
76 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
78 $iExcludedPlaceID = (int)$iExcludedPlaceID;
79 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
83 // Only certain ranks of feature
84 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
86 if (isset($_GET['featuretype']))
88 switch($_GET['featuretype'])
91 $iMinAddressRank = $iMaxAddressRank = 4;
94 $iMinAddressRank = $iMaxAddressRank = 8;
97 $iMinAddressRank = 14;
98 $iMaxAddressRank = 16;
101 $iMinAddressRank = 8;
102 $iMaxAddressRank = 20;
107 if (isset($_GET['countrycodes']))
109 $aCountryCodes = array();
110 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
112 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
114 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
117 $sCountryCodesSQL = join(',', $aCountryCodes);
121 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
122 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
124 $sQuery = substr($_SERVER['PATH_INFO'], 1);
126 // reverse order of '/' separated string
127 $aPhrases = explode('/', $sQuery);
128 $aPhrases = array_reverse($aPhrases);
129 $sQuery = join(', ',$aPhrases);
132 function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
134 if (!isset($_GET[$sKey])) return false;
135 $sValue = trim($_GET[$sKey]);
136 if (!$sValue) return false;
137 $aStructuredQuery[$sKey] = $sValue;
138 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30) {
139 $iMinAddressRank = $iNewMinAddressRank;
140 $iMaxAddressRank = $iNewMaxAddressRank;
146 $aStructuredOptions = array(
147 array('amenity', 26, 30),
148 array('street', 26, 30),
149 array('city', 14, 24),
150 array('county', 9, 13),
151 array('state', 8, 8),
152 array('country', 4, 4),
153 array('postalcode', 16, 25),
155 $aStructuredQuery = array();
156 foreach($aStructuredOptions as $aStructuredOption)
158 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
160 if (sizeof($aStructuredQuery) > 0) {
161 $sQuery = join(', ', $aStructuredQuery);
166 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
168 // Hack to make it handle "new york, ny" (and variants) correctly
169 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
170 if (isset($aLangPrefOrder['name:en']))
172 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
173 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
174 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
177 // If we have a view box create the SQL
178 // Small is the actual view box, Large is double (on each axis) that
179 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
180 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
182 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
183 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
185 if (isset($_GET['viewbox']) && $_GET['viewbox'])
187 $aCoOrdinates = explode(',',$_GET['viewbox']);
188 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
189 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
190 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
191 $aCoOrdinates[0] += $fHeight;
192 $aCoOrdinates[2] -= $fHeight;
193 $aCoOrdinates[1] += $fWidth;
194 $aCoOrdinates[3] -= $fWidth;
195 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
197 $bBoundingBoxSearch = false;
199 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
201 $aPoints = explode(',',$_GET['route']);
202 if (sizeof($aPoints) % 2 != 0)
204 userError("Uneven number of points");
207 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
209 foreach($aPoints as $i => $fPoint)
213 if ($i != 1) $sViewboxCentreSQL .= ",";
214 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
218 $fPrevCoord = (float)$fPoint;
221 $sViewboxCentreSQL .= ")'::geometry,4326)";
223 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
224 $sViewboxSmallSQL = $oDB->getOne($sSQL);
225 if (PEAR::isError($sViewboxSmallSQL))
227 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
229 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
231 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
232 $sViewboxLargeSQL = $oDB->getOne($sSQL);
233 if (PEAR::isError($sViewboxLargeSQL))
235 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
237 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
238 $bBoundingBoxSearch = true;
241 // Do we have anything that looks like a lat/lon pair?
242 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
244 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
245 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
246 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
248 $_GET['nearlat'] = $fQueryLat;
249 $_GET['nearlon'] = $fQueryLon;
250 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
253 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
255 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
256 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
257 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
259 $_GET['nearlat'] = $fQueryLat;
260 $_GET['nearlon'] = $fQueryLon;
261 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
264 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
266 $fQueryLat = $aData[2];
267 $fQueryLon = $aData[3];
268 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
270 $_GET['nearlat'] = $fQueryLat;
271 $_GET['nearlon'] = $fQueryLon;
272 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
276 if ($sQuery || $aStructuredQuery)
278 // Start with a blank search
280 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(),
281 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
284 $sNearPointSQL = false;
285 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
287 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
288 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
289 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
290 $aSearches[0]['fRadius'] = 0.1;
293 $bSpecialTerms = false;
294 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
295 $aSpecialTerms = array();
296 foreach($aSpecialTermsRaw as $aSpecialTerm)
298 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
299 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
302 preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
303 $aSpecialTerms = array();
304 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
306 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
307 unset($aStructuredQuery['amenity']);
309 foreach($aSpecialTermsRaw as $aSpecialTerm)
311 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
312 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
313 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
314 $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';
315 if (CONST_Debug) var_Dump($sSQL);
316 $aSearchWords = $oDB->getAll($sSQL);
317 $aNewSearches = array();
318 foreach($aSearches as $aSearch)
320 foreach($aSearchWords as $aSearchTerm)
322 $aNewSearch = $aSearch;
323 if ($aSearchTerm['country_code'])
325 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
326 $aNewSearches[] = $aNewSearch;
327 $bSpecialTerms = true;
329 if ($aSearchTerm['class'])
331 $aNewSearch['sClass'] = $aSearchTerm['class'];
332 $aNewSearch['sType'] = $aSearchTerm['type'];
333 $aNewSearches[] = $aNewSearch;
334 $bSpecialTerms = true;
338 $aSearches = $aNewSearches;
341 // Split query into phrases
342 // Commas are used to reduce the search space by indicating where phrases split
343 if (sizeof($aStructuredQuery) > 0)
345 $aPhrases = $aStructuredQuery;
346 $bStructuredPhrases = true;
350 $aPhrases = explode(',',$sQuery);
351 $bStructuredPhrases = false;
355 // Convert each phrase to standard form
356 // Create a list of standard words
357 // Get all 'sets' of words
358 // Generate a complete list of all
360 foreach($aPhrases as $iPhrase => $sPhrase)
362 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
363 if (PEAR::isError($aPhrase))
365 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
366 if (CONST_Debug) var_dump($aPhrase);
369 if (trim($aPhrase['string']))
371 $aPhrases[$iPhrase] = $aPhrase;
372 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
373 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
374 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
378 unset($aPhrases[$iPhrase]);
382 // reindex phrases - we make assumptions later on
383 $aPhraseTypes = array_keys($aPhrases);
384 $aPhrases = array_values($aPhrases);
386 if (sizeof($aTokens))
389 // Check which tokens we have, get the ID numbers
390 $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
391 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
392 $sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
393 // $sSQL .= ' group by word_token, word, class, type, location, country_code';
395 if (CONST_Debug) var_Dump($sSQL);
397 $aValidTokens = array();
398 if (sizeof($aTokens))
399 $aDatabaseWords = $oDB->getAll($sSQL);
401 $aDatabaseWords = array();
402 if (PEAR::IsError($aDatabaseWords))
404 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
406 $aPossibleMainWordIDs = array();
407 foreach($aDatabaseWords as $aToken)
409 if (isset($aValidTokens[$aToken['word_token']]))
411 $aValidTokens[$aToken['word_token']][] = $aToken;
415 $aValidTokens[$aToken['word_token']] = array($aToken);
417 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
419 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
421 $aSuggestion = array();
422 $bSuggestion = false;
423 if (CONST_Suggestions_Enabled)
425 foreach($aPhrases as $iPhrase => $aPhrase)
427 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
429 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
430 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
431 $aRow = $aSuggestionWords[0];
432 if ($aRow && $aRow['word'])
434 $aSuggestion[] = $aRow['word'];
439 $aSuggestion[] = $aPhrase['string'];
444 $aSuggestion[] = $aPhrase['string'];
448 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
450 // Try and calculate GB postcodes we might be missing
451 foreach($aTokens as $sToken)
453 // Source of gb postcodes is now definitive - always use
454 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
456 if (substr($aData[1],-2,1) != ' ')
458 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
459 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
461 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
462 if ($aGBPostcodeLocation)
464 $aValidTokens[$sToken] = $aGBPostcodeLocation;
469 foreach($aTokens as $sToken)
471 // Unknown single word token with a number - assume it is a house number
472 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
474 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
478 // Any words that have failed completely?
481 // Start the search process
482 $aResultPlaceIDs = array();
485 Calculate all searches using aValidTokens i.e.
487 'Wodsworth Road, Sheffield' =>
491 0 1 (wodsworth)(road)
494 Score how good the search is so they can be ordered
496 foreach($aPhrases as $iPhrase => $sPhrase)
498 $aNewPhraseSearches = array();
499 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
500 else $sPhraseType = '';
502 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
504 $aWordsetSearches = $aSearches;
506 // Add all words from this wordset
507 foreach($aWordset as $iToken => $sToken)
509 //echo "<br><b>$sToken</b>";
510 $aNewWordsetSearches = array();
512 foreach($aWordsetSearches as $aCurrentSearch)
515 //var_dump($aCurrentSearch);
518 // If the token is valid
519 if (isset($aValidTokens[' '.$sToken]))
521 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
523 $aSearch = $aCurrentSearch;
524 $aSearch['iSearchRank']++;
525 if (($sPhraseType == '' || $sPhraseType == 'country') && $aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
527 if ($aSearch['sCountryCode'] === false)
529 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
530 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
531 if ($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
532 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
535 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
537 if ($aSearch['fLat'] === '')
539 $aSearch['fLat'] = $aSearchTerm['lat'];
540 $aSearch['fLon'] = $aSearchTerm['lon'];
541 $aSearch['fRadius'] = $aSearchTerm['radius'];
542 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
545 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
547 if ($aSearch['sHouseNumber'] === '')
549 $aSearch['sHouseNumber'] = $sToken;
550 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
552 // Fall back to not searching for this item (better than nothing)
553 $aSearch = $aCurrentSearch;
554 $aSearch['iSearchRank'] += 1;
555 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
559 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
561 if ($aSearch['sClass'] === '')
563 $aSearch['sOperator'] = $aSearchTerm['operator'];
564 $aSearch['sClass'] = $aSearchTerm['class'];
565 $aSearch['sType'] = $aSearchTerm['type'];
566 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
567 else $aSearch['sOperator'] = 'near'; // near = in for the moment
569 // Do we have a shortcut id?
570 if ($aSearch['sOperator'] == 'name')
572 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
573 if ($iAmenityID = $oDB->getOne($sSQL))
575 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
576 $aSearch['aName'][$iAmenityID] = $iAmenityID;
577 $aSearch['sClass'] = '';
578 $aSearch['sType'] = '';
581 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
584 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
586 if (sizeof($aSearch['aName']))
588 if (($sPhraseType != 'street' && $sPhraseType != 'country') && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
590 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
594 $aSearch['iSearchRank'] += 1000; // skip;
599 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
600 // $aSearch['iNamePhrase'] = $iPhrase;
602 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
606 if (isset($aValidTokens[$sToken]))
608 // Allow searching for a word - but at extra cost
609 foreach($aValidTokens[$sToken] as $aSearchTerm)
611 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
613 if (($sPhraseType != 'street') && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
615 $aSearch = $aCurrentSearch;
616 $aSearch['iSearchRank'] += 1;
617 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
618 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
621 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
623 $aSearch = $aCurrentSearch;
624 $aSearch['iSearchRank'] += 2;
625 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
626 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
627 $aSearch['iNamePhrase'] = $iPhrase;
628 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
635 // Allow skipping a word - but at EXTREAM cost
636 //$aSearch = $aCurrentSearch;
637 //$aSearch['iSearchRank']+=100;
638 //$aNewWordsetSearches[] = $aSearch;
642 usort($aNewWordsetSearches, 'bySearchRank');
643 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
645 // var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
647 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
648 usort($aNewPhraseSearches, 'bySearchRank');
650 $aSearchHash = array();
651 foreach($aNewPhraseSearches as $iSearch => $aSearch)
653 $sHash = serialize($aSearch);
654 if (isset($aSearchHash[$sHash]))
656 unset($aNewPhraseSearches[$iSearch]);
660 $aSearchHash[$sHash] = 1;
664 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
667 // Re-group the searches by their score, junk anything over 20 as just not worth trying
668 $aGroupedSearches = array();
669 foreach($aNewPhraseSearches as $aSearch)
671 if ($aSearch['iSearchRank'] < $iMaxRank)
673 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
674 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
677 ksort($aGroupedSearches);
680 $aSearches = array();
681 foreach($aGroupedSearches as $iScore => $aNewSearches)
683 $iSearchCount += sizeof($aNewSearches);
684 $aSearches = array_merge($aSearches, $aNewSearches);
685 if ($iSearchCount > 50) break;
688 // if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
694 // Re-group the searches by their score, junk anything over 20 as just not worth trying
695 $aGroupedSearches = array();
696 foreach($aSearches as $aSearch)
698 if ($aSearch['iSearchRank'] < $iMaxRank)
700 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
701 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
704 ksort($aGroupedSearches);
707 if (CONST_Debug) var_Dump($aGroupedSearches);
711 $aCopyGroupedSearches = $aGroupedSearches;
712 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
714 foreach($aSearches as $iSearch => $aSearch)
716 if (sizeof($aSearch['aAddress']))
718 $iReverseItem = array_pop($aSearch['aAddress']);
719 if (isset($aPossibleMainWordIDs[$iReverseItem]))
721 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
722 $aSearch['aName'] = array($iReverseItem);
723 $aGroupedSearches[$iGroup][] = $aSearch;
725 // $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
726 // $aGroupedSearches[$iGroup][] = $aReverseSearch;
732 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
734 $aCopyGroupedSearches = $aGroupedSearches;
735 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
737 foreach($aSearches as $iSearch => $aSearch)
739 $aReductionsList = array($aSearch['aAddress']);
740 $iSearchRank = $aSearch['iSearchRank'];
741 while(sizeof($aReductionsList) > 0)
744 if ($iSearchRank > iMaxRank) break 3;
745 $aNewReductionsList = array();
746 foreach($aReductionsList as $aReductionsWordList)
748 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
750 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
751 $aReverseSearch = $aSearch;
752 $aSearch['aAddress'] = $aReductionsWordListResult;
753 $aSearch['iSearchRank'] = $iSearchRank;
754 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
755 if (sizeof($aReductionsWordListResult) > 0)
757 $aNewReductionsList[] = $aReductionsWordListResult;
761 $aReductionsList = $aNewReductionsList;
765 ksort($aGroupedSearches);
768 // Filter out duplicate searches
769 $aSearchHash = array();
770 foreach($aGroupedSearches as $iGroup => $aSearches)
772 foreach($aSearches as $iSearch => $aSearch)
774 $sHash = serialize($aSearch);
775 if (isset($aSearchHash[$sHash]))
777 unset($aGroupedSearches[$iGroup][$iSearch]);
778 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
782 $aSearchHash[$sHash] = 1;
787 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
791 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
794 foreach($aSearches as $aSearch)
798 // Must have a location term
799 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
801 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
803 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
805 $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
806 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
807 $sSQL .= " order by st_area(geometry) desc limit 1";
808 $aPlaceIDs = $oDB->getCol($sSQL);
813 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
814 if (!$aSearch['sClass']) continue;
815 if (CONST_Debug) var_dump('<hr>',$aSearch);
816 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
817 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
818 if ($oDB->getOne($sSQL))
820 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
821 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
822 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
823 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
824 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
825 $sSQL .= " limit $iLimit";
826 if (CONST_Debug) var_dump($sSQL);
827 $aPlaceIDs = $oDB->getCol($sSQL);
829 if (!sizeof($aPlaceIDs))
831 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
832 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
833 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
834 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
835 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
836 $sSQL .= " limit $iLimit";
837 if (CONST_Debug) var_dump($sSQL);
838 $aPlaceIDs = $oDB->getCol($sSQL);
843 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
844 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
845 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
846 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
847 $sSQL .= " limit $iLimit";
848 if (CONST_Debug) var_dump($sSQL);
849 $aPlaceIDs = $oDB->getCol($sSQL);
855 if (CONST_Debug) var_dump('<hr>',$aSearch);
856 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
857 $aPlaceIDs = array();
859 // First we need a position, either aName or fLat or both
863 // TODO: filter out the pointless search terms (2 letter name tokens and less)
864 // they might be right - but they are just too darned expensive to run
865 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
866 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
867 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
868 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
869 if ($aSearch['fLon'] && $aSearch['fLat'])
871 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
872 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
874 if (sizeof($aExcludePlaceIDs))
876 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
878 if ($sCountryCodesSQL)
880 $aTerms[] = "country_code in ($sCountryCodesSQL)";
883 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
884 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
886 $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.92-(search_rank::float/33) else importance end';
888 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
889 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
890 $aOrder[] = "$sImportanceSQL DESC";
894 $sSQL = "select place_id";
895 $sSQL .= " from search_name";
896 $sSQL .= " where ".join(' and ',$aTerms);
897 $sSQL .= " order by ".join(', ',$aOrder);
898 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
899 $sSQL .= " limit 50";
900 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
903 $sSQL .= " limit ".$iLimit;
905 if (CONST_Debug) var_dump($sSQL);
906 $iStartTime = time();
907 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
908 if (PEAR::IsError($aViewBoxPlaceIDs))
910 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
912 if (time() - $iStartTime > 60) {
913 file_put_contents(CONST_BasePath.'/log/long_queries.log', date('Y-m-d H:i:s', $iStartTime).' '.$sSQL."\n", FILE_APPEND);
916 //var_dump($aViewBoxPlaceIDs);
917 // Did we have an viewbox matches?
918 $aPlaceIDs = array();
919 $bViewBoxMatch = false;
920 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
922 // if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
923 // if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
924 // if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
925 // else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
926 $aPlaceIDs[] = $aViewBoxRow['place_id'];
929 //var_Dump($aPlaceIDs);
932 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
934 $aRoadPlaceIDs = $aPlaceIDs;
935 $sPlaceIDs = join(',',$aPlaceIDs);
937 // Now they are indexed look for a house attached to a street we found
938 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
939 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
940 if (sizeof($aExcludePlaceIDs))
942 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
944 $sSQL .= " limit $iLimit";
945 if (CONST_Debug) var_dump($sSQL);
946 $aPlaceIDs = $oDB->getCol($sSQL);
948 // If not try the aux fallback table
949 if (!sizeof($aPlaceIDs))
951 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
952 if (sizeof($aExcludePlaceIDs))
954 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
956 // $sSQL .= " limit $iLimit";
957 if (CONST_Debug) var_dump($sSQL);
958 $aPlaceIDs = $oDB->getCol($sSQL);
961 if (!sizeof($aPlaceIDs))
963 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
964 if (sizeof($aExcludePlaceIDs))
966 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
968 // $sSQL .= " limit $iLimit";
969 if (CONST_Debug) var_dump($sSQL);
970 $aPlaceIDs = $oDB->getCol($sSQL);
973 // Fallback to the road
974 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
976 $aPlaceIDs = $aRoadPlaceIDs;
981 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
983 $sPlaceIDs = join(',',$aPlaceIDs);
985 $aClassPlaceIDs = array();
987 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
989 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
990 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
991 $sSQL .= " and linked_place_id is null";
992 if ($sCountryCodesSQL) $sSQL .= " and country_code in ($sCountryCodesSQL)";
993 $sSQL .= " order by rank_search asc limit $iLimit";
994 if (CONST_Debug) var_dump($sSQL);
995 $aClassPlaceIDs = $oDB->getCol($sSQL);
998 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1000 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1001 $bCacheTable = $oDB->getOne($sSQL);
1003 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1005 if (CONST_Debug) var_dump($sSQL);
1006 $iMaxRank = ((int)$oDB->getOne($sSQL));
1008 // For state / country level searches the normal radius search doesn't work very well
1009 $sPlaceGeom = false;
1010 if ($iMaxRank < 9 && $bCacheTable)
1012 // Try and get a polygon to search in instead
1013 $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";
1014 if (CONST_Debug) var_dump($sSQL);
1015 $sPlaceGeom = $oDB->getOne($sSQL);
1025 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1026 if (CONST_Debug) var_dump($sSQL);
1027 $aPlaceIDs = $oDB->getCol($sSQL);
1028 $sPlaceIDs = join(',',$aPlaceIDs);
1031 if ($sPlaceIDs || $sPlaceGeom)
1037 // More efficient - can make the range bigger
1041 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1042 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1043 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1045 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1046 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1049 $sSQL .= ",placex as f where ";
1050 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
1055 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1057 if (sizeof($aExcludePlaceIDs))
1059 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1061 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1062 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1063 if ($iOffset) $sSQL .= " offset $iOffset";
1064 $sSQL .= " limit $iLimit";
1065 if (CONST_Debug) var_dump($sSQL);
1066 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1070 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1073 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1074 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1076 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1077 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
1078 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1079 if (sizeof($aExcludePlaceIDs))
1081 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1083 if ($sCountryCodesSQL) $sSQL .= " and l.country_code in ($sCountryCodesSQL)";
1084 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1085 if ($iOffset) $sSQL .= " offset $iOffset";
1086 $sSQL .= " limit $iLimit";
1087 if (CONST_Debug) var_dump($sSQL);
1088 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1093 $aPlaceIDs = $aClassPlaceIDs;
1099 if (PEAR::IsError($aPlaceIDs))
1101 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1104 if (CONST_Debug) var_Dump($aPlaceIDs);
1106 foreach($aPlaceIDs as $iPlaceID)
1108 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1110 if ($iQueryLoop > 20) break;
1114 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1115 if ($iGroupLoop > 4) break;
1116 if ($iQueryLoop > 30) break;
1119 // Did we find anything?
1120 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1122 //var_Dump($aResultPlaceIDs);exit;
1123 // Get the details for display (is this a redundant extra step?)
1124 $sPlaceIDs = join(',',$aResultPlaceIDs);
1125 $sOrderSQL = 'CASE ';
1126 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1128 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1130 $sOrderSQL .= ' ELSE 10000000 END';
1131 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1132 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1133 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1134 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1135 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1136 // $sSQL .= $sOrderSQL." as porder, ";
1137 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1138 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1139 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1140 $sSQL .= "and linked_place_id is null ";
1141 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1142 if (!$bDeDupe) $sSQL .= ",place_id";
1143 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1144 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1145 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1147 $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,";
1148 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1149 $sSQL .= "null as placename,";
1150 $sSQL .= "null as ref,";
1151 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1152 // $sSQL .= $sOrderSQL." as porder, ";
1153 $sSQL .= "-0.15 as importance ";
1154 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1155 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1156 $sSQL .= "group by place_id";
1157 if (!$bDeDupe) $sSQL .= ",place_id";
1159 $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,";
1160 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1161 $sSQL .= "null as placename,";
1162 $sSQL .= "null as ref,";
1163 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1164 // $sSQL .= $sOrderSQL." as porder, ";
1165 $sSQL .= "-0.10 as importance ";
1166 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1167 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1168 $sSQL .= "group by place_id";
1169 if (!$bDeDupe) $sSQL .= ",place_id";
1170 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1171 $sSQL .= "order by importance desc";
1172 // $sSQL .= "order by rank_search,rank_address,porder asc";
1173 if (CONST_Debug) var_dump('<hr>',$sSQL);
1174 $aSearchResults = $oDB->getAll($sSQL);
1175 //var_dump($sSQL,$aSearchResults);exit;
1177 if (PEAR::IsError($aSearchResults))
1179 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1182 } // end if ($sQuery)
1185 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1187 $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1188 $aResultPlaceIDs = array($iPlaceID);
1190 // TODO: this needs refactoring!
1192 // Get the details for display (is this a redundant extra step?)
1193 $sPlaceIDs = join(',',$aResultPlaceIDs);
1194 $sOrderSQL = 'CASE ';
1195 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1197 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1199 $sOrderSQL .= ' ELSE 10000000 END';
1200 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
1201 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1202 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1203 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1204 $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
1205 // $sSQL .= $sOrderSQL." as porder, ";
1206 $sSQL .= "coalesce(importance,0.9-(rank_search::float/30)) as importance ";
1207 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1208 $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1209 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code,importance";
1210 if (!$bDeDupe) $sSQL .= ",place_id";
1211 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1212 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1213 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1215 $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,";
1216 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1217 $sSQL .= "null as placename,";
1218 $sSQL .= "null as ref,";
1219 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1220 // $sSQL .= $sOrderSQL." as porder, ";
1221 $sSQL .= "-0.15 as importance ";
1222 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1223 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1224 $sSQL .= "group by place_id";
1225 if (!$bDeDupe) $sSQL .= ",place_id";
1227 $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,";
1228 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1229 $sSQL .= "null as placename,";
1230 $sSQL .= "null as ref,";
1231 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1232 // $sSQL .= $sOrderSQL." as porder, ";
1233 $sSQL .= "-0.10 as importance ";
1234 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1235 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1236 $sSQL .= "group by place_id";
1237 if (!$bDeDupe) $sSQL .= ",place_id";
1238 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1239 $sSQL .= "order by importance desc";
1240 // $sSQL .= "order by rank_search,rank_address,porder asc";
1241 if (CONST_Debug) var_dump('<hr>',$sSQL);
1242 $aSearchResults = $oDB->getAll($sSQL);
1243 //var_dump($sSQL,$aSearchResults);exit;
1245 if (PEAR::IsError($aSearchResults))
1247 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1253 $sSearchResult = '';
1254 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1256 $sSearchResult = 'No Results Found';
1258 //var_Dump($aSearchResults);
1260 $aClassType = getClassTypesWithImportance();
1261 $aRecheckWords = preg_split('/\b/',$sQuery);
1262 foreach($aRecheckWords as $i => $sWord)
1264 if (!$sWord) unset($aRecheckWords[$i]);
1266 foreach($aSearchResults as $iResNum => $aResult)
1268 if (CONST_Search_AreaPolygons)
1270 // Get the bounding box and outline polygon
1271 $sSQL = "select place_id,numfeatures,area,outline,";
1272 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1273 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1274 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1276 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1277 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1278 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1279 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1280 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1281 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1282 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1283 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1284 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1285 $aPointPolygon = $oDB->getRow($sSQL);
1286 if (PEAR::IsError($aPointPolygon))
1288 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1290 if ($aPointPolygon['place_id'])
1292 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1293 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1294 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1295 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1297 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1298 $aResult['lat'] = $aPointPolygon['centrelat'];
1299 $aResult['lon'] = $aPointPolygon['centrelon'];
1303 // Translate geometary string to point array
1304 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1306 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1308 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1310 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1312 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1315 $iSteps = ($fRadius * 40000)^2;
1316 $fStepSize = (2*pi())/$iSteps;
1317 $aPolyPoints = array();
1318 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1320 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1322 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1323 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1324 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1325 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1329 // Output data suitable for display (points and a bounding box)
1330 if ($bShowPolygons && isset($aPolyPoints))
1332 $aResult['aPolyPoints'] = array();
1333 foreach($aPolyPoints as $aPoint)
1335 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1338 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1342 if (!isset($aResult['aBoundingBox']))
1345 $fDiameter = 0.0001;
1347 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1348 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1350 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1352 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1353 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1355 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1357 $fRadius = $fDiameter / 2;
1359 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1360 $fStepSize = (2*pi())/$iSteps;
1361 $aPolyPoints = array();
1362 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1364 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1366 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1367 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1368 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1369 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1371 // Output data suitable for display (points and a bounding box)
1374 $aResult['aPolyPoints'] = array();
1375 foreach($aPolyPoints as $aPoint)
1377 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1380 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1383 // Is there an icon set for this type of result?
1384 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1385 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1387 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1390 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1391 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1393 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1396 if ($bShowAddressDetails)
1398 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1399 //var_dump($aResult['address']);
1403 // Adjust importance for the number of exact string matches in the result
1404 $aResult['importance'] = max(0.001,$aResult['importance']);
1406 $sAddress = $aResult['langaddress'];
1407 foreach($aRecheckWords as $i => $sWord)
1409 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1411 $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
1413 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1415 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1416 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1418 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1420 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1421 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1423 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1427 $aResult['importance'] = 1000000000000000;
1430 $aResult['name'] = $aResult['langaddress'];
1431 $aResult['foundorder'] = $iResNum;
1432 $aSearchResults[$iResNum] = $aResult;
1434 uasort($aSearchResults, 'byImportance');
1436 //var_dump($aSearchResults);exit;
1438 $aOSMIDDone = array();
1439 $aClassTypeNameDone = array();
1440 $aToFilter = $aSearchResults;
1441 $aSearchResults = array();
1444 foreach($aToFilter as $iResNum => $aResult)
1446 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1447 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1450 $fLat = $aResult['lat'];
1451 $fLon = $aResult['lon'];
1452 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1455 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1456 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1458 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1459 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1460 $aSearchResults[] = $aResult;
1463 // Absolute limit on number of results
1464 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1467 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1469 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1471 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1476 logEnd($oDB, $hLog, sizeof($aToFilter));
1478 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1479 $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1480 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1481 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1482 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1483 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1486 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1488 $sMoreURL .= '&q='.urlencode($sQuery);
1490 if (CONST_Debug) exit;
1492 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');