]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
more partitioning work, os open data postcodes, country list fixes
[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         $sSuggestion = $sSuggestionURL = false;
17         $bDeDupe = isset($_GET['dedupe'])?(bool)$_GET['dedupe']:true;
18         $bReverseInPlan = false;
19         $iLimit = isset($_GET['limit'])?(int)$_GET['limit']:10;
20         $iMaxRank = 20;
21         if ($iLimit > 100) $iLimit = 100;
22
23         // Format for output
24         if (isset($_GET['format']) && ($_GET['format'] == 'html' || $_GET['format'] == 'xml' || $_GET['format'] == 'json' ||  $_GET['format'] == 'jsonv2'))
25         {
26                 $sOutputFormat = $_GET['format'];
27         }
28
29         // Show / use polygons
30         $bShowPolygons = isset($_GET['polygon']) && $_GET['polygon'];
31
32         // Show address breakdown
33         $bShowAddressDetails = isset($_GET['addressdetails']) && $_GET['addressdetails'];
34
35         // Prefered language    
36         $aLangPrefOrder = getPrefferedLangauges();
37         if (isset($aLangPrefOrder['name:de'])) $bReverseInPlan = true;
38         $sLanguagePrefArraySQL = "ARRAY[".join(',',array_map("getDBQuoted",$aLangPrefOrder))."]";
39
40         if (isset($_GET['exclude_place_ids']) && $_GET['exclude_place_ids'])
41         {
42                 foreach(explode(',',$_GET['exclude_place_ids']) as $iExcludedPlaceID)
43                 {
44                         $iExcludedPlaceID = (int)$iExcludedPlaceID;
45                         if ($iExcludedPlaceID) $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
46                 }
47         }
48                 
49         // Search query
50         $sQuery = (isset($_GET['q'])?trim($_GET['q']):'');
51         if (!$sQuery && $_SERVER['PATH_INFO'] && $_SERVER['PATH_INFO'][0] == '/')
52         {
53                 $sQuery = substr($_SERVER['PATH_INFO'], 1);
54
55                 // reverse order of '/' seperated string
56                 $aPhrases = explode('/', $sQuery);              
57                 $aPhrases = array_reverse($aPhrases); 
58                 $sQuery = join(', ',$aPhrases);
59         }
60
61         if ($sQuery)
62         {
63                 $hLog = logStart($oDB, 'search', $sQuery, $aLangPrefOrder);
64
65                 // If we have a view box create the SQL
66                 // Small is the actual view box, Large is double (on each axis) that 
67                 $sViewboxCentreSQL = $sViewboxSmallSQL = $sViewboxLargeSQL = false;
68                 if (isset($_GET['viewboxlbrt']) && $_GET['viewboxlbrt'])
69                 {
70                         $aCoOrdinatesLBRT = explode(',',$_GET['viewboxlbrt']);
71                         $_GET['viewbox'] = $aCoOrdinatesLBRT[0].','.$aCoOrdinatesLBRT[3].','.$aCoOrdinatesLBRT[2].','.$aCoOrdinatesLBRT[1];
72                 }
73                 if (isset($_GET['viewbox']) && $_GET['viewbox'])
74                 {
75                         $aCoOrdinates = explode(',',$_GET['viewbox']);
76                         $sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
77                         $fHeight = $aCoOrdinates[0]-$aCoOrdinates[2];
78                         $fWidth = $aCoOrdinates[1]-$aCoOrdinates[3];
79                         $aCoOrdinates[0] += $fHeight;
80                         $aCoOrdinates[2] -= $fHeight;
81                         $aCoOrdinates[1] += $fWidth;
82                         $aCoOrdinates[3] -= $fWidth;
83                         $sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aCoOrdinates[0].",".(float)$aCoOrdinates[1]."),ST_Point(".(float)$aCoOrdinates[2].",".(float)$aCoOrdinates[3].")),4326)";
84                 }
85                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
86                 {
87                         $aPoints = explode(',',$_GET['route']);
88                         if (sizeof($aPoints) % 2 != 0)
89                         {
90                                 echo "Uneven number of points";
91                                 exit;
92                         }
93                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
94                         $fPrevCoord = false;
95                         foreach($aPoints as $i => $fPoint)
96                         {
97                                 if ($i%2)
98                                 {
99                                         if ($i != 1) $sViewboxCentreSQL .= ",";
100                                         $sViewboxCentreSQL .= ((float)$fPoint).' '.$fPrevCoord;
101                                 }
102                                 else
103                                 {
104                                         $fPrevCoord = (float)$fPoint;
105                                 }
106                         }
107                         $sViewboxCentreSQL .= ")'::geometry,4326)";
108
109                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
110                         $sViewboxSmallSQL = $oDB->getOne($sSQL);
111                         if (PEAR::isError($sViewboxSmallSQL))
112                         {
113                                 var_dump($sViewboxSmallSQL);
114                                 exit;
115                         }
116                         $sViewboxSmallSQL = "'".$sViewboxSmallSQL."'::geometry";
117
118                         $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
119                         $sViewboxLargeSQL = $oDB->getOne($sSQL);
120                         if (PEAR::isError($sViewboxLargeSQL))
121                         {
122                                 var_dump($sViewboxLargeSQL);
123                                 exit;
124                         }
125                         $sViewboxLargeSQL = "'".$sViewboxLargeSQL."'::geometry";
126                 }
127
128                 // Do we have anything that looks like a lat/lon pair?
129                 if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
130                 {
131                         $_GET['nearlat'] = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
132                         $_GET['nearlon'] = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
133                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
134                 }
135                 elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
136                 {
137                         $_GET['nearlat'] = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
138                         $_GET['nearlon'] = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
139                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
140                 }
141                 elseif (preg_match('/(\\[|\\b)(-?[0-9]+[0-9.]*)[, ]+(-?[0-9]+[0-9.]*)(\\]|\\b])/', $sQuery, $aData))
142                 {
143                         $_GET['nearlat'] = $aData[2];
144                         $_GET['nearlon'] = $aData[3];
145                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
146                 }
147
148                 if ($sQuery)
149                 {
150
151                         // Start with a blank search
152                         $aSearches = array(
153                                 array('iSearchRank' => 0, 'iNamePhrase' => 0, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 
154                                         'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
155                         );
156
157                         $sNearPointSQL = false;
158                         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
159                         {
160                                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$_GET['nearlon'].",".$_GET['nearlat']."),4326)";
161                                 $aSearches[0]['fLat'] = (float)$_GET['nearlat'];
162                                 $aSearches[0]['fLon'] = (float)$_GET['nearlon'];
163                                 $aSearches[0]['fRadius'] = 0.1;
164                         }
165
166                         $bSpecialTerms = false;
167                         preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
168                         $aSpecialTerms = array();
169                         foreach($aSpecialTermsRaw as $aSpecialTerm)
170                         {
171                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
172                                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
173                         }
174
175                         preg_match_all('/\\[([a-zA-Z]*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
176                         $aSpecialTerms = array();
177                         foreach($aSpecialTermsRaw as $aSpecialTerm)
178                         {
179                                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
180                                 $sToken = $oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
181                                 $sSQL = 'select * from (select word_id,word_token, word, class, type, location, country_code, operator';
182                                 $sSQL .= ' from word where word_token in (\' '.$sToken.'\')) as x where (class is not null and class != \'place\') or country_code is not null';
183                                 $aSearchWords = $oDB->getAll($sSQL);
184                                 $aNewSearches = array();
185                                 foreach($aSearches as $aSearch)
186                                 {
187                                         foreach($aSearchWords as $aSearchTerm)
188                                         {
189                                                 $aNewSearch = $aSearch;                 
190                                                 if ($aSearchTerm['country_code'])
191                                                 {
192                                                         $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
193                                                         $aNewSearches[] = $aNewSearch;
194                                                         $bSpecialTerms = true;
195                                                 }
196                                                 if ($aSearchTerm['class'])
197                                                 {
198                                                         $aNewSearch['sClass'] = $aSearchTerm['class'];
199                                                         $aNewSearch['sType'] = $aSearchTerm['type'];
200                                                         $aNewSearches[] = $aNewSearch;
201                                                         $bSpecialTerms = true;
202                                                 }
203                                         }
204                                 }
205                                 $aSearches = $aNewSearches;
206                         }
207
208                         // Split query into phrases
209                         // Commas are used to reduce the search space by indicating where phrases split
210                         $aPhrases = explode(',',$sQuery);
211
212                         // Convert each phrase to standard form
213                         // Create a list of standard words
214                         // Get all 'sets' of words
215                         // Generate a complete list of all 
216                         $aTokens = array();
217                         foreach($aPhrases as $iPhrase => $sPhrase)
218                         {
219                                 $aPhrase = $oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
220                                 if (PEAR::isError($aPhrase))
221                                 {
222                                         var_dump($aPhrase);
223                                         exit;
224                                 }
225                                 if (trim($aPhrase['string']))
226                                 {
227                                         $aPhrases[$iPhrase] = $aPhrase;
228                                         $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
229                                         $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words']);
230                                         $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
231                                 }
232                                 else
233                                 {
234                                         unset($aPhrases[$iPhrase]);
235                                 }
236                         }                       
237
238                         // reindex phrases - we make assumptions later on
239                         $aPhrases = array_values($aPhrases);
240
241                         if (sizeof($aTokens))
242                         {
243
244                         // Check which tokens we have, get the ID numbers                       
245                         $sSQL = 'select word_id,word_token, word, class, type, location, country_code, operator';
246                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
247 //                      $sSQL .= ' group by word_token, word, class, type, location,country_code';
248
249                         if (CONST_Debug) var_Dump($sSQL);
250
251                         $aValidTokens = array();
252                         if (sizeof($aTokens))
253                                 $aDatabaseWords = $oDB->getAll($sSQL);
254                         else
255                                 $aDatabaseWords = array();
256                         if (PEAR::IsError($aDatabaseWords))
257                         {
258                                 var_dump($sSQL, $aDatabaseWords);
259                                 exit;
260                         }
261                         foreach($aDatabaseWords as $aToken)
262                         {
263                                 if (isset($aValidTokens[$aToken['word_token']]))
264                                 {
265                                         $aValidTokens[$aToken['word_token']][] = $aToken;
266                                 }
267                                 else
268                                 {
269                                         $aValidTokens[$aToken['word_token']] = array($aToken);
270                                 }
271                         }
272                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
273
274                         $aSuggestion = array();
275                         $bSuggestion = false;
276                         if (CONST_Suggestions_Enabled)
277                         {
278                                 foreach($aPhrases as $iPhrase => $aPhrase)
279                                 {
280                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
281                                         {
282                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
283                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
284                                                 $aRow = $aSuggestionWords[0];
285                                                 if ($aRow && $aRow['word'])
286                                                 {
287                                                         $aSuggestion[] = $aRow['word'];
288                                                         $bSuggestion = true;
289                                                 }
290                                                 else
291                                                 {
292                                                         $aSuggestion[] = $aPhrase['string'];
293                                                 }
294                                         }
295                                         else
296                                         {
297                                                 $aSuggestion[] = $aPhrase['string'];
298                                         }
299                                 }
300                         }
301                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
302
303                         // Try and calculate GB postcodes we might be missing
304                         foreach($aTokens as $sToken)
305                         {
306                                 if (!isset($aValidTokens[$sToken]) && !isset($aValidTokens[' '.$sToken]) && preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
307                                 {
308                                         if (substr($aData[1],-2,1) != ' ')
309                                         {
310                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
311                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
312                                         }
313                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
314                                         if ($aGBPostcodeLocation)
315                                         {
316                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
317                                         }
318                                 }
319                         }
320
321                         // Any words that have failed completely?
322                         // TODO: suggestions
323
324                         // Start the search process
325                         $aResultPlaceIDs = array();
326
327                         /*
328                                 Calculate all searches using aValidTokens i.e.
329
330                                 'Wodsworth Road, Sheffield' =>
331                                         
332                                 Phrase Wordset
333                                 0      0       (wodsworth road)
334                                 0      1       (wodsworth)(road)
335                                 1      0       (sheffield)
336                                 
337                                 Score how good the search is so they can be ordered
338                         */
339
340                                 foreach($aPhrases as $iPhrase => $sPhrase)
341                                 {
342                                         $aNewPhraseSearches = array();
343
344                                         foreach($aPhrases[$iPhrase]['wordsets'] as $iWordset => $aWordset)
345                                         {
346                                                 $aWordsetSearches = $aSearches;
347
348                                                 // Add all words from this wordset
349                                                 foreach($aWordset as $sToken)
350                                                 {
351                                                         $aNewWordsetSearches = array();
352                                                         
353                                                         foreach($aWordsetSearches as $aCurrentSearch)
354                                                         {
355                                                                 // If the token is valid
356                                                                 if (isset($aValidTokens[' '.$sToken]))
357                                                                 {
358                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
359                                                                         {
360                                                                                 $aSearch = $aCurrentSearch;
361                                                                                 $aSearch['iSearchRank']++;
362                                                                                 if ($aSearchTerm['country_code'] !== null && $aSearchTerm['country_code'] != '0')
363                                                                                 {
364                                                                                         if ($aSearch['sCountryCode'] === false)
365                                                                                         {
366                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
367                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (opimisation)
368                                                                                                 if ($iWordset+1 != sizeof($aPhrases[$iPhrase]['wordsets']) || $iPhrase+1 != sizeof($aPhrases)) $aSearch['iSearchRank'] += 5;
369                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
370                                                                                         }
371                                                                                 }
372                                                                                 elseif ($aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
373                                                                                 {
374                                                                                         if ($aSearch['fLat'] === '')
375                                                                                         {
376                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
377                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
378                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
379                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
380                                                                                         }
381                                                                                 }
382                                                                                 elseif ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
383                                                                                 {
384                                                                                         if ($aSearch['sHouseNumber'] === '')
385                                                                                         {
386                                                                                                 $aSearch['sHouseNumber'] = $sToken;
387                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
388
389                                                                                                 // Fall back to not searching for this item (better than nothing)
390                                                                                                 $aSearch = $aCurrentSearch;
391                                                                                                 $aSearch['iSearchRank'] += 2;
392                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
393                                                                                         }
394                                                                                 }
395                                                                                 elseif ($aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
396                                                                                 {
397                                                                                         if ($aSearch['sClass'] === '')
398                                                                                         {
399                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
400                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
401                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
402                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
403                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
404
405                                                                                                 // Do we have a shortcut id?
406                                                                                                 if ($aSearch['sOperator'] == 'name')
407                                                                                                 {
408                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
409                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
410                                                                                                         {
411                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
412                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
413                                                                                                                 $aSearch['sClass'] = '';
414                                                                                                                 $aSearch['sType'] = '';
415                                                                                                         }
416                                                                                                 }
417                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
418                                                                                         }
419                                                                                 }
420                                                                                 else
421                                                                                 {
422                                                                                         if (sizeof($aSearch['aName']))
423                                                                                         {
424                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
425                                                                                         }
426                                                                                         else
427                                                                                         {
428                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
429                                                                                                 $aSearch['iNamePhrase'] = $iPhrase;
430                                                                                         }
431                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
432                                                                                 }
433                                                                         }
434                                                                 }
435                                                                 if (isset($aValidTokens[$sToken]))
436                                                                 {
437                                                                         // Allow searching for a word - but at extra cost
438                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
439                                                                         {
440                                                                                 $aSearch = $aCurrentSearch;
441                                                                                 $aSearch['iSearchRank']+=5;
442                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
443                                                                                 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
444                                                                                 {
445                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
446                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
447                                                                                 }
448                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
449                                                                         }
450                                                                 }
451                                                                 else
452                                                                 {
453                                                                         // Allow skipping a word - but at EXTREAM cost
454                                                                         //$aSearch = $aCurrentSearch;
455                                                                         //$aSearch['iSearchRank']+=100;
456                                                                         //$aNewWordsetSearches[] = $aSearch;
457                                                                 }
458                                                         }
459                                                         // Sort and cut
460                                                         usort($aNewWordsetSearches, 'bySearchRank');
461                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
462                                                 }                                               
463 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
464
465                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
466                                                 usort($aNewPhraseSearches, 'bySearchRank');
467                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
468                                         }
469
470                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
471                                         $aGroupedSearches = array();
472                                         foreach($aNewPhraseSearches as $aSearch)
473                                         {
474                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
475                                                 {
476                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
477                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
478                                                 }
479                                         }
480                                         ksort($aGroupedSearches);
481
482                                         $iSearchCount = 0;
483                                         $aSearches = array();
484                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
485                                         {
486                                                 $iSearchCount += sizeof($aNewSearches);
487                                                 $aSearches = array_merge($aSearches, $aNewSearches);
488                                                 if ($iSearchCount > 50) break;
489                                         }
490                                 }
491                         }
492                         else
493                         {
494                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
495                                         $aGroupedSearches = array();
496                                         foreach($aSearches as $aSearch)
497                                         {
498                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
499                                                 {
500                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
501                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
502                                                 }
503                                         }
504                                         ksort($aGroupedSearches);
505                         }
506                                 
507                                 if (CONST_Debug) var_Dump($aGroupedSearches);
508
509                                 if ($bReverseInPlan)
510                                 {
511                                         foreach($aGroupedSearches as $iGroup => $aSearches)
512                                         {
513                                                 foreach($aSearches as $iSearch => $aSearch)
514                                                 {
515                                                         if (sizeof($aSearch['aAddress']))
516                                                         {
517                                                                 $aReverseSearch = $aSearch;
518                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
519                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
520                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
521                                                         }
522                                                 }
523                                         }
524                                 }
525
526 //var_Dump($aGroupedSearches); exit;
527
528                                 // Filter out duplicate searches
529                                 $aSearchHash = array();
530                                 foreach($aGroupedSearches as $iGroup => $aSearches)
531                                 {
532                                         foreach($aSearches as $iSearch => $aSearch)
533                                         {
534                                                 $sHash = serialize($aSearch);
535                                                 if (isset($aSearchHash[$sHash]))
536                                                 {
537                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
538                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
539                                                 }
540                                                 else
541                                                 {
542                                                         $aSearchHash[$sHash] = 1;
543                                                 }
544                                         }
545                                 }
546                                 
547                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
548
549                                 if ($bReverseInPlan)
550                                 {
551                                         foreach($aGroupedSearches as $iGroup => $aSearches)
552                                         {
553                                                 foreach($aSearches as $iSearch => $aSearch)
554                                                 {
555                                                         if (sizeof($aSearch['aAddress']))
556                                                         {
557                                                                 $aReverseSearch = $aSearch;
558                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
559                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
560                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
561                                                         }
562                                                 }
563                                         }
564                                 }
565
566                                 // Filter out duplicate searches
567                                 $aSearchHash = array();
568                                 foreach($aGroupedSearches as $iGroup => $aSearches)
569                                 {
570                                         foreach($aSearches as $iSearch => $aSearch)
571                                         {
572                                                 $sHash = serialize($aSearch);
573                                                 if (isset($aSearchHash[$sHash]))
574                                                 {
575                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
576                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
577                                                 }
578                                                 else
579                                                 {
580                                                         $aSearchHash[$sHash] = 1;
581                                                 }
582                                         }
583                                 }
584
585                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
586
587                                 $iGroupLoop = 0;
588                                 $iQueryLoop = 0;
589                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
590                                 {
591                                         $iGroupLoop++;
592                                         foreach($aSearches as $aSearch)
593                                         {
594                                                 $iQueryLoop++;
595                                                 // Must have a location term
596                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress'] && !$aSearch['fLon']))
597                                                 {
598                                                         if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
599                                                         if (!$aSearch['sClass']) continue;
600                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
601                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
602
603                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
604                                                         if ($oDB->getOne($sSQL))
605                                                         {
606                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
607                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
608                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
609                                                                 $sSQL .= " limit $iLimit";
610                                                                 if (CONST_Debug) var_dump($sSQL);
611                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
612
613                                                                 if (!sizeof($aPlaceIDs))
614                                                                 {
615                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
616                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
617                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
618                                                                         $sSQL .= " limit $iLimit";
619                                                                         if (CONST_Debug) var_dump($sSQL);
620                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
621                                                                 }
622                                                         }
623                                                         else
624                                                         {
625                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
626                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
627                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
628                                                                 $sSQL .= " limit $iLimit";
629                                                                 if (CONST_Debug) var_dump($sSQL);
630                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
631                                                         }
632                                                 }
633                                                 else
634                                                 {
635                                                         if ($aSearch['aName'] == array(282=>'282')) continue;
636
637                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
638                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
639                                                         $aPlaceIDs = array();
640                                                 
641                                                         // First we need a position, either aName or fLat or both
642                                                         $aTerms = array();
643                                                         $aOrder = array();
644                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
645                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
646                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
647                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
648                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
649                                                         {
650                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
651                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
652                                                         }
653                                                         if (sizeof($aExcludePlaceIDs))
654                                                         {
655                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
656                                                         }
657                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
658                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
659                                                         if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
660                                                         if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
661                                                         $aOrder[] = "search_rank ASC";
662                                                 
663                                                         if (sizeof($aTerms))
664                                                         {
665                                                                 $sSQL = "select place_id";
666                                                                 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
667                                                                 else $sSQL .= ",false as in_small";
668                                                                 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
669                                                                 else $sSQL .= ",false as in_large";
670                                                                 $sSQL .= " from search_name";
671                                                                 $sSQL .= " where ".join(' and ',$aTerms);
672                                                                 $sSQL .= " order by ".join(', ',$aOrder);
673                                                                 if ($aSearch['sHouseNumber'])
674                                                                         $sSQL .= " limit 50";
675                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
676                                                                         $sSQL .= " limit 1";
677                                                                 else
678                                                                         $sSQL .= " limit ".$iLimit;
679
680                                                                 if (CONST_Debug) var_dump($sSQL);
681                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
682                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
683                                                                 {
684                                                                         var_dump($sSQL, $aViewBoxPlaceIDs);                                     
685                                                                         exit;
686                                                                 }
687
688                                                                 // Did we have an viewbox matches?
689                                                                 $aPlaceIDs = array();
690                                                                 $bViewBoxMatch = false;
691                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
692                                                                 {
693                                                                         if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
694                                                                         if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
695                                                                         if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
696                                                                         else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
697                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
698                                                                 }
699                                                         }
700
701                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
702                                                         {
703                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
704         
705                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
706
707                                                                 // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
708                                                                 $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
709                                                                 $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
710                                                                 $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
711                                                                 $sSQL .= " and placex.class='place' and placex.type='house'";
712                                                                 if (CONST_Debug) var_dump($sSQL);
713                                                                 $oDB->query($sSQL);
714                                                         
715                                                                 // Now they are indexed look for a house attached to a street we found
716                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
717                                                                 if (sizeof($aExcludePlaceIDs))
718                                                                 {
719                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
720                                                                 }
721                                                                 $sSQL .= " limit $iLimit";
722                                                                 if (CONST_Debug) var_dump($sSQL);
723                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
724                                                         }
725                                                 
726                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
727                                                         {
728                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
729
730                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
731                                                                 {
732                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
733                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
734                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
735                                                                         if (CONST_Debug) var_dump($sSQL);
736                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
737                                                                 }
738                                                                 
739                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
740                                                                 {
741                                                                         $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
742                                                                         if (CONST_Debug) var_dump($sSQL);
743                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
744
745                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
746                                                                         if (CONST_Debug) var_dump($sSQL);
747                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
748                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
749
750                                                                         $fRange = 0.01;
751                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
752                                                                         if ($oDB->getOne($sSQL))
753                                                                         {
754                                                                                 // More efficient - can make the range bigger
755                                                                         $fRange = 0.05;
756                                                                                 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
757                                                                                 $sSQL .= ",placex as f where ";
758                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
759                                                                                 if (sizeof($aExcludePlaceIDs))
760                                                                                 {
761                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
762                                                                                 }
763                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
764                                                                                 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
765                                                                                 $sSQL .= " limit $iLimit";
766                                                                                 if (CONST_Debug) var_dump($sSQL);
767                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
768                                                                         }
769                                                                         else
770                                                                         {
771                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
772                                                                                 $sSQL = "select l.place_id from placex as l,placex as f where ";
773                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
774                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
775                                                                                 if (sizeof($aExcludePlaceIDs))
776                                                                                 {
777                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
778                                                                                 }
779                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
780                                                                                 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
781                                                                                 $sSQL .= " limit $iLimit";
782                                                                                 if (CONST_Debug) var_dump($sSQL);
783                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
784                                                                         }
785                                                                 }
786                                                         }
787                                                 
788                                                 }
789
790                                                 if (PEAR::IsError($aPlaceIDs))
791                                                 {
792                                                         var_dump($sSQL, $aPlaceIDs);                                    
793                                                         exit;
794                                                 }
795
796                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
797
798                                                 foreach($aPlaceIDs as $iPlaceID)
799                                                 {
800                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
801                                                 }
802                                                 if ($iQueryLoop > 20) break;
803                                         }
804                                         //exit;
805                                         if (sizeof($aResultPlaceIDs)) break;
806                                         if ($iGroupLoop > 4) break;
807                                         if ($iQueryLoop > 30) break;
808                                 }
809 //exit;
810                                 // Did we find anything?        
811                                 if (sizeof($aResultPlaceIDs))
812                                 {
813 //var_Dump($aResultPlaceIDs);exit;
814                                         // Get the details for display (is this a redundant extra step?)
815                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
816                                         $sOrderSQL = 'CASE ';
817                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
818                                         {
819                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
820                                         }
821                                         $sOrderSQL .= ' ELSE 10000000 END ASC';
822                                         $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
823                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
824                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
825                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
826                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
827                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
828                                         $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
829                                         if (!$bDeDupe) $sSQL .= ",place_id";
830                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
831                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
832                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
833                                         $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
834                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
835                                         $aSearchResults = $oDB->getAll($sSQL);
836 //var_dump($sSQL,$aSearchResults);exit;
837
838                                         if (PEAR::IsError($aSearchResults))
839                                         {
840                                                 var_dump($sSQL, $aSearchResults);                                       
841                                                 exit;
842                                         }
843                                 }
844                         }
845                 }
846         
847         $sSearchResult = '';
848         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
849         {
850                 $sSearchResult = 'No Results Found';
851         }
852         
853         $aClassType = getClassTypesWithImportance();
854
855         foreach($aSearchResults as $iResNum => $aResult)
856         {
857                 if (CONST_Search_AreaPolygons || true)
858                 {
859                         // Get the bounding box and outline polygon
860                         $sSQL = "select place_id,numfeatures,area,outline,";
861                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
862                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
863                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
864                         $aPointPolygon = $oDB->getRow($sSQL);
865                         if (PEAR::IsError($aPointPolygon))
866                         {
867                                 var_dump($sSQL, $aPointPolygon);
868                                 exit;
869                         }
870                         if ($aPointPolygon['place_id'])
871                         {
872                                 // Translate geometary string to point array
873                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
874                                 {
875                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
876                                 }
877                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
878                                 {
879                                         $fRadius = 0.01;
880                                         $iSteps = ($fRadius * 40000)^2;
881                                         $fStepSize = (2*pi())/$iSteps;
882                                         $aPolyPoints = array();
883                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
884                                         {
885                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
886                                         }
887                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
888                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
889                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
890                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
891                                 }
892
893                                 // Output data suitable for display (points and a bounding box)
894                                 if ($bShowPolygons)
895                                 {
896                                         $aResult['aPolyPoints'] = array();
897                                         foreach($aPolyPoints as $aPoint)
898                                         {
899                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
900                                         }
901                                 }
902                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
903                         }
904                 }
905
906                 if (!isset($aResult['aBoundingBox']))
907                 {
908                         // Default
909                         $fDiameter = 0.0001;
910
911                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
912                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
913                         {
914                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
915                         }
916                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
917                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
918                         {
919                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
920                         }
921                         $fRadius = $fDiameter / 2;
922
923                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
924                         $fStepSize = (2*pi())/$iSteps;
925                         $aPolyPoints = array();
926                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
927                         {
928                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
929                         }
930                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
931                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
932                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
933                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
934
935                         // Output data suitable for display (points and a bounding box)
936                         if ($bShowPolygons)
937                         {
938                                 $aResult['aPolyPoints'] = array();
939                                 foreach($aPolyPoints as $aPoint)
940                                 {
941                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
942                                 }
943                         }
944                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
945                 }
946
947                 // Is there an icon set for this type of result?
948                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
949                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
950                 {
951                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
952                 }
953
954                 if ($bShowAddressDetails)
955                 {
956                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
957                 }
958
959                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
960                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
961                 {
962                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
963                 }
964                 else
965                 {
966                         $aResult['importance'] = 1000000000000000;
967                 }
968
969                 $aResult['name'] = $aResult['langaddress'];
970                 $aResult['foundorder'] = $iResNum;
971                 $aSearchResults[$iResNum] = $aResult;
972         }
973         
974         uasort($aSearchResults, 'byImportance');
975         
976         $aOSMIDDone = array();
977         $aClassTypeNameDone = array();
978         $aToFilter = $aSearchResults;
979         $aSearchResults = array();
980
981         $bFirst = true;
982         foreach($aToFilter as $iResNum => $aResult)
983         {
984                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
985                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
986                 if ($bFirst)
987                 {
988                         $fLat = $aResult['lat'];
989                         $fLon = $aResult['lon'];
990                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
991                         $bFirst = false;
992                 }
993                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
994                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
995                 {
996                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
997                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
998                         $aSearchResults[] = $aResult;
999                 }
1000         }
1001
1002         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1003
1004         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1005         {
1006                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1007         }
1008
1009         if ($sQuery)
1010         {
1011                 logEnd($oDB, $hLog, sizeof($aToFilter));
1012         }
1013         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1014         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1015         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1016         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1017         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1018         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1019         if ($sSuggestion)
1020         {
1021                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1022         }
1023         $sMoreURL .= '&q='.urlencode($sQuery);
1024
1025         if (CONST_Debug) exit;
1026
1027         include('.htlib/output/search-'.$sOutputFormat.'.php');