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