]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
hstore names / refactoring
[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                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
423                                                                                         if (!sizeof($aSearch['aName']))
424                                                                                         {
425                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
426                                                                                                 $aSearch['iNamePhrase'] = $iPhrase;
427                                                                                         }
428                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
429                                                                                 }
430                                                                         }
431                                                                 }
432                                                                 if (isset($aValidTokens[$sToken]))
433                                                                 {
434                                                                         // Allow searching for a word - but at extra cost
435                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
436                                                                         {
437                                                                                 $aSearch = $aCurrentSearch;
438                                                                                 $aSearch['iSearchRank']+=5;
439                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
440                                                                                 if (!sizeof($aSearch['aName']) || $aSearch['iNamePhrase'] == $iPhrase)
441                                                                                 {
442                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
443                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
444                                                                                 }
445                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
446                                                                         }
447                                                                 }
448                                                                 else
449                                                                 {
450                                                                         // Allow skipping a word - but at EXTREAM cost
451                                                                         //$aSearch = $aCurrentSearch;
452                                                                         //$aSearch['iSearchRank']+=100;
453                                                                         //$aNewWordsetSearches[] = $aSearch;
454                                                                 }
455                                                         }
456                                                         // Sort and cut
457                                                         usort($aNewWordsetSearches, 'bySearchRank');
458                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
459                                                 }                                               
460 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
461
462                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
463                                                 usort($aNewPhraseSearches, 'bySearchRank');
464                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
465                                         }
466
467                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
468                                         $aGroupedSearches = array();
469                                         foreach($aNewPhraseSearches as $aSearch)
470                                         {
471                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
472                                                 {
473                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
474                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
475                                                 }
476                                         }
477                                         ksort($aGroupedSearches);
478
479                                         $iSearchCount = 0;
480                                         $aSearches = array();
481                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
482                                         {
483                                                 $iSearchCount += sizeof($aNewSearches);
484                                                 $aSearches = array_merge($aSearches, $aNewSearches);
485                                                 if ($iSearchCount > 50) break;
486                                         }
487                                 }
488                         }
489                         else
490                         {
491                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
492                                         $aGroupedSearches = array();
493                                         foreach($aSearches as $aSearch)
494                                         {
495                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
496                                                 {
497                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
498                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
499                                                 }
500                                         }
501                                         ksort($aGroupedSearches);
502                         }
503                                 
504                                 if (CONST_Debug) var_Dump($aGroupedSearches);
505
506                                 if ($bReverseInPlan)
507                                 {
508                                         foreach($aGroupedSearches as $iGroup => $aSearches)
509                                         {
510                                                 foreach($aSearches as $iSearch => $aSearch)
511                                                 {
512                                                         if (sizeof($aSearch['aAddress']))
513                                                         {
514                                                                 $aReverseSearch = $aSearch;
515                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
516                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
517                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
518                                                         }
519                                                 }
520                                         }
521                                 }
522
523 //var_Dump($aGroupedSearches); exit;
524
525                                 // Filter out duplicate searches
526                                 $aSearchHash = array();
527                                 foreach($aGroupedSearches as $iGroup => $aSearches)
528                                 {
529                                         foreach($aSearches as $iSearch => $aSearch)
530                                         {
531                                                 $sHash = serialize($aSearch);
532                                                 if (isset($aSearchHash[$sHash]))
533                                                 {
534                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
535                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
536                                                 }
537                                                 else
538                                                 {
539                                                         $aSearchHash[$sHash] = 1;
540                                                 }
541                                         }
542                                 }
543                                 
544                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
545
546                                 if ($bReverseInPlan)
547                                 {
548                                         foreach($aGroupedSearches as $iGroup => $aSearches)
549                                         {
550                                                 foreach($aSearches as $iSearch => $aSearch)
551                                                 {
552                                                         if (sizeof($aSearch['aAddress']))
553                                                         {
554                                                                 $aReverseSearch = $aSearch;
555                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
556                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
557                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
558                                                         }
559                                                 }
560                                         }
561                                 }
562
563                                 // Filter out duplicate searches
564                                 $aSearchHash = array();
565                                 foreach($aGroupedSearches as $iGroup => $aSearches)
566                                 {
567                                         foreach($aSearches as $iSearch => $aSearch)
568                                         {
569                                                 $sHash = serialize($aSearch);
570                                                 if (isset($aSearchHash[$sHash]))
571                                                 {
572                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
573                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
574                                                 }
575                                                 else
576                                                 {
577                                                         $aSearchHash[$sHash] = 1;
578                                                 }
579                                         }
580                                 }
581
582                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
583
584                                 $iGroupLoop = 0;
585                                 $iQueryLoop = 0;
586                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
587                                 {
588                                         $iGroupLoop++;
589                                         foreach($aSearches as $aSearch)
590                                         {
591                                                 $iQueryLoop++;
592                                                 // Must have a location term
593                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']))
594                                                 {
595                                                         if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
596                                                         if (!$aSearch['sClass']) continue;
597                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
598                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
599
600                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
601                                                         if ($oDB->getOne($sSQL))
602                                                         {
603                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
604                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
605                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
606                                                                 $sSQL .= " limit $iLimit";
607                                                                 if (CONST_Debug) var_dump($sSQL);
608                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
609
610                                                                 if (!sizeof($aPlaceIDs))
611                                                                 {
612                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
613                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
614                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
615                                                                         $sSQL .= " limit $iLimit";
616                                                                         if (CONST_Debug) var_dump($sSQL);
617                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
618                                                                 }
619                                                         }
620                                                         else
621                                                         {
622                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
623                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
624                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
625                                                                 $sSQL .= " limit $iLimit";
626                                                                 if (CONST_Debug) var_dump($sSQL);
627                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
628                                                         }
629                                                 }
630                                                 else
631                                                 {
632                                                         if ($aSearch['aName'] == array(282=>'282')) continue;
633
634                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
635                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
636                                                         $aPlaceIDs = array();
637                                                 
638                                                         // First we need a position, either aName or fLat or both
639                                                         $aTerms = array();
640                                                         $aOrder = array();
641                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
642                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
643                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
644                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
645                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
646                                                         {
647                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
648                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
649                                                         }
650                                                         if (sizeof($aExcludePlaceIDs))
651                                                         {
652                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
653                                                         }
654                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
655                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
656                                                         if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
657                                                         if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
658                                                         $aOrder[] = "search_rank ASC";
659                                                 
660                                                         if (sizeof($aTerms))
661                                                         {
662                                                                 $sSQL = "select place_id";
663                                                                 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
664                                                                 else $sSQL .= ",false as in_small";
665                                                                 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
666                                                                 else $sSQL .= ",false as in_large";
667                                                                 $sSQL .= " from search_name";
668                                                                 $sSQL .= " where ".join(' and ',$aTerms);
669                                                                 $sSQL .= " order by ".join(', ',$aOrder);
670                                                                 if ($aSearch['sHouseNumber'])
671                                                                         $sSQL .= " limit 50";
672                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
673                                                                         $sSQL .= " limit 1";
674                                                                 else
675                                                                         $sSQL .= " limit ".$iLimit;
676
677                                                                 if (CONST_Debug) var_dump($sSQL);
678                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
679                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
680                                                                 {
681                                                                         var_dump($sSQL, $aViewBoxPlaceIDs);                                     
682                                                                         exit;
683                                                                 }
684
685                                                                 // Did we have an viewbox matches?
686                                                                 $aPlaceIDs = array();
687                                                                 $bViewBoxMatch = false;
688                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
689                                                                 {
690                                                                         if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
691                                                                         if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
692                                                                         if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
693                                                                         else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
694                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
695                                                                 }
696                                                         }
697
698                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
699                                                         {
700                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
701         
702                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';
703
704                                                                 // Make sure everything nearby is indexed (if we pre-indexed houses this wouldn't be needed!)
705                                                                 $sSQL = "update placex set indexed = true from placex as f where placex.indexed = false";
706                                                                 $sSQL .= " and f.place_id in (".$sPlaceIDs.") and ST_DWithin(placex.geometry, f.geometry, 0.004)";
707                                                                 $sSQL .= " and placex.housenumber ~* E'".$sHouseNumberRegex."'";
708                                                                 $sSQL .= " and placex.class='place' and placex.type='house'";
709                                                                 if (CONST_Debug) var_dump($sSQL);
710                                                                 $oDB->query($sSQL);
711                                                         
712                                                                 // Now they are indexed look for a house attached to a street we found
713                                                                 $sSQL = "select place_id from placex where street_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
714                                                                 if (sizeof($aExcludePlaceIDs))
715                                                                 {
716                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
717                                                                 }
718                                                                 $sSQL .= " limit $iLimit";
719                                                                 if (CONST_Debug) var_dump($sSQL);
720                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
721                                                         }
722                                                 
723                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
724                                                         {
725                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
726
727                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
728                                                                 {
729                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
730                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
731                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
732                                                                         if (CONST_Debug) var_dump($sSQL);
733                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
734                                                                 }
735                                                                 
736                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
737                                                                 {
738                                                                         $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
739                                                                         if (CONST_Debug) var_dump($sSQL);
740                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
741
742                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
743                                                                         if (CONST_Debug) var_dump($sSQL);
744                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
745                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
746
747                                                                         $fRange = 0.01;
748                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
749                                                                         if ($oDB->getOne($sSQL))
750                                                                         {
751                                                                                 // More efficient - can make the range bigger
752                                                                         $fRange = 0.05;
753                                                                                 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
754                                                                                 $sSQL .= ",placex as f where ";
755                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
756                                                                                 if (sizeof($aExcludePlaceIDs))
757                                                                                 {
758                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
759                                                                                 }
760                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
761                                                                                 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
762                                                                                 $sSQL .= " limit $iLimit";
763                                                                                 if (CONST_Debug) var_dump($sSQL);
764                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
765                                                                         }
766                                                                         else
767                                                                         {
768                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
769                                                                                 $sSQL = "select l.place_id from placex as l,placex as f where ";
770                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
771                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
772                                                                                 if (sizeof($aExcludePlaceIDs))
773                                                                                 {
774                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
775                                                                                 }
776                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
777                                                                                 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
778                                                                                 $sSQL .= " limit $iLimit";
779                                                                                 if (CONST_Debug) var_dump($sSQL);
780                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
781                                                                         }
782                                                                 }
783                                                         }
784                                                 
785                                                 }
786
787                                                 if (PEAR::IsError($aPlaceIDs))
788                                                 {
789                                                         var_dump($sSQL, $aPlaceIDs);                                    
790                                                         exit;
791                                                 }
792
793                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
794
795                                                 foreach($aPlaceIDs as $iPlaceID)
796                                                 {
797                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
798                                                 }
799                                                 if ($iQueryLoop > 20) break;
800                                         }
801                                         //exit;
802                                         if (sizeof($aResultPlaceIDs)) break;
803                                         if ($iGroupLoop > 4) break;
804                                         if ($iQueryLoop > 30) break;
805                                 }
806 //exit;
807                                 // Did we find anything?        
808                                 if (sizeof($aResultPlaceIDs))
809                                 {
810 //var_Dump($aResultPlaceIDs);exit;
811                                         // Get the details for display (is this a redundant extra step?)
812                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
813                                         $sOrderSQL = 'CASE ';
814                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
815                                         {
816                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
817                                         }
818                                         $sOrderSQL .= ' ELSE 10000000 END ASC';
819                                         $sSQL = "select osm_type,osm_id,class,type,rank_search,rank_address,min(place_id) as place_id,country_code,";
820                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
821                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
822                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
823                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat ";
824                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
825                                         $sSQL .= "group by osm_type,osm_id,class,type,rank_search,rank_address,country_code";
826                                         if (!$bDeDupe) $sSQL .= ",place_id";
827                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
828                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
829                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
830                                         $sSQL .= "order by rank_search,rank_address,".$sOrderSQL;
831                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
832                                         $aSearchResults = $oDB->getAll($sSQL);
833 //var_dump($sSQL,$aSearchResults);exit;
834
835                                         if (PEAR::IsError($aSearchResults))
836                                         {
837                                                 var_dump($sSQL, $aSearchResults);                                       
838                                                 exit;
839                                         }
840                                 }
841                         }
842                 }
843         
844         $sSearchResult = '';
845         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
846         {
847                 $sSearchResult = 'No Results Found';
848         }
849         
850         $aClassType = getClassTypesWithImportance();
851
852         foreach($aSearchResults as $iResNum => $aResult)
853         {
854                 if (CONST_Search_AreaPolygons || true)
855                 {
856                         // Get the bounding box and outline polygon
857                         $sSQL = "select place_id,numfeatures,area,outline,";
858                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
859                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
860                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
861                         $aPointPolygon = $oDB->getRow($sSQL);
862                         if (PEAR::IsError($aPointPolygon))
863                         {
864                                 var_dump($sSQL, $aPointPolygon);
865                                 exit;
866                         }
867                         if ($aPointPolygon['place_id'])
868                         {
869                                 // Translate geometary string to point array
870                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
871                                 {
872                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
873                                 }
874                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
875                                 {
876                                         $fRadius = 0.01;
877                                         $iSteps = ($fRadius * 40000)^2;
878                                         $fStepSize = (2*pi())/$iSteps;
879                                         $aPolyPoints = array();
880                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
881                                         {
882                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
883                                         }
884                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
885                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
886                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
887                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
888                                 }
889
890                                 // Output data suitable for display (points and a bounding box)
891                                 if ($bShowPolygons)
892                                 {
893                                         $aResult['aPolyPoints'] = array();
894                                         foreach($aPolyPoints as $aPoint)
895                                         {
896                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
897                                         }
898                                 }
899                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
900                         }
901                 }
902
903                 if (!isset($aResult['aBoundingBox']))
904                 {
905                         // Default
906                         $fDiameter = 0.0001;
907
908                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
909                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
910                         {
911                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
912                         }
913                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
914                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
915                         {
916                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
917                         }
918                         $fRadius = $fDiameter / 2;
919
920                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
921                         $fStepSize = (2*pi())/$iSteps;
922                         $aPolyPoints = array();
923                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
924                         {
925                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
926                         }
927                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
928                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
929                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
930                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
931
932                         // Output data suitable for display (points and a bounding box)
933                         if ($bShowPolygons)
934                         {
935                                 $aResult['aPolyPoints'] = array();
936                                 foreach($aPolyPoints as $aPoint)
937                                 {
938                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
939                                 }
940                         }
941                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
942                 }
943
944                 // Is there an icon set for this type of result?
945                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
946                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
947                 {
948                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
949                 }
950
951                 if ($bShowAddressDetails)
952                 {
953                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
954                 }
955
956                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
957                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
958                 {
959                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
960                 }
961                 else
962                 {
963                         $aResult['importance'] = 1000000000000000;
964                 }
965
966                 $aResult['name'] = $aResult['langaddress'];
967                 $aResult['foundorder'] = $iResNum;
968                 $aSearchResults[$iResNum] = $aResult;
969         }
970         
971         uasort($aSearchResults, 'byImportance');
972         
973         $aOSMIDDone = array();
974         $aClassTypeNameDone = array();
975         $aToFilter = $aSearchResults;
976         $aSearchResults = array();
977
978         $bFirst = true;
979         foreach($aToFilter as $iResNum => $aResult)
980         {
981                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
982                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
983                 if ($bFirst)
984                 {
985                         $fLat = $aResult['lat'];
986                         $fLon = $aResult['lon'];
987                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
988                         $bFirst = false;
989                 }
990                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
991                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
992                 {
993                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
994                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
995                         $aSearchResults[] = $aResult;
996                 }
997         }
998
999         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1000
1001         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1002         {
1003                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1004         }
1005
1006         if ($sQuery)
1007         {
1008                 logEnd($oDB, $hLog, sizeof($aToFilter));
1009         }
1010         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1011         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1012         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1013         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1014         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1015         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1016         if ($sSuggestion)
1017         {
1018                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1019         }
1020         $sMoreURL .= '&q='.urlencode($sQuery);
1021
1022         if (CONST_Debug) exit;
1023
1024         include('.htlib/output/search-'.$sOutputFormat.'.php');