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