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