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