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