2 @define('CONST_ConnectionBucket_PageType', 'Search');
4 require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
5 require_once(CONST_BasePath.'/lib/log.php');
7 ini_set('memory_limit', '200M');
12 $fLat = CONST_Default_Lat;
13 $fLon = CONST_Default_Lon;
14 $iZoom = CONST_Default_Zoom;
15 $bBoundingBoxSearch = isset($_GET['bounded'])?(bool)$_GET['bounded']:false;
16 $sOutputFormat = 'html';
17 $aSearchResults = array();
18 $aExcludePlaceIDs = array();
19 $sCountryCodesSQL = false;
20 $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
21 $bReverseInPlan = false;
22 $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
23 $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
25 if ($iFinalLimit > 50) $iFinalLimit = 50;
26 $iLimit = $iFinalLimit + min($iFinalLimit, 10);
28 $iMaxAddressRank = 30;
29 $sAllowedTypesSQLList = false;
32 if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' || $_GET['format'] == 'jsonv2'))
34 $sOutputFormat = $_GET['format'];
37 // Show / use polygons
38 $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
39 if ($sOutputFormat == 'html')
41 $bAsText = $bShowPolygons;
42 $bShowPolygons = false;
49 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
50 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
51 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
52 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
53 if ((($bShowPolygons?1:0)
58 ) > CONST_PolygonOutput_MaximumTypes)
60 if (CONST_PolygonOutput_MaximumTypes)
62 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
66 userError("Polygon output is disabled");
72 // Show address breakdown
73 $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
76 $aLangPrefOrder = getPreferredLanguages();
77 if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
78 if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
79 if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
81 $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
83 if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
85 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
87 $iExcludedPlaceID = (int)$iExcludedPlaceID;
88 if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
92 // Only certain ranks of feature
93 if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
95 if (isset($_GET['featuretype']))
97 switch($_GET['featuretype'])
100 $iMinAddressRank = $iMaxAddressRank = 4;
103 $iMinAddressRank = $iMaxAddressRank = 8;
106 $iMinAddressRank = 14;
107 $iMaxAddressRank = 16;
110 $iMinAddressRank = 8;
111 $iMaxAddressRank = 20;
116 if (isset($_GET['countrycodes']))
118 $aCountryCodes = array();
119 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
121 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
123 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
126 $sCountryCodesSQL = join(',', $aCountryCodes);
130 $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
131 if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
133 $sQuery = substr($_SERVER['PATH_INFO'], 1);
135 // reverse order of '/' separated string
136 $aPhrases = explode('/', $sQuery);
137 $aPhrases = array_reverse($aPhrases);
138 $sQuery = join(', ',$aPhrases);
142 $aStructuredOptions = array(
143 array('amenity', 26, 30),
144 array('street', 26, 30),
145 array('city', 14, 24),
146 array('county', 9, 13),
147 array('state', 8, 8),
148 array('country', 4, 4),
149 array('postalcode', 5, 11),
151 $aStructuredQuery = array();
152 $sAllowedTypesSQLList = '';
153 foreach($aStructuredOptions as $aStructuredOption)
155 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
157 if (sizeof($aStructuredQuery) > 0)
159 $sQuery = join(', ', $aStructuredQuery);
160 if ($iMaxAddressRank < 30)
162 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
168 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
170 // Hack to make it handle "new york, ny" (and variants) correctly
171 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
172 if (isset($aLangPrefOrder['name:en']))
174 $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
175 $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
176 $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
179 // If we have a view box create the SQL
180 // Small is the actual view box, Large is double (on each axis) that
181 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
182 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
184 $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
185 $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
187 if (isset($_GET['viewbox']) && $_GET['viewbox'])
189 $aCoOrdinates = explode(',',$_GET['viewbox']);
190 $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
191 $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
192 $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
193 $aCoOrdinates[0] += $fHeight;
194 $aCoOrdinates[2] -= $fHeight;
195 $aCoOrdinates[1] += $fWidth;
196 $aCoOrdinates[3] -= $fWidth;
197 $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
201 $bBoundingBoxSearch = false;
203 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
205 $aPoints = explode(',',$_GET['route']);
206 if (sizeof($aPoints) % 2 != 0)
208 userError("Uneven number of points");
211 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
213 foreach($aPoints as $i => $fPoint)
217 if ($i != 1) $sViewboxCentreSQL .= ",";
218 $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
222 $fPrevCoord = (float)$fPoint;
225 $sViewboxCentreSQL .= ")'::geometry,4326)";
227 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
228 $sViewboxSmallSQL = $oDB->getOne($sSQL);
229 if (PEAR::isError($sViewboxSmallSQL))
231 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
233 $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
235 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
236 $sViewboxLargeSQL = $oDB->getOne($sSQL);
237 if (PEAR::isError($sViewboxLargeSQL))
239 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
241 $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
242 $bBoundingBoxSearch = true;
245 // Do we have anything that looks like a lat/lon pair?
246 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
248 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
249 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
250 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
252 $_GET['nearlat'] = $fQueryLat;
253 $_GET['nearlon'] = $fQueryLon;
254 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
257 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
259 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
260 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
261 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
263 $_GET['nearlat'] = $fQueryLat;
264 $_GET['nearlon'] = $fQueryLon;
265 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
268 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
270 $fQueryLat = $aData[2];
271 $fQueryLon = $aData[3];
272 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
274 $_GET['nearlat'] = $fQueryLat;
275 $_GET['nearlon'] = $fQueryLon;
276 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
280 if ($sQuery || $aStructuredQuery)
282 // Start with a blank search
284 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
285 'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
286 'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
289 $sNearPointSQL = false;
290 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
292 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".(float)$_GET['nearlat']."),4326)";
293 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
294 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
295 $aSearches[0]['fRadius'] = 0.1;
298 $bSpecialTerms = false;
299 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
300 $aSpecialTerms = array();
301 foreach($aSpecialTermsRaw as $aSpecialTerm)
303 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
304 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
307 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
308 $aSpecialTerms = array();
309 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
311 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
312 unset($aStructuredQuery['amenity']);
314 foreach($aSpecialTermsRaw as $aSpecialTerm)
316 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
317 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
318 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
319 $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';
320 if (CONST_Debug) var_Dump($sSQL);
321 $aSearchWords = $oDB->getAll($sSQL);
322 $aNewSearches = array();
323 foreach($aSearches as $aSearch)
325 foreach($aSearchWords as $aSearchTerm)
327 $aNewSearch = $aSearch;
328 if ($aSearchTerm['country_code'])
330 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
331 $aNewSearches[] = $aNewSearch;
332 $bSpecialTerms = true;
334 if ($aSearchTerm['class'])
336 $aNewSearch['sClass'] = $aSearchTerm['class'];
337 $aNewSearch['sType'] = $aSearchTerm['type'];
338 $aNewSearches[] = $aNewSearch;
339 $bSpecialTerms = true;
343 $aSearches = $aNewSearches;
346 // Split query into phrases
347 // Commas are used to reduce the search space by indicating where phrases split
348 if (sizeof($aStructuredQuery) > 0)
350 $aPhrases = $aStructuredQuery;
351 $bStructuredPhrases = true;
355 $aPhrases = explode(',',$sQuery);
356 $bStructuredPhrases = false;
360 // Convert each phrase to standard form
361 // Create a list of standard words
362 // Get all 'sets' of words
363 // Generate a complete list of all
365 foreach($aPhrases as $iPhrase => $sPhrase)
367 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
368 if (PEAR::isError($aPhrase))
370 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
371 if (CONST_Debug) var_dump($aPhrase);
374 if (trim($aPhrase['string']))
376 $aPhrases[$iPhrase] = $aPhrase;
377 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
378 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
379 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
383 unset($aPhrases[$iPhrase]);
387 // reindex phrases - we make assumptions later on
388 $aPhraseTypes = array_keys($aPhrases);
389 $aPhrases = array_values($aPhrases);
391 if (sizeof($aTokens))
394 // Check which tokens we have, get the ID numbers
395 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
396 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
397 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
398 //$sSQL .= ' group by word_token, word, class, type, country_code';
400 if (CONST_Debug) var_Dump($sSQL);
402 $aValidTokens = array();
403 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
404 else $aDatabaseWords = array();
405 if (PEAR::IsError($aDatabaseWords))
407 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
409 $aPossibleMainWordIDs = array();
410 $aWordFrequencyScores = array();
411 foreach($aDatabaseWords as $aToken)
413 // Very special case - require 2 letter country param to match the country code found
414 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
415 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
420 if (isset($aValidTokens[$aToken['word_token']]))
422 $aValidTokens[$aToken['word_token']][] = $aToken;
426 $aValidTokens[$aToken['word_token']] = array($aToken);
428 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
429 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
431 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
433 // Try and calculate GB postcodes we might be missing
434 foreach($aTokens as $sToken)
436 // Source of gb postcodes is now definitive - always use
437 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
439 if (substr($aData[1],-2,1) != ' ')
441 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
442 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
444 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
445 if ($aGBPostcodeLocation)
447 $aValidTokens[$sToken] = $aGBPostcodeLocation;
452 foreach($aTokens as $sToken)
454 // Unknown single word token with a number - assume it is a house number
455 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
457 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
461 // Any words that have failed completely?
464 // Start the search process
465 $aResultPlaceIDs = array();
468 Calculate all searches using aValidTokens i.e.
470 'Wodsworth Road, Sheffield' =>
474 0 1 (wodsworth)(road)
477 Score how good the search is so they can be ordered
479 foreach($aPhrases as $iPhrase => $sPhrase)
481 $aNewPhraseSearches = array();
482 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
483 else $sPhraseType = '';
485 foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
487 $aWordsetSearches = $aSearches;
489 // Add all words from this wordset
490 foreach($aWordset as $iToken => $sToken)
492 //echo "<br><b>$sToken</b>";
493 $aNewWordsetSearches = array();
495 foreach($aWordsetSearches as $aCurrentSearch)
498 //var_dump($aCurrentSearch);
501 // If the token is valid
502 if (isset($aValidTokens[' '.$sToken]))
504 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
506 $aSearch = $aCurrentSearch;
507 $aSearch['iSearchRank']++;
508 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
510 if ($aSearch['sCountryCode'] === false)
512 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
513 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
514 // If reverse order is enabled, it may appear at the beginning as well.
515 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
516 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
518 $aSearch['iSearchRank'] += 5;
520 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
523 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
525 if ($aSearch['fLat'] === '')
527 $aSearch['fLat'] = $aSearchTerm['lat'];
528 $aSearch['fLon'] = $aSearchTerm['lon'];
529 $aSearch['fRadius'] = $aSearchTerm['radius'];
530 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
533 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
535 if ($aSearch['sHouseNumber'] === '')
537 $aSearch['sHouseNumber'] = $sToken;
538 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
540 // Fall back to not searching for this item (better than nothing)
541 $aSearch = $aCurrentSearch;
542 $aSearch['iSearchRank'] += 1;
543 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
547 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
549 if ($aSearch['sClass'] === '')
551 $aSearch['sOperator'] = $aSearchTerm['operator'];
552 $aSearch['sClass'] = $aSearchTerm['class'];
553 $aSearch['sType'] = $aSearchTerm['type'];
554 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
555 else $aSearch['sOperator'] = 'near'; // near = in for the moment
557 // Do we have a shortcut id?
558 if ($aSearch['sOperator'] == 'name')
560 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
561 if ($iAmenityID = $oDB->getOne($sSQL))
563 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
564 $aSearch['aName'][$iAmenityID] = $iAmenityID;
565 $aSearch['sClass'] = '';
566 $aSearch['sType'] = '';
569 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
572 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
574 if (sizeof($aSearch['aName']))
576 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
578 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
582 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
583 $aSearch['iSearchRank'] += 1000; // skip;
588 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
589 //$aSearch['iNamePhrase'] = $iPhrase;
591 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
595 if (isset($aValidTokens[$sToken]))
597 // Allow searching for a word - but at extra cost
598 foreach($aValidTokens[$sToken] as $aSearchTerm)
600 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
602 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
604 $aSearch = $aCurrentSearch;
605 $aSearch['iSearchRank'] += 1;
606 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
608 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
609 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
611 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
613 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
615 if (empty($aSearchTermToken['country_code'])
616 && empty($aSearchTermToken['lat'])
617 && empty($aSearchTermToken['class']))
619 $aSearch = $aCurrentSearch;
620 $aSearch['iSearchRank'] += 1;
621 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
622 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
628 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
629 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
633 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
635 $aSearch = $aCurrentSearch;
636 $aSearch['iSearchRank'] += 2;
637 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
638 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
639 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
641 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
642 $aSearch['iNamePhrase'] = $iPhrase;
643 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
650 // Allow skipping a word - but at EXTREAM cost
651 //$aSearch = $aCurrentSearch;
652 //$aSearch['iSearchRank']+=100;
653 //$aNewWordsetSearches[] = $aSearch;
657 usort($aNewWordsetSearches, 'bySearchRank');
658 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
660 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
662 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
663 usort($aNewPhraseSearches, 'bySearchRank');
665 $aSearchHash = array();
666 foreach($aNewPhraseSearches as $iSearch => $aSearch)
668 $sHash = serialize($aSearch);
669 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
670 else $aSearchHash[$sHash] = 1;
673 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
676 // Re-group the searches by their score, junk anything over 20 as just not worth trying
677 $aGroupedSearches = array();
678 foreach($aNewPhraseSearches as $aSearch)
680 if ($aSearch['iSearchRank'] < $iMaxRank)
682 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
683 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
686 ksort($aGroupedSearches);
689 $aSearches = array();
690 foreach($aGroupedSearches as $iScore => $aNewSearches)
692 $iSearchCount += sizeof($aNewSearches);
693 $aSearches = array_merge($aSearches, $aNewSearches);
694 if ($iSearchCount > 50) break;
697 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
703 // Re-group the searches by their score, junk anything over 20 as just not worth trying
704 $aGroupedSearches = array();
705 foreach($aSearches as $aSearch)
707 if ($aSearch['iSearchRank'] < $iMaxRank)
709 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
710 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
713 ksort($aGroupedSearches);
716 if (CONST_Debug) var_Dump($aGroupedSearches);
720 $aCopyGroupedSearches = $aGroupedSearches;
721 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
723 foreach($aSearches as $iSearch => $aSearch)
725 if (sizeof($aSearch['aAddress']))
727 $iReverseItem = array_pop($aSearch['aAddress']);
728 if (isset($aPossibleMainWordIDs[$iReverseItem]))
730 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
731 $aSearch['aName'] = array($iReverseItem);
732 $aGroupedSearches[$iGroup][] = $aSearch;
734 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
735 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
741 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
743 $aCopyGroupedSearches = $aGroupedSearches;
744 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
746 foreach($aSearches as $iSearch => $aSearch)
748 $aReductionsList = array($aSearch['aAddress']);
749 $iSearchRank = $aSearch['iSearchRank'];
750 while(sizeof($aReductionsList) > 0)
753 if ($iSearchRank > iMaxRank) break 3;
754 $aNewReductionsList = array();
755 foreach($aReductionsList as $aReductionsWordList)
757 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
759 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
760 $aReverseSearch = $aSearch;
761 $aSearch['aAddress'] = $aReductionsWordListResult;
762 $aSearch['iSearchRank'] = $iSearchRank;
763 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
764 if (sizeof($aReductionsWordListResult) > 0)
766 $aNewReductionsList[] = $aReductionsWordListResult;
770 $aReductionsList = $aNewReductionsList;
774 ksort($aGroupedSearches);
777 // Filter out duplicate searches
778 $aSearchHash = array();
779 foreach($aGroupedSearches as $iGroup => $aSearches)
781 foreach($aSearches as $iSearch => $aSearch)
783 $sHash = serialize($aSearch);
784 if (isset($aSearchHash[$sHash]))
786 unset($aGroupedSearches[$iGroup][$iSearch]);
787 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
791 $aSearchHash[$sHash] = 1;
796 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
800 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
803 foreach($aSearches as $aSearch)
807 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
808 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
811 // Must have a location term
812 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
814 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
816 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
818 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
819 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
820 $sSQL .= " order by st_area(geometry) desc limit 1";
821 if (CONST_Debug) var_dump($sSQL);
822 $aPlaceIDs = $oDB->getCol($sSQL);
827 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
828 if (!$aSearch['sClass']) continue;
829 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
830 if ($oDB->getOne($sSQL))
832 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
833 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
834 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
835 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
836 if (sizeof($aExcludePlaceIDs))
838 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
840 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
841 $sSQL .= " limit $iLimit";
842 if (CONST_Debug) var_dump($sSQL);
843 $aPlaceIDs = $oDB->getCol($sSQL);
845 // If excluded place IDs are given, it is fair to assume that
846 // there have been results in the small box, so no further
847 // expansion in that case.
848 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
850 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
851 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
852 $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
853 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
854 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
855 $sSQL .= " limit $iLimit";
856 if (CONST_Debug) var_dump($sSQL);
857 $aPlaceIDs = $oDB->getCol($sSQL);
862 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
863 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
864 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
865 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
866 $sSQL .= " limit $iLimit";
867 if (CONST_Debug) var_dump($sSQL);
868 $aPlaceIDs = $oDB->getCol($sSQL);
874 $aPlaceIDs = array();
876 // First we need a position, either aName or fLat or both
880 // TODO: filter out the pointless search terms (2 letter name tokens and less)
881 // they might be right - but they are just too darned expensive to run
882 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
883 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
884 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
886 // For infrequent name terms disable index usage for address
887 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
888 sizeof($aSearch['aName']) == 1 &&
889 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
891 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
895 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
896 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
899 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
900 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
901 if ($aSearch['fLon'] && $aSearch['fLat'])
903 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
904 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
906 if (sizeof($aExcludePlaceIDs))
908 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
910 if ($sCountryCodesSQL)
912 $aTerms[] = "country_code in ($sCountryCodesSQL)";
915 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
916 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
918 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
919 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
920 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
921 $aOrder[] = "$sImportanceSQL DESC";
922 if (sizeof($aSearch['aFullNameAddress']))
923 $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
927 $sSQL = "select place_id";
928 $sSQL .= " from search_name";
929 $sSQL .= " where ".join(' and ',$aTerms);
930 $sSQL .= " order by ".join(', ',$aOrder);
931 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
932 $sSQL .= " limit 50";
933 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
936 $sSQL .= " limit ".$iLimit;
938 if (CONST_Debug) { var_dump($sSQL); }
939 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
940 if (PEAR::IsError($aViewBoxPlaceIDs))
942 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
944 //var_dump($aViewBoxPlaceIDs);
945 // Did we have an viewbox matches?
946 $aPlaceIDs = array();
947 $bViewBoxMatch = false;
948 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
950 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
951 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
952 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
953 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
954 $aPlaceIDs[] = $aViewBoxRow['place_id'];
957 //var_Dump($aPlaceIDs);
960 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
962 $aRoadPlaceIDs = $aPlaceIDs;
963 $sPlaceIDs = join(',',$aPlaceIDs);
965 // Now they are indexed look for a house attached to a street we found
966 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
967 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
968 if (sizeof($aExcludePlaceIDs))
970 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
972 $sSQL .= " limit $iLimit";
973 if (CONST_Debug) var_dump($sSQL);
974 $aPlaceIDs = $oDB->getCol($sSQL);
976 // If not try the aux fallback table
977 if (!sizeof($aPlaceIDs))
979 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
980 if (sizeof($aExcludePlaceIDs))
982 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
984 //$sSQL .= " limit $iLimit";
985 if (CONST_Debug) var_dump($sSQL);
986 $aPlaceIDs = $oDB->getCol($sSQL);
989 if (!sizeof($aPlaceIDs))
991 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
992 if (sizeof($aExcludePlaceIDs))
994 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
996 //$sSQL .= " limit $iLimit";
997 if (CONST_Debug) var_dump($sSQL);
998 $aPlaceIDs = $oDB->getCol($sSQL);
1001 // Fallback to the road
1002 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1004 $aPlaceIDs = $aRoadPlaceIDs;
1009 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1011 $sPlaceIDs = join(',',$aPlaceIDs);
1012 $aClassPlaceIDs = array();
1014 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1016 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1017 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1018 $sSQL .= " and linked_place_id is null";
1019 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1020 $sSQL .= " order by rank_search asc limit $iLimit";
1021 if (CONST_Debug) var_dump($sSQL);
1022 $aClassPlaceIDs = $oDB->getCol($sSQL);
1025 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1027 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1028 $bCacheTable = $oDB->getOne($sSQL);
1030 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1032 if (CONST_Debug) var_dump($sSQL);
1033 $iMaxRank = ((int)$oDB->getOne($sSQL));
1035 // For state / country level searches the normal radius search doesn't work very well
1036 $sPlaceGeom = false;
1037 if ($iMaxRank < 9 && $bCacheTable)
1039 // Try and get a polygon to search in instead
1040 $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";
1041 if (CONST_Debug) var_dump($sSQL);
1042 $sPlaceGeom = $oDB->getOne($sSQL);
1052 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1053 if (CONST_Debug) var_dump($sSQL);
1054 $aPlaceIDs = $oDB->getCol($sSQL);
1055 $sPlaceIDs = join(',',$aPlaceIDs);
1058 if ($sPlaceIDs || $sPlaceGeom)
1064 // More efficient - can make the range bigger
1068 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1069 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1070 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1072 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1073 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1076 $sSQL .= ",placex as f where ";
1077 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1082 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1084 if (sizeof($aExcludePlaceIDs))
1086 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1088 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1089 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1090 if ($iOffset) $sSQL .= " offset $iOffset";
1091 $sSQL .= " limit $iLimit";
1092 if (CONST_Debug) var_dump($sSQL);
1093 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1097 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1100 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1101 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1103 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1104 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1105 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1106 if (sizeof($aExcludePlaceIDs))
1108 $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1110 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1111 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1112 if ($iOffset) $sSQL .= " offset $iOffset";
1113 $sSQL .= " limit $iLimit";
1114 if (CONST_Debug) var_dump($sSQL);
1115 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1120 $aPlaceIDs = $aClassPlaceIDs;
1126 if (PEAR::IsError($aPlaceIDs))
1128 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1131 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1133 foreach($aPlaceIDs as $iPlaceID)
1135 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1137 if ($iQueryLoop > 20) break;
1141 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1142 if ($iGroupLoop > 4) break;
1143 if ($iQueryLoop > 30) break;
1146 // Did we find anything?
1147 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1149 //var_Dump($aResultPlaceIDs);exit;
1150 // Get the details for display (is this a redundant extra step?)
1151 $sPlaceIDs = join(',',$aResultPlaceIDs);
1152 $sOrderSQL = 'CASE ';
1153 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1155 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1157 $sOrderSQL .= ' ELSE 10000000 END';
1158 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1159 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1160 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1161 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1162 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1163 //$sSQL .= $sOrderSQL." as porder, ";
1164 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1165 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(placex.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1166 $sSQL .= "(extratags->'place') as extra_place ";
1167 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1168 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1169 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1171 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1172 $sSQL .= "and linked_place_id is null ";
1173 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1174 if (!$bDeDupe) $sSQL .= ",place_id";
1175 $sSQL .= ",langaddress ";
1176 $sSQL .= ",placename ";
1178 $sSQL .= ",extratags->'place' ";
1180 $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,";
1181 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1182 $sSQL .= "null as placename,";
1183 $sSQL .= "null as ref,";
1184 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1185 //$sSQL .= $sOrderSQL." as porder, ";
1186 $sSQL .= "-0.15 as importance, ";
1187 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_tiger.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1188 $sSQL .= "null as extra_place ";
1189 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1190 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1191 $sSQL .= "group by place_id";
1192 if (!$bDeDupe) $sSQL .= ",place_id";
1194 $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,";
1195 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1196 $sSQL .= "null as placename,";
1197 $sSQL .= "null as ref,";
1198 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1199 //$sSQL .= $sOrderSQL." as porder, ";
1200 $sSQL .= "-0.10 as importance, ";
1201 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
1202 $sSQL .= "null as extra_place ";
1203 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1204 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1205 $sSQL .= "group by place_id";
1206 if (!$bDeDupe) $sSQL .= ",place_id";
1207 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1208 $sSQL .= "order by importance desc";
1209 //$sSQL .= "order by rank_search,rank_address,porder asc";
1210 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1211 $aSearchResults = $oDB->getAll($sSQL);
1212 //var_dump($sSQL,$aSearchResults);exit;
1214 if (PEAR::IsError($aSearchResults))
1216 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1219 } // end if ($sQuery)
1222 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1224 $iPlaceID = geocodeReverse((float)$_GET['nearlat'], (float)$_GET['nearlon']);
1228 $aResultPlaceIDs = array($iPlaceID);
1229 // TODO: this needs refactoring!
1231 // Get the details for display (is this a redundant extra step?)
1232 $sPlaceIDs = join(',',$aResultPlaceIDs);
1233 $sOrderSQL = 'CASE ';
1234 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1236 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1238 $sOrderSQL .= ' ELSE 10000000 END';
1239 $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,calculated_country_code as country_code,";
1240 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1241 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1242 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1243 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1244 //$sSQL .= $sOrderSQL." as porder, ";
1245 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1246 $sSQL .= "(extratags->'place') as extra_place ";
1247 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1248 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1249 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1251 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1252 if (!$bDeDupe) $sSQL .= ",place_id";
1253 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1254 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1255 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1256 $sSQL .= ",extratags->'place' ";
1258 $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,";
1259 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1260 $sSQL .= "null as placename,";
1261 $sSQL .= "null as ref,";
1262 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1263 //$sSQL .= $sOrderSQL." as porder, ";
1264 $sSQL .= "-0.15 as importance, ";
1265 $sSQL .= "null as extra_place ";
1266 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1267 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1268 $sSQL .= "group by place_id";
1269 if (!$bDeDupe) $sSQL .= ",place_id";
1271 $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,";
1272 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1273 $sSQL .= "null as placename,";
1274 $sSQL .= "null as ref,";
1275 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1276 //$sSQL .= $sOrderSQL." as porder, ";
1277 $sSQL .= "-0.10 as importance, ";
1278 $sSQL .= "null as extra_place ";
1279 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1280 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1281 $sSQL .= "group by place_id";
1282 if (!$bDeDupe) $sSQL .= ",place_id";
1283 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1284 $sSQL .= "order by importance desc";
1285 //$sSQL .= "order by rank_search,rank_address,porder asc";
1286 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1287 $aSearchResults = $oDB->getAll($sSQL);
1288 //var_dump($sSQL,$aSearchResults);exit;
1290 if (PEAR::IsError($aSearchResults))
1292 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1297 $aSearchResults = array();
1303 $sSearchResult = '';
1304 if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1306 $sSearchResult = 'No Results Found';
1308 //var_Dump($aSearchResults);
1310 $aClassType = getClassTypesWithImportance();
1311 $aRecheckWords = preg_split('/\b/u',$sQuery);
1312 foreach($aRecheckWords as $i => $sWord)
1314 if (!$sWord) unset($aRecheckWords[$i]);
1316 foreach($aSearchResults as $iResNum => $aResult)
1318 if (CONST_Search_AreaPolygons)
1320 // Get the bounding box and outline polygon
1321 $sSQL = "select place_id,numfeatures,area,outline,";
1322 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1323 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1324 $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1326 $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1327 $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1328 $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1329 $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1330 if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1331 if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1332 if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1333 if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1334 $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1335 $aPointPolygon = $oDB->getRow($sSQL);
1336 if (PEAR::IsError($aPointPolygon))
1338 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1340 if ($aPointPolygon['place_id'])
1342 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1343 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1344 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1345 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1347 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1349 $aResult['lat'] = $aPointPolygon['centrelat'];
1350 $aResult['lon'] = $aPointPolygon['centrelon'];
1354 // Translate geometary string to point array
1355 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1357 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1359 elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1361 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1363 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1366 $iSteps = ($fRadius * 40000)^2;
1367 $fStepSize = (2*pi())/$iSteps;
1368 $aPolyPoints = array();
1369 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1371 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1373 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1374 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1375 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1376 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1380 // Output data suitable for display (points and a bounding box)
1381 if ($bShowPolygons && isset($aPolyPoints))
1383 $aResult['aPolyPoints'] = array();
1384 foreach($aPolyPoints as $aPoint)
1386 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1389 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1393 if ($aResult['extra_place'] == 'city')
1395 $aResult['class'] = 'place';
1396 $aResult['type'] = 'city';
1397 $aResult['rank_search'] = 16;
1400 if (!isset($aResult['aBoundingBox']))
1403 $fDiameter = 0.0001;
1405 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1406 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1408 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1410 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1411 && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1413 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1415 $fRadius = $fDiameter / 2;
1417 $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1418 $fStepSize = (2*pi())/$iSteps;
1419 $aPolyPoints = array();
1420 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1422 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1424 $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1425 $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1426 $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1427 $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1429 // Output data suitable for display (points and a bounding box)
1432 $aResult['aPolyPoints'] = array();
1433 foreach($aPolyPoints as $aPoint)
1435 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1438 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1441 // Is there an icon set for this type of result?
1442 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1443 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1445 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1448 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1449 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1451 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1454 if ($bShowAddressDetails)
1456 $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1457 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1459 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1462 //var_dump($aResult['address']);
1466 // Adjust importance for the number of exact string matches in the result
1467 $aResult['importance'] = max(0.001,$aResult['importance']);
1469 $sAddress = $aResult['langaddress'];
1470 foreach($aRecheckWords as $i => $sWord)
1472 if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1475 $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
1477 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1479 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1480 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1482 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1484 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1485 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1487 $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1491 $aResult['importance'] = 1000000000000000;
1494 $aResult['name'] = $aResult['langaddress'];
1495 $aResult['foundorder'] = -$aResult['addressimportance'];
1496 $aSearchResults[$iResNum] = $aResult;
1498 uasort($aSearchResults, 'byImportance');
1500 $aOSMIDDone = array();
1501 $aClassTypeNameDone = array();
1502 $aToFilter = $aSearchResults;
1503 $aSearchResults = array();
1506 foreach($aToFilter as $iResNum => $aResult)
1508 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1509 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1512 $fLat = $aResult['lat'];
1513 $fLon = $aResult['lon'];
1514 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1517 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1518 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1520 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1521 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1522 $aSearchResults[] = $aResult;
1525 // Absolute limit on number of results
1526 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1529 $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1531 if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1533 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1538 logEnd($oDB, $hLog, sizeof($aToFilter));
1540 $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1541 if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1542 if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1543 if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1544 if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1545 if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1546 $sMoreURL .= '&q='.urlencode($sQuery);
1548 if (CONST_Debug) exit;
1550 include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');