]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
fix missing number conversion for coordinates
[nominatim.git] / website / search.php
1 <?php
2         @define('CONST_ConnectionBucket_PageType', 'Search');
3
4         require_once(dirname(dirname(__FILE__)).'/lib/init-website.php');
5         require_once(CONST_BasePath.'/lib/log.php');
6
7         ini_set('memory_limit', '200M');
8
9         $oDB =& getDB();
10
11         // Display defaults
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         $sSuggestion = $sSuggestionURL = false;
21         $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
22         $bReverseInPlan = false;
23         $iFinalLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
24         $iOffset = isset($_GET['offset'])?(int)$_GET['offset']:0;
25         $iMaxRank = 20;
26         if ($iFinalLimit > 50) $iFinalLimit = 50;
27         $iLimit = $iFinalLimit + min($iFinalLimit, 10);
28         $iMinAddressRank = 0;
29         $iMaxAddressRank = 30;
30         $sAllowedTypesSQLList = false;
31
32         // Format for output
33         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
34         {
35                 $sOutputFormat = $_GET['format'];
36         }
37
38         // Show / use polygons
39         $bShowPolygons = (boolean)isset($_GET['polygon']) && $_GET['polygon'];
40         if ($sOutputFormat == 'html')
41         {
42                 $bAsText = $bShowPolygons;
43                 $bShowPolygons = false;
44                 $bAsGeoJSON = false;
45                 $bAsKML = false;
46                 $bAsSVG = false;
47         }
48         else
49         {
50                 $bAsGeoJSON = (boolean)isset($_GET['polygon_geojson']) && $_GET['polygon_geojson'];
51                 $bAsKML = (boolean)isset($_GET['polygon_kml']) && $_GET['polygon_kml'];
52                 $bAsSVG = (boolean)isset($_GET['polygon_svg']) && $_GET['polygon_svg'];
53                 $bAsText = (boolean)isset($_GET['polygon_text']) && $_GET['polygon_text'];
54                 if ((($bShowPolygons?1:0)
55                                         + ($bAsGeoJSON?1:0)
56                                         + ($bAsKML?1:0)
57                                         + ($bAsSVG?1:0)
58                                         + ($bAsText?1:0)
59                         ) > CONST_PolygonOutput_MaximumTypes)
60                 {
61                         if (CONST_PolygonOutput_MaximumTypes)
62                         {
63                                 userError("Select only ".CONST_PolygonOutput_MaximumTypes." polgyon output option");
64                         }
65                         else
66                         {
67                                 userError("Polygon output is disabled");
68                         }
69                         exit;
70                 }
71         }
72
73         // Show address breakdown
74         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
75
76         // Preferred language
77         $aLangPrefOrder = getPreferredLanguages();
78         if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
79         if (isset($aLangPrefOrder['name:ru'])) $bReverseInPlan = true;
80         if (isset($aLangPrefOrder['name:ja'])) $bReverseInPlan = true;
81
82         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
83
84         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
85         {
86                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
87                 {
88                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
89                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
90                 }
91         }
92
93         // Only certain ranks of feature
94         if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
95
96         if (isset($_GET['featuretype']))
97         {
98                 switch($_GET['featuretype'])
99                 {
100                 case 'country':
101                         $iMinAddressRank = $iMaxAddressRank = 4;
102                         break;
103                 case 'state':
104                         $iMinAddressRank = $iMaxAddressRank = 8;
105                         break;
106                 case 'city':
107                         $iMinAddressRank = 14;
108                         $iMaxAddressRank = 16;
109                         break;
110                 case 'settlement':
111                         $iMinAddressRank = 8;
112                         $iMaxAddressRank = 20;
113                         break;
114                 }
115         }
116
117         if (isset($_GET['countrycodes']))
118         {
119                 $aCountryCodes = array();
120                 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
121                 {
122                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
123                         {
124                                 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
125                         }
126                 }
127                 $sCountryCodesSQL = join(',', $aCountryCodes);
128         }
129
130         // Search query
131         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
132         if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
133         {
134                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
135
136                 // reverse order of '/' separated string
137                 $aPhrases = explode('/', $sQuery);
138                 $aPhrases = array_reverse($aPhrases);
139                 $sQuery = join(', ',$aPhrases);
140         }
141
142         function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
143         {
144                 if (!isset($_GET[$sKey])) return false;
145                 $sValue = trim($_GET[$sKey]);
146                 if (!$sValue) return false;
147                 $aStructuredQuery[$sKey] = $sValue;
148                 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
149                 {
150                         $iMinAddressRank = $iNewMinAddressRank;
151                         $iMaxAddressRank = $iNewMaxAddressRank;
152                 }
153                 return true;
154         }
155
156         // Structured query?
157         $aStructuredOptions = array(
158                                 array('amenity', 26, 30),
159                                 array('street', 26, 30),
160                                 array('city', 14, 24),
161                                 array('county', 9, 13),
162                                 array('state', 8, 8),
163                                 array('country', 4, 4),
164                                 array('postalcode', 5, 11),
165                                 );
166         $aStructuredQuery = array();
167         $sAllowedTypesSQLList = '';
168         foreach($aStructuredOptions as $aStructuredOption)
169         {
170                 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
171         }
172         if (sizeof($aStructuredQuery) > 0) 
173         {
174                 $sQuery = join(', ', $aStructuredQuery);
175                 if ($iMaxAddressRank < 30)
176                 {
177                         $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
178                 }
179         }
180
181         if ($sQuery)
182         {
183                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
184
185                 // Hack to make it handle "new york, ny" (and variants) correctly
186                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
187                 if (isset($aLangPrefOrder['name:en']))
188                 {
189                         $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
190                         $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
191                         $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
192                 }
193
194                 // If we have a view box create the SQL
195                 // Small is the actual view box, Large is double (on each axis) that
196                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
197                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
198                 {
199                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
200                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
201                 }
202                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
203                 {
204                         $aCoOrdinates = explode(',',$_GET['viewbox']);
205                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
206                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
207                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
208                         $aCoOrdinates[0] += $fHeight;
209                         $aCoOrdinates[2] -= $fHeight;
210                         $aCoOrdinates[1] += $fWidth;
211                         $aCoOrdinates[3] -= $fWidth;
212                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
213                 }
214                 else
215                 {
216                         $bBoundingBoxSearch = false;
217                 }
218                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
219                 {
220                         $aPoints = explode(',',$_GET['route']);
221                         if (sizeof($aPoints) % 2 != 0)
222                         {
223                                 userError("Uneven number of points");
224                                 exit;
225                         }
226                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
227                         $fPrevCoord = false;
228                         foreach($aPoints as $i => $fPoint)
229                         {
230                                 if ($i%2)
231                                 {
232                                         if ($i != 1) $sViewboxCentreSQL .= ",";
233                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
234                                 }
235                                 else
236                                 {
237                                         $fPrevCoord = (float)$fPoint;
238                                 }
239                         }
240                         $sViewboxCentreSQL .= ")'::geometry,4326)";
241
242                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
243                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
244                         if (PEAR::isError($sViewboxSmallSQL))
245                         {
246                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
247                         }
248                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
249
250                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
251                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
252                         if (PEAR::isError($sViewboxLargeSQL))
253                         {
254                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
255                         }
256                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
257                         $bBoundingBoxSearch = true;
258                 }
259
260                 // Do we have anything that looks like a lat/lon pair?
261                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
262                 {
263                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
264                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
265                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
266                         {
267                                 $_GET['nearlat'] = $fQueryLat;
268                                 $_GET['nearlon'] = $fQueryLon;
269                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
270                         }
271                 }
272                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
273                 {
274                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
275                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
276                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
277                         {
278                                 $_GET['nearlat'] = $fQueryLat;
279                                 $_GET['nearlon'] = $fQueryLon;
280                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
281                         }
282                 }
283                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
284                 {
285                         $fQueryLat = $aData[2];
286                         $fQueryLon = $aData[3];
287                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
288                         {
289                                 $_GET['nearlat'] = $fQueryLat;
290                                 $_GET['nearlon'] = $fQueryLon;
291                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
292                         }
293                 }
294
295                 if ($sQuery || $aStructuredQuery)
296                 {
297                         // Start with a blank search
298                         $aSearches = array(
299                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
300                                       'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
301                                       'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
302                         );
303
304                         $sNearPointSQL = false;
305                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
306                         {
307                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".(float)$_GET['nearlat']."),4326)";
308                                 echo '<br><b>--'.$sNearPointSQL.'--</b><br>';
309                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
310                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
311                                 $aSearches[0]['fRadius'] = 0.1;
312                         }
313
314                         $bSpecialTerms = false;
315                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
316                         $aSpecialTerms = array();
317                         foreach($aSpecialTermsRaw as $aSpecialTerm)
318                         {
319                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
320                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
321                         }
322
323                         preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
324                         $aSpecialTerms = array();
325                         if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
326                         {
327                                 $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
328                                 unset($aStructuredQuery['amenity']);
329                         }
330                         foreach($aSpecialTermsRaw as $aSpecialTerm)
331                         {
332                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
333                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
334                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
335                                 $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';
336                                 if (CONST_Debug) var_Dump($sSQL);
337                                 $aSearchWords = $oDB->getAll($sSQL);
338                                 $aNewSearches = array();
339                                 foreach($aSearches as $aSearch)
340                                 {
341                                         foreach($aSearchWords as $aSearchTerm)
342                                         {
343                                                 $aNewSearch = $aSearch;
344                                                 if ($aSearchTerm['country_code'])
345                                                 {
346                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
347                                                         $aNewSearches[] = $aNewSearch;
348                                                         $bSpecialTerms = true;
349                                                 }
350                                                 if ($aSearchTerm['class'])
351                                                 {
352                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
353                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
354                                                         $aNewSearches[] = $aNewSearch;
355                                                         $bSpecialTerms = true;
356                                                 }
357                                         }
358                                 }
359                                 $aSearches = $aNewSearches;
360                         }
361
362                         // Split query into phrases
363                         // Commas are used to reduce the search space by indicating where phrases split
364                         if (sizeof($aStructuredQuery) > 0)
365                         {
366                                 $aPhrases = $aStructuredQuery;
367                                 $bStructuredPhrases = true;
368                         }
369                         else
370                         {
371                                 $aPhrases = explode(',',$sQuery);
372                                 $bStructuredPhrases = false;
373                         }
374
375
376                         // Convert each phrase to standard form
377                         // Create a list of standard words
378                         // Get all 'sets' of words
379                         // Generate a complete list of all
380                         $aTokens = array();
381                         foreach($aPhrases as $iPhrase => $sPhrase)
382                         {
383                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
384                                 if (PEAR::isError($aPhrase))
385                                 {
386                                         userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
387                                         if (CONST_Debug) var_dump($aPhrase);
388                                         exit;
389                                 }
390                                 if (trim($aPhrase['string']))
391                                 {
392                                         $aPhrases[$iPhrase] = $aPhrase;
393                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
394                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
395                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
396                                 }
397                                 else
398                                 {
399                                         unset($aPhrases[$iPhrase]);
400                                 }
401                         }
402
403                         // reindex phrases - we make assumptions later on
404                         $aPhraseTypes = array_keys($aPhrases);
405                         $aPhrases = array_values($aPhrases);
406
407                         if (sizeof($aTokens))
408                         {
409
410                                 // Check which tokens we have, get the ID numbers
411                                 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
412                                 $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
413                                 //$sSQL .= ' and search_name_count < '.CONST_Max_Word_Frequency;
414                                 //$sSQL .= ' group by word_token, word, class, type, country_code';
415
416                                 if (CONST_Debug) var_Dump($sSQL);
417
418                                 $aValidTokens = array();
419                                 if (sizeof($aTokens)) $aDatabaseWords = $oDB->getAll($sSQL);
420                                 else $aDatabaseWords = array();
421                                 if (PEAR::IsError($aDatabaseWords))
422                                 {
423                                         failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
424                                 }
425                                 $aPossibleMainWordIDs = array();
426                                 $aWordFrequencyScores = array();
427                                 foreach($aDatabaseWords as $aToken)
428                                 {
429                                         // Very special case - require 2 letter country param to match the country code found
430                                         if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
431                                                         && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
432                                         {
433                                                 continue;
434                                         }
435
436                                         if (isset($aValidTokens[$aToken['word_token']]))
437                                         {
438                                                 $aValidTokens[$aToken['word_token']][] = $aToken;
439                                         }
440                                         else
441                                         {
442                                                 $aValidTokens[$aToken['word_token']] = array($aToken);
443                                         }
444                                         if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
445                                         $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
446                                 }
447                                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
448
449                                 $aSuggestion = array();
450                                 $bSuggestion = false;
451                                 if (CONST_Suggestions_Enabled)
452                                 {
453                                         foreach($aPhrases as $iPhrase => $aPhrase)
454                                         {
455                                                 if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
456                                                 {
457                                                         $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
458                                                         $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
459                                                         $aRow = $aSuggestionWords[0];
460                                                         if ($aRow && $aRow['word'])
461                                                         {
462                                                                 $aSuggestion[] = $aRow['word'];
463                                                                 $bSuggestion = true;
464                                                         }
465                                                         else
466                                                         {
467                                                                 $aSuggestion[] = $aPhrase['string'];
468                                                         }
469                                                 }
470                                                 else
471                                                 {
472                                                         $aSuggestion[] = $aPhrase['string'];
473                                                 }
474                                         }
475                                 }
476                                 if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
477
478                                 // Try and calculate GB postcodes we might be missing
479                                 foreach($aTokens as $sToken)
480                                 {
481                                         // Source of gb postcodes is now definitive - always use
482                                         if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
483                                         {
484                                                 if (substr($aData[1],-2,1) != ' ')
485                                                 {
486                                                         $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
487                                                         $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
488                                                 }
489                                                 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
490                                                 if ($aGBPostcodeLocation)
491                                                 {
492                                                         $aValidTokens[$sToken] = $aGBPostcodeLocation;
493                                                 }
494                                         }
495                                 }
496
497                                 foreach($aTokens as $sToken)
498                                 {
499                                         // Unknown single word token with a number - assume it is a house number
500                                         if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
501                                         {
502                                                 $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
503                                         }
504                                 }
505
506                                 // Any words that have failed completely?
507                                 // TODO: suggestions
508
509                                 // Start the search process
510                                 $aResultPlaceIDs = array();
511
512                                 /*
513                                    Calculate all searches using aValidTokens i.e.
514
515                                    'Wodsworth Road, Sheffield' =>
516
517                                    Phrase Wordset
518                                    0      0       (wodsworth road)
519                                    0      1       (wodsworth)(road)
520                                    1      0       (sheffield)
521
522                                    Score how good the search is so they can be ordered
523                                  */
524                                 foreach($aPhrases as $iPhrase => $sPhrase)
525                                 {
526                                         $aNewPhraseSearches = array();
527                                         if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
528                                         else $sPhraseType = '';
529
530                                         foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
531                                         {
532                                                 $aWordsetSearches = $aSearches;
533
534                                                 // Add all words from this wordset
535                                                 foreach($aWordset as $iToken => $sToken)
536                                                 {
537                                                         //echo "<br><b>$sToken</b>";
538                                                         $aNewWordsetSearches = array();
539
540                                                         foreach($aWordsetSearches as $aCurrentSearch)
541                                                         {
542                                                                 //echo "<i>";
543                                                                 //var_dump($aCurrentSearch);
544                                                                 //echo "</i>";
545
546                                                                 // If the token is valid
547                                                                 if (isset($aValidTokens[' '.$sToken]))
548                                                                 {
549                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
550                                                                         {
551                                                                                 $aSearch = $aCurrentSearch;
552                                                                                 $aSearch['iSearchRank']++;
553                                                                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
554                                                                                 {
555                                                                                         if ($aSearch['sCountryCode'] === false)
556                                                                                         {
557                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
558                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
559                                                                                                 // If reverse order is enabled, it may appear at the beginning as well.
560                                                                                                 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
561                                                                                                                 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
562                                                                                                 {
563                                                                                                         $aSearch['iSearchRank'] += 5;
564                                                                                                 }
565                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
566                                                                                         }
567                                                                                 }
568                                                                                 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
569                                                                                 {
570                                                                                         if ($aSearch['fLat'] === '')
571                                                                                         {
572                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
573                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
574                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
575                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
576                                                                                         }
577                                                                                 }
578                                                                                 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
579                                                                                 {
580                                                                                         if ($aSearch['sHouseNumber'] === '')
581                                                                                         {
582                                                                                                 $aSearch['sHouseNumber'] = $sToken;
583                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
584                                                                                                 /*
585                                                                                                 // Fall back to not searching for this item (better than nothing)
586                                                                                                 $aSearch = $aCurrentSearch;
587                                                                                                 $aSearch['iSearchRank'] += 1;
588                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
589                                                                                                  */
590                                                                                         }
591                                                                                 }
592                                                                                 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
593                                                                                 {
594                                                                                         if ($aSearch['sClass'] === '')
595                                                                                         {
596                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
597                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
598                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
599                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
600                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
601
602                                                                                                 // Do we have a shortcut id?
603                                                                                                 if ($aSearch['sOperator'] == 'name')
604                                                                                                 {
605                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
606                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
607                                                                                                         {
608                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
609                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
610                                                                                                                 $aSearch['sClass'] = '';
611                                                                                                                 $aSearch['sType'] = '';
612                                                                                                         }
613                                                                                                 }
614                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
615                                                                                         }
616                                                                                 }
617                                                                                 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
618                                                                                 {
619                                                                                         if (sizeof($aSearch['aName']))
620                                                                                         {
621                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
622                                                                                                 {
623                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
624                                                                                                 }
625                                                                                                 else
626                                                                                                 {
627                                                                                                         $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
628                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
629                                                                                                 }
630                                                                                         }
631                                                                                         else
632                                                                                         {
633                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
634                                                                                                 //$aSearch['iNamePhrase'] = $iPhrase;
635                                                                                         }
636                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
637                                                                                 }
638                                                                         }
639                                                                 }
640                                                                 if (isset($aValidTokens[$sToken]))
641                                                                 {
642                                                                         // Allow searching for a word - but at extra cost
643                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
644                                                                         {
645                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
646                                                                                 {
647                                                                                         if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
648                                                                                         {
649                                                                                                 $aSearch = $aCurrentSearch;
650                                                                                                 $aSearch['iSearchRank'] += 1;
651                                                                                                 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
652                                                                                                 {
653                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
654                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
655                                                                                                 }
656                                                                                                 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
657                                                                                                 {
658                                                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
659                                                                                                         {
660                                                                                                                 if (empty($aSearchTermToken['country_code'])
661                                                                                                                                 && empty($aSearchTermToken['lat'])
662                                                                                                                                 && empty($aSearchTermToken['class']))
663                                                                                                                 {
664                                                                                                                         $aSearch = $aCurrentSearch;
665                                                                                                                         $aSearch['iSearchRank'] += 1;
666                                                                                                                         $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
667                                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
668                                                                                                                 }
669                                                                                                         }
670                                                                                                 }
671                                                                                                 else
672                                                                                                 {
673                                                                                                         $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
674                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
675                                                                                                 }
676                                                                                         }
677
678                                                                                         if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
679                                                                                         {
680                                                                                                 $aSearch = $aCurrentSearch;
681                                                                                                 $aSearch['iSearchRank'] += 2;
682                                                                                                 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
683                                                                                                 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
684                                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
685                                                                                                 else
686                                                                                                         $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
687                                                                                                 $aSearch['iNamePhrase'] = $iPhrase;
688                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
689                                                                                         }
690                                                                                 }
691                                                                         }
692                                                                 }
693                                                                 else
694                                                                 {
695                                                                         // Allow skipping a word - but at EXTREAM cost
696                                                                         //$aSearch = $aCurrentSearch;
697                                                                         //$aSearch['iSearchRank']+=100;
698                                                                         //$aNewWordsetSearches[] = $aSearch;
699                                                                 }
700                                                         }
701                                                         // Sort and cut
702                                                         usort($aNewWordsetSearches, 'bySearchRank');
703                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
704                                                 }
705                                                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
706
707                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
708                                                 usort($aNewPhraseSearches, 'bySearchRank');
709
710                                                 $aSearchHash = array();
711                                                 foreach($aNewPhraseSearches as $iSearch => $aSearch)
712                                                 {
713                                                         $sHash = serialize($aSearch);
714                                                         if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
715                                                         else $aSearchHash[$sHash] = 1;
716                                                 }
717
718                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
719                                         }
720
721                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
722                                         $aGroupedSearches = array();
723                                         foreach($aNewPhraseSearches as $aSearch)
724                                         {
725                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
726                                                 {
727                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
728                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
729                                                 }
730                                         }
731                                         ksort($aGroupedSearches);
732
733                                         $iSearchCount = 0;
734                                         $aSearches = array();
735                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
736                                         {
737                                                 $iSearchCount += sizeof($aNewSearches);
738                                                 $aSearches = array_merge($aSearches, $aNewSearches);
739                                                 if ($iSearchCount > 50) break;
740                                         }
741
742                                         //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
743
744                                 }
745                         }
746                         else
747                         {
748                                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
749                                 $aGroupedSearches = array();
750                                 foreach($aSearches as $aSearch)
751                                 {
752                                         if ($aSearch['iSearchRank'] < $iMaxRank)
753                                         {
754                                                 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
755                                                 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
756                                         }
757                                 }
758                                 ksort($aGroupedSearches);
759                         }
760
761                         if (CONST_Debug) var_Dump($aGroupedSearches);
762
763                         if ($bReverseInPlan)
764                         {
765                                 $aCopyGroupedSearches = $aGroupedSearches;
766                                 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
767                                 {
768                                         foreach($aSearches as $iSearch => $aSearch)
769                                         {
770                                                 if (sizeof($aSearch['aAddress']))
771                                                 {
772                                                         $iReverseItem = array_pop($aSearch['aAddress']);
773                                                         if (isset($aPossibleMainWordIDs[$iReverseItem]))
774                                                         {
775                                                                 $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
776                                                                 $aSearch['aName'] = array($iReverseItem);
777                                                                 $aGroupedSearches[$iGroup][] = $aSearch;
778                                                         }
779                                                         //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
780                                                         //$aGroupedSearches[$iGroup][] = $aReverseSearch;
781                                                 }
782                                         }
783                                 }
784                         }
785
786                         if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
787                         {
788                                 $aCopyGroupedSearches = $aGroupedSearches;
789                                 foreach($aCopyGroupedSearches as $iGroup => $aSearches)
790                                 {
791                                         foreach($aSearches as $iSearch => $aSearch)
792                                         {
793                                                 $aReductionsList = array($aSearch['aAddress']);
794                                                 $iSearchRank = $aSearch['iSearchRank'];
795                                                 while(sizeof($aReductionsList) > 0)
796                                                 {
797                                                         $iSearchRank += 5;
798                                                         if ($iSearchRank > iMaxRank) break 3;
799                                                         $aNewReductionsList = array();
800                                                         foreach($aReductionsList as $aReductionsWordList)
801                                                         {
802                                                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
803                                                                 {
804                                                                         $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
805                                                                         $aReverseSearch = $aSearch;
806                                                                         $aSearch['aAddress'] = $aReductionsWordListResult;
807                                                                         $aSearch['iSearchRank'] = $iSearchRank;
808                                                                         $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
809                                                                         if (sizeof($aReductionsWordListResult) > 0)
810                                                                         {
811                                                                                 $aNewReductionsList[] = $aReductionsWordListResult;
812                                                                         }
813                                                                 }
814                                                         }
815                                                         $aReductionsList = $aNewReductionsList;
816                                                 }
817                                         }
818                                 }
819                                 ksort($aGroupedSearches);
820                         }
821
822                         // Filter out duplicate searches
823                         $aSearchHash = array();
824                         foreach($aGroupedSearches as $iGroup => $aSearches)
825                         {
826                                 foreach($aSearches as $iSearch => $aSearch)
827                                 {
828                                         $sHash = serialize($aSearch);
829                                         if (isset($aSearchHash[$sHash]))
830                                         {
831                                                 unset($aGroupedSearches[$iGroup][$iSearch]);
832                                                 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
833                                         }
834                                         else
835                                         {
836                                                 $aSearchHash[$sHash] = 1;
837                                         }
838                                 }
839                         }
840
841                         if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
842
843                         $iGroupLoop = 0;
844                         $iQueryLoop = 0;
845                         foreach($aGroupedSearches as $iGroupedRank => $aSearches)
846                         {
847                                 $iGroupLoop++;
848                                 foreach($aSearches as $aSearch)
849                                 {
850                                         $iQueryLoop++;
851
852                                         if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
853                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
854
855
856                                         // Must have a location term
857                                         if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
858                                         {
859                                                 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
860                                                 {
861                                                         if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
862                                                         {
863                                                                 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
864                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
865                                                                 $sSQL .= " order by st_area(geometry) desc limit 1";
866                                                                 if (CONST_Debug) var_dump($sSQL);
867                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
868                                                         }
869                                                 }
870                                                 else
871                                                 {
872                                                         if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
873                                                         if (!$aSearch['sClass']) continue;
874                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
875                                                         if ($oDB->getOne($sSQL))
876                                                         {
877                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
878                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
879                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
880                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
881                                                                 if (sizeof($aExcludePlaceIDs))
882                                                                 {
883                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
884                                                                 }
885                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
886                                                                 $sSQL .= " limit $iLimit";
887                                                                 if (CONST_Debug) var_dump($sSQL);
888                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
889
890                                                                 // If excluded place IDs are given, it is fair to assume that
891                                                                 // there have been results in the small box, so no further
892                                                                 // expansion in that case.
893                                                                 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
894                                                                 {
895                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
896                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
897                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
898                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
899                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
900                                                                         $sSQL .= " limit $iLimit";
901                                                                         if (CONST_Debug) var_dump($sSQL);
902                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
903                                                                 }
904                                                         }
905                                                         else
906                                                         {
907                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
908                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
909                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
910                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
911                                                                 $sSQL .= " limit $iLimit";
912                                                                 if (CONST_Debug) var_dump($sSQL);
913                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
914                                                         }
915                                                 }
916                                         }
917                                         else
918                                         {
919                                                 $aPlaceIDs = array();
920
921                                                 // First we need a position, either aName or fLat or both
922                                                 $aTerms = array();
923                                                 $aOrder = array();
924
925                                                 // TODO: filter out the pointless search terms (2 letter name tokens and less)
926                                                 // they might be right - but they are just too darned expensive to run
927                                                 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
928                                                 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
929                                                 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
930                                                 {
931                                                         // For infrequent name terms disable index usage for address
932                                                         if (CONST_Search_NameOnlySearchFrequencyThreshold &&
933                                                                         sizeof($aSearch['aName']) == 1 &&
934                                                                         $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
935                                                         {
936                                                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
937                                                         }
938                                                         else
939                                                         {
940                                                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
941                                                                 if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
942                                                         }
943                                                 }
944                                                 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
945                                                 if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
946                                                 if ($aSearch['fLon'] && $aSearch['fLat'])
947                                                 {
948                                                         $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
949                                                         $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
950                                                 }
951                                                 if (sizeof($aExcludePlaceIDs))
952                                                 {
953                                                         $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
954                                                 }
955                                                 if ($sCountryCodesSQL)
956                                                 {
957                                                         $aTerms[] = "country_code in ($sCountryCodesSQL)";
958                                                 }
959
960                                                 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
961                                                 if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
962
963                                                 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
964                                                 if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
965                                                 if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
966                                                 $aOrder[] = "$sImportanceSQL DESC";
967                                                 if (sizeof($aSearch['aFullNameAddress']))
968                                                         $aOrder[] = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) DESC';
969
970                                                 if (sizeof($aTerms))
971                                                 {
972                                                         $sSQL = "select place_id";
973                                                         $sSQL .= " from search_name";
974                                                         $sSQL .= " where ".join(' and ',$aTerms);
975                                                         $sSQL .= " order by ".join(', ',$aOrder);
976                                                         if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
977                                                                 $sSQL .= " limit 50";
978                                                         elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
979                                                                 $sSQL .= " limit 1";
980                                                         else
981                                                                 $sSQL .= " limit ".$iLimit;
982
983                                                         if (CONST_Debug) { var_dump($sSQL); }
984                                                         $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
985                                                         if (PEAR::IsError($aViewBoxPlaceIDs))
986                                                         {
987                                                                 failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
988                                                         }
989                                                         //var_dump($aViewBoxPlaceIDs);
990                                                         // Did we have an viewbox matches?
991                                                         $aPlaceIDs = array();
992                                                         $bViewBoxMatch = false;
993                                                         foreach($aViewBoxPlaceIDs as $aViewBoxRow)
994                                                         {
995                                                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
996                                                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
997                                                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
998                                                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
999                                                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1000                                                         }
1001                                                 }
1002                                                 //var_Dump($aPlaceIDs);
1003                                                 //exit;
1004
1005                                                 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1006                                                 {
1007                                                         $aRoadPlaceIDs = $aPlaceIDs;
1008                                                         $sPlaceIDs = join(',',$aPlaceIDs);
1009
1010                                                         // Now they are indexed look for a house attached to a street we found
1011                                                         $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1012                                                         $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1013                                                         if (sizeof($aExcludePlaceIDs))
1014                                                         {
1015                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1016                                                         }
1017                                                         $sSQL .= " limit $iLimit";
1018                                                         if (CONST_Debug) var_dump($sSQL);
1019                                                         $aPlaceIDs = $oDB->getCol($sSQL);
1020
1021                                                         // If not try the aux fallback table
1022                                                         if (!sizeof($aPlaceIDs))
1023                                                         {
1024                                                                 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1025                                                                 if (sizeof($aExcludePlaceIDs))
1026                                                                 {
1027                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1028                                                                 }
1029                                                                 //$sSQL .= " limit $iLimit";
1030                                                                 if (CONST_Debug) var_dump($sSQL);
1031                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
1032                                                         }
1033
1034                                                         if (!sizeof($aPlaceIDs))
1035                                                         {
1036                                                                 $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1037                                                                 if (sizeof($aExcludePlaceIDs))
1038                                                                 {
1039                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1040                                                                 }
1041                                                                 //$sSQL .= " limit $iLimit";
1042                                                                 if (CONST_Debug) var_dump($sSQL);
1043                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
1044                                                         }
1045
1046                                                         // Fallback to the road
1047                                                         if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1048                                                         {
1049                                                                 $aPlaceIDs = $aRoadPlaceIDs;
1050                                                         }
1051
1052                                                 }
1053
1054                                                 if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1055                                                 {
1056                                                         $sPlaceIDs = join(',',$aPlaceIDs);
1057                                                         $aClassPlaceIDs = array();
1058
1059                                                         if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1060                                                         {
1061                                                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1062                                                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1063                                                                 $sSQL .= " and linked_place_id is null";
1064                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1065                                                                 $sSQL .= " order by rank_search asc limit $iLimit";
1066                                                                 if (CONST_Debug) var_dump($sSQL);
1067                                                                 $aClassPlaceIDs = $oDB->getCol($sSQL);
1068                                                         }
1069
1070                                                         if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1071                                                         {
1072                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1073                                                                 $bCacheTable = $oDB->getOne($sSQL);
1074
1075                                                                 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1076
1077                                                                 if (CONST_Debug) var_dump($sSQL);
1078                                                                 $iMaxRank = ((int)$oDB->getOne($sSQL));
1079
1080                                                                 // For state / country level searches the normal radius search doesn't work very well
1081                                                                 $sPlaceGeom = false;
1082                                                                 if ($iMaxRank < 9 && $bCacheTable)
1083                                                                 {
1084                                                                         // Try and get a polygon to search in instead
1085                                                                         $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";
1086                                                                         if (CONST_Debug) var_dump($sSQL);
1087                                                                         $sPlaceGeom = $oDB->getOne($sSQL);
1088                                                                 }
1089
1090                                                                 if ($sPlaceGeom)
1091                                                                 {
1092                                                                         $sPlaceIDs = false;
1093                                                                 }
1094                                                                 else
1095                                                                 {
1096                                                                         $iMaxRank += 5;
1097                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1098                                                                         if (CONST_Debug) var_dump($sSQL);
1099                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
1100                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
1101                                                                 }
1102
1103                                                                 if ($sPlaceIDs || $sPlaceGeom)
1104                                                                 {
1105
1106                                                                         $fRange = 0.01;
1107                                                                         if ($bCacheTable)
1108                                                                         {
1109                                                                                 // More efficient - can make the range bigger
1110                                                                                 $fRange = 0.05;
1111
1112                                                                                 $sOrderBySQL = '';
1113                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1114                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1115                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1116
1117                                                                                 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1118                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1119                                                                                 if ($sPlaceIDs)
1120                                                                                 {
1121                                                                                         $sSQL .= ",placex as f where ";
1122                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1123                                                                                 }
1124                                                                                 if ($sPlaceGeom)
1125                                                                                 {
1126                                                                                         $sSQL .= " where ";
1127                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1128                                                                                 }
1129                                                                                 if (sizeof($aExcludePlaceIDs))
1130                                                                                 {
1131                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1132                                                                                 }
1133                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1134                                                                                 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1135                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
1136                                                                                 $sSQL .= " limit $iLimit";
1137                                                                                 if (CONST_Debug) var_dump($sSQL);
1138                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1139                                                                         }
1140                                                                         else
1141                                                                         {
1142                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1143
1144                                                                                 $sOrderBySQL = '';
1145                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1146                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1147
1148                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1149                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1150                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1151                                                                                 if (sizeof($aExcludePlaceIDs))
1152                                                                                 {
1153                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1154                                                                                 }
1155                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1156                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1157                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
1158                                                                                 $sSQL .= " limit $iLimit";
1159                                                                                 if (CONST_Debug) var_dump($sSQL);
1160                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1161                                                                         }
1162                                                                 }
1163                                                         }
1164
1165                                                         $aPlaceIDs = $aClassPlaceIDs;
1166
1167                                                 }
1168
1169                                         }
1170
1171                                         if (PEAR::IsError($aPlaceIDs))
1172                                         {
1173                                                 failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1174                                         }
1175
1176                                         if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1177
1178                                         foreach($aPlaceIDs as $iPlaceID)
1179                                         {
1180                                                 $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1181                                         }
1182                                         if ($iQueryLoop > 20) break;
1183                                 }
1184
1185                                 //exit;
1186                                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1187                                 if ($iGroupLoop > 4) break;
1188                                 if ($iQueryLoop > 30) break;
1189                         }
1190
1191                         // Did we find anything?
1192                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1193                         {
1194                                 //var_Dump($aResultPlaceIDs);exit;
1195                                 // Get the details for display (is this a redundant extra step?)
1196                                 $sPlaceIDs = join(',',$aResultPlaceIDs);
1197                                 $sOrderSQL = 'CASE ';
1198                                 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1199                                 {
1200                                         $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1201                                 }
1202                                 $sOrderSQL .= ' ELSE 10000000 END';
1203                                 $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,";
1204                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1205                                 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1206                                 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1207                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1208                                 //$sSQL .= $sOrderSQL." as porder, ";
1209                                 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1210                                 $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, ";
1211                                 $sSQL .= "(extratags->'place') as extra_place ";
1212                                 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1213                                 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1214                                 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1215                                 $sSQL .= ") ";
1216                                 if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1217                                 $sSQL .= "and linked_place_id is null ";
1218                                 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1219                                 if (!$bDeDupe) $sSQL .= ",place_id";
1220                                 $sSQL .= ",langaddress ";
1221                                 $sSQL .= ",placename ";
1222                                 $sSQL .= ",ref ";
1223                                 $sSQL .= ",extratags->'place' ";
1224                                 $sSQL .= " union ";
1225                                 $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,";
1226                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1227                                 $sSQL .= "null as placename,";
1228                                 $sSQL .= "null as ref,";
1229                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1230                                 //$sSQL .= $sOrderSQL." as porder, ";
1231                                 $sSQL .= "-0.15 as importance, ";
1232                                 $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, ";
1233                                 $sSQL .= "null as extra_place ";
1234                                 $sSQL .= "from location_property_tiger 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 .= " union ";
1239                                 $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,";
1240                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1241                                 $sSQL .= "null as placename,";
1242                                 $sSQL .= "null as ref,";
1243                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1244                                 //$sSQL .= $sOrderSQL." as porder, ";
1245                                 $sSQL .= "-0.10 as importance, ";
1246                                 $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, ";
1247                                 $sSQL .= "null as extra_place ";
1248                                 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1249                                 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1250                                 $sSQL .= "group by place_id";
1251                                 if (!$bDeDupe) $sSQL .= ",place_id";
1252                                 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1253                                 $sSQL .= "order by importance desc";
1254                                 //$sSQL .= "order by rank_search,rank_address,porder asc";
1255                                 if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1256                                 $aSearchResults = $oDB->getAll($sSQL);
1257                                 //var_dump($sSQL,$aSearchResults);exit;
1258
1259                                 if (PEAR::IsError($aSearchResults))
1260                                 {
1261                                         failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1262                                 }
1263                         }
1264                 } // end if ($sQuery)
1265                 else
1266                 {
1267                         if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1268                         {
1269                                 $iPlaceID = geocodeReverse((float)$_GET['nearlat'], (float)$_GET['nearlon']);
1270
1271                                 if ($iPlaceID)
1272                                 {
1273                                         $aResultPlaceIDs = array($iPlaceID);
1274                                         // TODO: this needs refactoring!
1275
1276                                         // Get the details for display (is this a redundant extra step?)
1277                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1278                                         $sOrderSQL = 'CASE ';
1279                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1280                                         {
1281                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1282                                         }
1283                                         $sOrderSQL .= ' ELSE 10000000 END';
1284                                         $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,";
1285                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1286                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1287                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1288                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1289                                         //$sSQL .= $sOrderSQL." as porder, ";
1290                                         $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1291                                         $sSQL .= "(extratags->'place') as extra_place ";
1292                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1293                                         $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1294                                         if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1295                                         $sSQL .= ") ";
1296                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1297                                         if (!$bDeDupe) $sSQL .= ",place_id";
1298                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1299                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1300                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1301                                         $sSQL .= ",extratags->'place' ";
1302                                         $sSQL .= " union ";
1303                                         $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,";
1304                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1305                                         $sSQL .= "null as placename,";
1306                                         $sSQL .= "null as ref,";
1307                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1308                                         //$sSQL .= $sOrderSQL." as porder, ";
1309                                         $sSQL .= "-0.15 as importance, ";
1310                                         $sSQL .= "null as extra_place ";
1311                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1312                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1313                                         $sSQL .= "group by place_id";
1314                                         if (!$bDeDupe) $sSQL .= ",place_id";
1315                                         $sSQL .= " union ";
1316                                         $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,";
1317                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1318                                         $sSQL .= "null as placename,";
1319                                         $sSQL .= "null as ref,";
1320                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1321                                         //$sSQL .= $sOrderSQL." as porder, ";
1322                                         $sSQL .= "-0.10 as importance, ";
1323                                         $sSQL .= "null as extra_place ";
1324                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1325                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1326                                         $sSQL .= "group by place_id";
1327                                         if (!$bDeDupe) $sSQL .= ",place_id";
1328                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1329                                         $sSQL .= "order by importance desc";
1330                                         //$sSQL .= "order by rank_search,rank_address,porder asc";
1331                                         if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1332                                         $aSearchResults = $oDB->getAll($sSQL);
1333                                         //var_dump($sSQL,$aSearchResults);exit;
1334
1335                                         if (PEAR::IsError($aSearchResults))
1336                                         {
1337                                                 failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1338                                         }
1339                                 }
1340                                 else
1341                                 {
1342                                         $aSearchResults = array();
1343                                 }
1344                         }
1345                 }
1346         }
1347
1348         $sSearchResult = '';
1349         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1350         {
1351                 $sSearchResult = 'No Results Found';
1352         }
1353         //var_Dump($aSearchResults);
1354         //exit;
1355         $aClassType = getClassTypesWithImportance();
1356         $aRecheckWords = preg_split('/\b/u',$sQuery);
1357         foreach($aRecheckWords as $i => $sWord)
1358         {
1359                 if (!$sWord) unset($aRecheckWords[$i]);
1360         }
1361         foreach($aSearchResults as $iResNum => $aResult)
1362         {
1363                 if (CONST_Search_AreaPolygons)
1364                 {
1365                         // Get the bounding box and outline polygon
1366                         $sSQL = "select place_id,numfeatures,area,outline,";
1367                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1368                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1369                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1370
1371                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1372                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1373                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1374                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1375                         if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1376                         if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1377                         if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1378                         if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1379                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1380                         $aPointPolygon = $oDB->getRow($sSQL);
1381                         if (PEAR::IsError($aPointPolygon))
1382                         {
1383                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1384                         }
1385                         if ($aPointPolygon['place_id'])
1386                         {
1387                                 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1388                                 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1389                                 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1390                                 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1391
1392                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1393                                 {
1394                                         $aResult['lat'] = $aPointPolygon['centrelat'];
1395                                         $aResult['lon'] = $aPointPolygon['centrelon'];
1396                                 }
1397                                 if ($bShowPolygons)
1398                                 {
1399                                         // Translate geometary string to point array
1400                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1401                                         {
1402                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1403                                         }
1404                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1405                                         {
1406                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1407                                         }
1408                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1409                                         {
1410                                                 $fRadius = 0.01;
1411                                                 $iSteps = ($fRadius * 40000)^2;
1412                                                 $fStepSize = (2*pi())/$iSteps;
1413                                                 $aPolyPoints = array();
1414                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1415                                                 {
1416                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1417                                                 }
1418                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1419                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1420                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1421                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1422                                         }
1423                                 }
1424
1425                                 // Output data suitable for display (points and a bounding box)
1426                                 if ($bShowPolygons && isset($aPolyPoints))
1427                                 {
1428                                         $aResult['aPolyPoints'] = array();
1429                                         foreach($aPolyPoints as $aPoint)
1430                                         {
1431                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1432                                         }
1433                                 }
1434                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1435                         }
1436                 }
1437
1438                 if ($aResult['extra_place'] == 'city')
1439                 {
1440                         $aResult['class'] = 'place';
1441                         $aResult['type'] = 'city';
1442                         $aResult['rank_search'] = 16;
1443                 }
1444
1445                 if (!isset($aResult['aBoundingBox']))
1446                 {
1447                         // Default
1448                         $fDiameter = 0.0001;
1449
1450                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1451                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1452                         {
1453                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1454                         }
1455                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1456                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1457                         {
1458                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1459                         }
1460                         $fRadius = $fDiameter / 2;
1461
1462                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1463                         $fStepSize = (2*pi())/$iSteps;
1464                         $aPolyPoints = array();
1465                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1466                         {
1467                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1468                         }
1469                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1470                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1471                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1472                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1473
1474                         // Output data suitable for display (points and a bounding box)
1475                         if ($bShowPolygons)
1476                         {
1477                                 $aResult['aPolyPoints'] = array();
1478                                 foreach($aPolyPoints as $aPoint)
1479                                 {
1480                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1481                                 }
1482                         }
1483                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1484                 }
1485
1486                 // Is there an icon set for this type of result?
1487                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1488                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1489                 {
1490                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1491                 }
1492
1493                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1494                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1495                 {
1496                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1497                 }
1498
1499                 if ($bShowAddressDetails)
1500                 {
1501                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1502                         if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1503                         {
1504                                 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1505                         }
1506
1507                         //var_dump($aResult['address']);
1508                         //exit;
1509                 }
1510
1511                 // Adjust importance for the number of exact string matches in the result
1512                 $aResult['importance'] = max(0.001,$aResult['importance']);
1513                 $iCountWords = 0;
1514                 $sAddress = $aResult['langaddress'];
1515                 foreach($aRecheckWords as $i => $sWord)
1516                 {
1517                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1518                 }
1519
1520                 $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
1521
1522                 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1523                 /*
1524                    if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1525                    && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1526                    {
1527                    $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1528                    }
1529                    elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1530                    && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1531                    {
1532                    $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1533                    }
1534                    else
1535                    {
1536                    $aResult['importance'] = 1000000000000000;
1537                    }
1538                  */
1539                 $aResult['name'] = $aResult['langaddress'];
1540                 $aResult['foundorder'] = -$aResult['addressimportance'];
1541                 $aSearchResults[$iResNum] = $aResult;
1542         }
1543         uasort($aSearchResults, 'byImportance');
1544
1545         $aOSMIDDone = array();
1546         $aClassTypeNameDone = array();
1547         $aToFilter = $aSearchResults;
1548         $aSearchResults = array();
1549
1550         $bFirst = true;
1551         foreach($aToFilter as $iResNum => $aResult)
1552         {
1553                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1554                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1555                 if ($bFirst)
1556                 {
1557                         $fLat = $aResult['lat'];
1558                         $fLon = $aResult['lon'];
1559                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1560                         $bFirst = false;
1561                 }
1562                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1563                                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1564                 {
1565                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1566                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1567                         $aSearchResults[] = $aResult;
1568                 }
1569
1570                 // Absolute limit on number of results
1571                 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1572         }
1573
1574         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1575
1576         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1577         {
1578                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1579         }
1580
1581         if ($sQuery)
1582         {
1583                 logEnd($oDB, $hLog, sizeof($aToFilter));
1584         }
1585         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1586         if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1587         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1588         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1589         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1590         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1591         if ($sSuggestion)
1592         {
1593                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1594         }
1595         $sMoreURL .= '&q='.urlencode($sQuery);
1596
1597         if (CONST_Debug) exit;
1598
1599         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');