]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
Merge remote-tracking branch 'upstream/master'
[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         if (isset($aLangPrefOrder['name:pl'])) $bReverseInPlan = true;
82
83         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
84
85         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
86         {
87                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
88                 {
89                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
90                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
91                 }
92         }
93
94         // Only certain ranks of feature
95         if (isset($_GET['featureType']) && !isset($_GET['featuretype'])) $_GET['featuretype'] = $_GET['featureType'];
96
97         if (isset($_GET['featuretype']))
98         {
99                 switch($_GET['featuretype'])
100                 {
101                 case 'country':
102                         $iMinAddressRank = $iMaxAddressRank = 4;
103                         break;
104                 case 'state':
105                         $iMinAddressRank = $iMaxAddressRank = 8;
106                         break;
107                 case 'city':
108                         $iMinAddressRank = 14;
109                         $iMaxAddressRank = 16;
110                         break;
111                 case 'settlement':
112                         $iMinAddressRank = 8;
113                         $iMaxAddressRank = 20;
114                         break;
115                 }
116         }
117
118         if (isset($_GET['countrycodes']))
119         {
120                 $aCountryCodes = array();
121                 foreach(explode(',',$_GET['countrycodes']) as $sCountryCode)
122                 {
123                         if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode))
124                         {
125                                 $aCountryCodes[] = "'".strtolower($sCountryCode)."'";
126                         }
127                 }
128                 $sCountryCodesSQL = join(',', $aCountryCodes);
129         }
130
131         // Search query
132         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
133         if (!$sQuery && isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'][0] == '/')
134         {
135                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
136
137                 // reverse order of '/' separated string
138                 $aPhrases = explode('/', $sQuery);
139                 $aPhrases = array_reverse($aPhrases);
140                 $sQuery = join(', ',$aPhrases);
141         }
142
143         function structuredAddressElement(&$aStructuredQuery, &$iMinAddressRank, &$iMaxAddressRank, $aParams, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank)
144         {
145                 if (!isset($_GET[$sKey])) return false;
146                 $sValue = trim($_GET[$sKey]);
147                 if (!$sValue) return false;
148                 $aStructuredQuery[$sKey] = $sValue;
149                 if ($iMinAddressRank == 0 && $iMaxAddressRank == 30)
150                 {
151                         $iMinAddressRank = $iNewMinAddressRank;
152                         $iMaxAddressRank = $iNewMaxAddressRank;
153                 }
154                 return true;
155         }
156
157         // Structured query?
158         $aStructuredOptions = array(
159                                 array('amenity', 26, 30),
160                                 array('street', 26, 30),
161                                 array('city', 14, 24),
162                                 array('county', 9, 13),
163                                 array('state', 8, 8),
164                                 array('country', 4, 4),
165                                 array('postalcode', 5, 11),
166                                 );
167         $aStructuredQuery = array();
168         $sAllowedTypesSQLList = '';
169         foreach($aStructuredOptions as $aStructuredOption)
170         {
171                 loadStructuredAddressElement($aStructuredQuery, $iMinAddressRank, $iMaxAddressRank, $_GET, $aStructuredOption[0], $aStructuredOption[1], $aStructuredOption[2]);
172         }
173         if (sizeof($aStructuredQuery) > 0) 
174         {
175                 $sQuery = join(', ', $aStructuredQuery);
176                 if ($iMaxAddressRank < 30)
177                 {
178                         $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
179                 }
180         }
181
182         if ($sQuery)
183         {
184                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
185
186                 // Hack to make it handle "new york, ny" (and variants) correctly
187                 $sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $sQuery);
188                 if (isset($aLangPrefOrder['name:en']))
189                 {
190                         $sQuery = preg_replace('/,\s*il\s*(,|$)/',', illinois\1', $sQuery);
191                         $sQuery = preg_replace('/,\s*al\s*(,|$)/',', alabama\1', $sQuery);
192                         $sQuery = preg_replace('/,\s*la\s*(,|$)/',', louisiana\1', $sQuery);
193                 }
194
195                 // If we have a view box create the SQL
196                 // Small is the actual view box, Large is double (on each axis) that
197                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
198                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
199                 {
200                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
201                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
202                 }
203                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
204                 {
205                         $aCoOrdinates = explode(',',$_GET['viewbox']);
206                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
207                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
208                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
209                         $aCoOrdinates[0] += $fHeight;
210                         $aCoOrdinates[2] -= $fHeight;
211                         $aCoOrdinates[1] += $fWidth;
212                         $aCoOrdinates[3] -= $fWidth;
213                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
214                 }
215                 else
216                 {
217                         $bBoundingBoxSearch = false;
218                 }
219                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
220                 {
221                         $aPoints = explode(',',$_GET['route']);
222                         if (sizeof($aPoints) % 2 != 0)
223                         {
224                                 userError("Uneven number of points");
225                                 exit;
226                         }
227                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
228                         $fPrevCoord = false;
229                         foreach($aPoints as $i => $fPoint)
230                         {
231                                 if ($i%2)
232                                 {
233                                         if ($i != 1) $sViewboxCentreSQL .= ",";
234                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
235                                 }
236                                 else
237                                 {
238                                         $fPrevCoord = (float)$fPoint;
239                                 }
240                         }
241                         $sViewboxCentreSQL .= ")'::geometry,4326)";
242
243                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
244                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
245                         if (PEAR::isError($sViewboxSmallSQL))
246                         {
247                                 failInternalError("Could not get small viewbox.", $sSQL, $sViewboxSmallSQL);
248                         }
249                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
250
251                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
252                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
253                         if (PEAR::isError($sViewboxLargeSQL))
254                         {
255                                 failInternalError("Could not get large viewbox.", $sSQL, $sViewboxLargeSQL);
256                         }
257                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
258                         $bBoundingBoxSearch = true;
259                 }
260
261                 // Do we have anything that looks like a lat/lon pair?
262                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
263                 {
264                         $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
265                         $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
266                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
267                         {
268                                 $_GET['nearlat'] = $fQueryLat;
269                                 $_GET['nearlon'] = $fQueryLon;
270                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
271                         }
272                 }
273                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
274                 {
275                         $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
276                         $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
277                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
278                         {
279                                 $_GET['nearlat'] = $fQueryLat;
280                                 $_GET['nearlon'] = $fQueryLon;
281                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
282                         }
283                 }
284                 elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|$|\\b)/', $sQuery, $aData))
285                 {
286                         $fQueryLat = $aData[2];
287                         $fQueryLon = $aData[3];
288                         if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
289                         {
290                                 $_GET['nearlat'] = $fQueryLat;
291                                 $_GET['nearlon'] = $fQueryLon;
292                                 $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
293                         }
294                 }
295
296                 if ($sQuery || $aStructuredQuery)
297                 {
298                         // Start with a blank search
299                         $aSearches = array(
300                                 array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
301                                       'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
302                                       'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
303                         );
304
305                         $sNearPointSQL = false;
306                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
307                         {
308                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
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']);
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 in (26,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($_GET['nearlat'], $_GET['nearlon']);
1270                                 $aResultPlaceIDs = array($iPlaceID);
1271
1272                                 // TODO: this needs refactoring!
1273
1274                                 // Get the details for display (is this a redundant extra step?)
1275                                 $sPlaceIDs = join(',',$aResultPlaceIDs);
1276                                 $sOrderSQL = 'CASE ';
1277                                 foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1278                                 {
1279                                         $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1280                                 }
1281                                 $sOrderSQL .= ' ELSE 10000000 END';
1282                                 $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,";
1283                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1284                                 $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1285                                 $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1286                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1287                                 //$sSQL .= $sOrderSQL." as porder, ";
1288                                 $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
1289                                 $sSQL .= "(extratags->'place') as extra_place ";
1290                                 $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1291                                 $sSQL .= "and (placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1292                                 if (14 >= $iMinAddressRank && 14 <= $iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1293                                 $sSQL .= ") ";
1294                                 $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1295                                 if (!$bDeDupe) $sSQL .= ",place_id";
1296                                 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1297                                 $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1298                                 $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1299                                 $sSQL .= ",extratags->'place' ";
1300                                 $sSQL .= " union ";
1301                                 $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,";
1302                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1303                                 $sSQL .= "null as placename,";
1304                                 $sSQL .= "null as ref,";
1305                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1306                                 //$sSQL .= $sOrderSQL." as porder, ";
1307                                 $sSQL .= "-0.15 as importance, ";
1308                                 $sSQL .= "null as extra_place ";
1309                                 $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1310                                 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1311                                 $sSQL .= "group by place_id";
1312                                 if (!$bDeDupe) $sSQL .= ",place_id";
1313                                 $sSQL .= " union ";
1314                                 $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,";
1315                                 $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1316                                 $sSQL .= "null as placename,";
1317                                 $sSQL .= "null as ref,";
1318                                 $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1319                                 //$sSQL .= $sOrderSQL." as porder, ";
1320                                 $sSQL .= "-0.10 as importance, ";
1321                                 $sSQL .= "null as extra_place ";
1322                                 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1323                                 $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1324                                 $sSQL .= "group by place_id";
1325                                 if (!$bDeDupe) $sSQL .= ",place_id";
1326                                 $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1327                                 $sSQL .= "order by importance desc";
1328                                 //$sSQL .= "order by rank_search,rank_address,porder asc";
1329                                 if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1330                                 $aSearchResults = $oDB->getAll($sSQL);
1331                                 //var_dump($sSQL,$aSearchResults);exit;
1332
1333                                 if (PEAR::IsError($aSearchResults))
1334                                 {
1335                                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1336                                 }
1337                         }
1338                 }
1339         }
1340
1341         $sSearchResult = '';
1342         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1343         {
1344                 $sSearchResult = 'No Results Found';
1345         }
1346         //var_Dump($aSearchResults);
1347         //exit;
1348         $aClassType = getClassTypesWithImportance();
1349         $aRecheckWords = preg_split('/\b/u',$sQuery);
1350         foreach($aRecheckWords as $i => $sWord)
1351         {
1352                 if (!$sWord) unset($aRecheckWords[$i]);
1353         }
1354         foreach($aSearchResults as $iResNum => $aResult)
1355         {
1356                 if (CONST_Search_AreaPolygons)
1357                 {
1358                         // Get the bounding box and outline polygon
1359                         $sSQL = "select place_id,numfeatures,area,outline,";
1360                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1361                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1362                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1363
1364                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1365                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1366                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1367                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1368                         if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1369                         if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1370                         if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1371                         if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1372                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1373                         $aPointPolygon = $oDB->getRow($sSQL);
1374                         if (PEAR::IsError($aPointPolygon))
1375                         {
1376                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1377                         }
1378                         if ($aPointPolygon['place_id'])
1379                         {
1380                                 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1381                                 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1382                                 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1383                                 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1384
1385                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1386                                 {
1387                                         $aResult['lat'] = $aPointPolygon['centrelat'];
1388                                         $aResult['lon'] = $aPointPolygon['centrelon'];
1389                                 }
1390                                 if ($bShowPolygons)
1391                                 {
1392                                         // Translate geometary string to point array
1393                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1394                                         {
1395                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1396                                         }
1397                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1398                                         {
1399                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1400                                         }
1401                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1402                                         {
1403                                                 $fRadius = 0.01;
1404                                                 $iSteps = ($fRadius * 40000)^2;
1405                                                 $fStepSize = (2*pi())/$iSteps;
1406                                                 $aPolyPoints = array();
1407                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1408                                                 {
1409                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1410                                                 }
1411                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1412                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1413                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1414                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1415                                         }
1416                                 }
1417
1418                                 // Output data suitable for display (points and a bounding box)
1419                                 if ($bShowPolygons && isset($aPolyPoints))
1420                                 {
1421                                         $aResult['aPolyPoints'] = array();
1422                                         foreach($aPolyPoints as $aPoint)
1423                                         {
1424                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1425                                         }
1426                                 }
1427                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1428                         }
1429                 }
1430
1431                 if ($aResult['extra_place'] == 'city')
1432                 {
1433                         $aResult['class'] = 'place';
1434                         $aResult['type'] = 'city';
1435                         $aResult['rank_search'] = 16;
1436                 }
1437
1438                 if (!isset($aResult['aBoundingBox']))
1439                 {
1440                         // Default
1441                         $fDiameter = 0.0001;
1442
1443                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1444                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1445                         {
1446                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1447                         }
1448                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1449                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1450                         {
1451                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1452                         }
1453                         $fRadius = $fDiameter / 2;
1454
1455                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1456                         $fStepSize = (2*pi())/$iSteps;
1457                         $aPolyPoints = array();
1458                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1459                         {
1460                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1461                         }
1462                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1463                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1464                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1465                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1466
1467                         // Output data suitable for display (points and a bounding box)
1468                         if ($bShowPolygons)
1469                         {
1470                                 $aResult['aPolyPoints'] = array();
1471                                 foreach($aPolyPoints as $aPoint)
1472                                 {
1473                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1474                                 }
1475                         }
1476                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1477                 }
1478
1479                 // Is there an icon set for this type of result?
1480                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1481                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1482                 {
1483                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1484                 }
1485
1486                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1487                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1488                 {
1489                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1490                 }
1491
1492                 if ($bShowAddressDetails)
1493                 {
1494                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1495                         if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1496                         {
1497                                 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1498                         }
1499
1500                         //var_dump($aResult['address']);
1501                         //exit;
1502                 }
1503
1504                 // Adjust importance for the number of exact string matches in the result
1505                 $aResult['importance'] = max(0.001,$aResult['importance']);
1506                 $iCountWords = 0;
1507                 $sAddress = $aResult['langaddress'];
1508                 foreach($aRecheckWords as $i => $sWord)
1509                 {
1510                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1511                 }
1512
1513                 $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
1514
1515                 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1516                 /*
1517                    if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1518                    && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1519                    {
1520                    $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1521                    }
1522                    elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1523                    && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1524                    {
1525                    $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1526                    }
1527                    else
1528                    {
1529                    $aResult['importance'] = 1000000000000000;
1530                    }
1531                  */
1532                 $aResult['name'] = $aResult['langaddress'];
1533                 $aResult['foundorder'] = -$aResult['addressimportance'];
1534                 $aSearchResults[$iResNum] = $aResult;
1535         }
1536         uasort($aSearchResults, 'byImportance');
1537
1538         $aOSMIDDone = array();
1539         $aClassTypeNameDone = array();
1540         $aToFilter = $aSearchResults;
1541         $aSearchResults = array();
1542
1543         $bFirst = true;
1544         foreach($aToFilter as $iResNum => $aResult)
1545         {
1546                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1547                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1548                 if ($bFirst)
1549                 {
1550                         $fLat = $aResult['lat'];
1551                         $fLon = $aResult['lon'];
1552                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1553                         $bFirst = false;
1554                 }
1555                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1556                                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1557                 {
1558                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1559                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1560                         $aSearchResults[] = $aResult;
1561                 }
1562
1563                 // Absolute limit on number of results
1564                 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1565         }
1566
1567         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '2 minutes'::interval,'YYYY/MM/DD HH24:MI')||' GMT' from import_status limit 1");
1568
1569         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1570         {
1571                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1572         }
1573
1574         if ($sQuery)
1575         {
1576                 logEnd($oDB, $hLog, sizeof($aToFilter));
1577         }
1578         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1579         if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1580         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1581         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1582         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1583         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1584         if ($sSuggestion)
1585         {
1586                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1587         }
1588         $sMoreURL .= '&q='.urlencode($sQuery);
1589
1590         if (CONST_Debug) exit;
1591
1592         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');