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