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