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