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