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