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