]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
avoid dropping tokens completely just because they are expensive. Use ' ' token...
[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                                 // Very special case - require 2 letter country param to match the country code found
420                                 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country']) 
421                                   && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
422                                 {
423                                         continue;
424                                 }
425
426                                 if (isset($aValidTokens[$aToken['word_token']]))
427                                 {
428                                         $aValidTokens[$aToken['word_token']][] = $aToken;
429                                 }
430                                 else
431                                 {
432                                         $aValidTokens[$aToken['word_token']] = array($aToken);
433                                 }
434                                 if ($aToken['word_token'][0]==' ' && !$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
435                                 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
436                         }
437                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
438
439                         $aSuggestion = array();
440                         $bSuggestion = false;
441                         if (CONST_Suggestions_Enabled)
442                         {
443                                 foreach($aPhrases as $iPhrase => $aPhrase)
444                                 {
445                                         if (!isset($aValidTokens[' '.$aPhrase['wordsets'][0][0]]))
446                                         {
447                                                 $sQuotedPhrase = getDBQuoted(' '.$aPhrase['wordsets'][0][0]);
448                                                 $aSuggestionWords = getWordSuggestions($oDB, $aPhrase['wordsets'][0][0]);
449                                                 $aRow = $aSuggestionWords[0];
450                                                 if ($aRow && $aRow['word'])
451                                                 {
452                                                         $aSuggestion[] = $aRow['word'];
453                                                         $bSuggestion = true;
454                                                 }
455                                                 else
456                                                 {
457                                                         $aSuggestion[] = $aPhrase['string'];
458                                                 }
459                                         }
460                                         else
461                                         {
462                                                 $aSuggestion[] = $aPhrase['string'];
463                                         }
464                                 }
465                         }
466                         if ($bSuggestion) $sSuggestion = join(', ',$aSuggestion);
467
468                         // Try and calculate GB postcodes we might be missing
469                         foreach($aTokens as $sToken)
470                         {
471                                 // Source of gb postcodes is now definitive - always use
472                                 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
473                                 {
474                                         if (substr($aData[1],-2,1) != ' ')
475                                         {
476                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
477                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
478                                         }
479                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $oDB);
480                                         if ($aGBPostcodeLocation)
481                                         {
482                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
483                                         }
484                                 }
485                         }
486
487                         foreach($aTokens as $sToken)
488                         {
489                                 // Unknown single word token with a number - assume it is a house number
490                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
491                                 {
492                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
493                                 }
494                         }
495
496                         // Any words that have failed completely?
497                         // TODO: suggestions
498
499                         // Start the search process
500                         $aResultPlaceIDs = array();
501
502                         /*
503                                 Calculate all searches using aValidTokens i.e.
504
505                                 'Wodsworth Road, Sheffield' =>
506
507                                 Phrase Wordset
508                                 0      0       (wodsworth road)
509                                 0      1       (wodsworth)(road)
510                                 1      0       (sheffield)
511
512                                 Score how good the search is so they can be ordered
513                         */
514                                 foreach($aPhrases as $iPhrase => $sPhrase)
515                                 {
516                                         $aNewPhraseSearches = array();
517                                         if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
518                                         else $sPhraseType = '';
519
520                                         foreach($aPhrases[$iPhrase]['wordsets'] as $aWordset)
521                                         {
522                                                 $aWordsetSearches = $aSearches;
523
524                                                 // Add all words from this wordset
525                                                 foreach($aWordset as $iToken => $sToken)
526                                                 {
527 //echo "<br><b>$sToken</b>";
528                                                         $aNewWordsetSearches = array();
529
530                                                         foreach($aWordsetSearches as $aCurrentSearch)
531                                                         {
532 //echo "<i>";
533 //var_dump($aCurrentSearch);
534 //echo "</i>";
535
536                                                                 // If the token is valid
537                                                                 if (isset($aValidTokens[' '.$sToken]))
538                                                                 {
539                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
540                                                                         {
541                                                                                 $aSearch = $aCurrentSearch;
542                                                                                 $aSearch['iSearchRank']++;
543                                                                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
544                                                                                 {
545                                                                                         if ($aSearch['sCountryCode'] === false)
546                                                                                         {
547                                                                                                 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
548                                                                                                 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
549                                                                                                 // If reverse order is enabled, it may appear at the beginning as well.
550                                                                                                 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
551                                                                                                                 (!$bReverseInPlan || $iToken > 0 || $iPhrase > 0))
552                                                                                                 {
553                                                                                                         $aSearch['iSearchRank'] += 5;
554                                                                                                 }
555                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
556                                                                                         }
557                                                                                 }
558                                                                                 elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
559                                                                                 {
560                                                                                         if ($aSearch['fLat'] === '')
561                                                                                         {
562                                                                                                 $aSearch['fLat'] = $aSearchTerm['lat'];
563                                                                                                 $aSearch['fLon'] = $aSearchTerm['lon'];
564                                                                                                 $aSearch['fRadius'] = $aSearchTerm['radius'];
565                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
566                                                                                         }
567                                                                                 }
568                                                                                 elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
569                                                                                 {
570                                                                                         if ($aSearch['sHouseNumber'] === '')
571                                                                                         {
572                                                                                                 $aSearch['sHouseNumber'] = $sToken;
573                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
574 /*
575                                                                                                 // Fall back to not searching for this item (better than nothing)
576                                                                                                 $aSearch = $aCurrentSearch;
577                                                                                                 $aSearch['iSearchRank'] += 1;
578                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
579 */
580                                                                                         }
581                                                                                 }
582                                                                                 elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
583                                                                                 {
584                                                                                         if ($aSearch['sClass'] === '')
585                                                                                         {
586                                                                                                 $aSearch['sOperator'] = $aSearchTerm['operator'];
587                                                                                                 $aSearch['sClass'] = $aSearchTerm['class'];
588                                                                                                 $aSearch['sType'] = $aSearchTerm['type'];
589                                                                                                 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
590                                                                                                 else $aSearch['sOperator'] = 'near'; // near = in for the moment
591
592                                                                                                 // Do we have a shortcut id?
593                                                                                                 if ($aSearch['sOperator'] == 'name')
594                                                                                                 {
595                                                                                                         $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
596                                                                                                         if ($iAmenityID = $oDB->getOne($sSQL))
597                                                                                                         {
598                                                                                                                 $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
599                                                                                                                 $aSearch['aName'][$iAmenityID] = $iAmenityID;
600                                                                                                                 $aSearch['sClass'] = '';
601                                                                                                                 $aSearch['sType'] = '';
602                                                                                                         }
603                                                                                                 }
604                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
605                                                                                         }
606                                                                                 }
607                                                                                 elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
608                                                                                 {
609                                                                                         if (sizeof($aSearch['aName']))
610                                                                                         {
611                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
612                                                                                                 {
613                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
614                                                                                                 }
615                                                                                                 else
616                                                                                                 {
617                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
618                                                                                                 }
619                                                                                         }
620                                                                                         else
621                                                                                         {
622                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623 //                                                                                              $aSearch['iNamePhrase'] = $iPhrase;
624                                                                                         }
625                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
626                                                                                 }
627                                                                         }
628                                                                 }
629                                                                 if (isset($aValidTokens[$sToken]))
630                                                                 {
631                                                                         // Allow searching for a word - but at extra cost
632                                                                         foreach($aValidTokens[$sToken] as $aSearchTerm)
633                                                                         {
634                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
635                                                                                 {
636                                                                                         if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
637                                                                                         {
638                                                                                                 $aSearch = $aCurrentSearch;
639                                                                                                 $aSearch['iSearchRank'] += 1;
640                                                                                                 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
641                                                                                                 {
642                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
643                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
644                                                                                                 }
645                                                                                                 elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
646                                                                                                 {
647                                                                                                         foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
648                                                                                                         {
649                                                                                                                 if (empty($aSearchTermToken['country_code']) 
650                                                                                                                         && empty($aSearchTermToken['lat'])
651                                                                                                                         && empty($aSearchTermToken['class']))
652                                                                                                                 {
653                                                                                                                         $aSearch = $aCurrentSearch;
654                                                                                                                         $aSearch['iSearchRank'] += 1;
655                                                                                                                         $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
656                                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
657                                                                                                                 }
658                                                                                                         }
659                                                                                                 }
660                                                                                                 else
661                                                                                                 {
662                                                                                                         $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
663                                                                                                         if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
664                                                                                                 }
665                                                                                         }
666
667                                                                                         if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
668                                                                                         {
669                                                                                                 $aSearch = $aCurrentSearch;
670                                                                                                 $aSearch['iSearchRank'] += 2;
671                                                                                                 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
672                                                                                                 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
673                                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
674                                                                                                 else
675                                                                                                         $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
676                                                                                                 $aSearch['iNamePhrase'] = $iPhrase;
677                                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
678                                                                                         }
679                                                                                 }
680                                                                         }
681                                                                 }
682                                                                 else
683                                                                 {
684                                                                         // Allow skipping a word - but at EXTREAM cost
685                                                                         //$aSearch = $aCurrentSearch;
686                                                                         //$aSearch['iSearchRank']+=100;
687                                                                         //$aNewWordsetSearches[] = $aSearch;
688                                                                 }
689                                                         }
690                                                         // Sort and cut
691                                                         usort($aNewWordsetSearches, 'bySearchRank');
692                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
693                                                 }                                               
694 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
695
696                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
697                                                 usort($aNewPhraseSearches, 'bySearchRank');
698
699           $aSearchHash = array();
700           foreach($aNewPhraseSearches as $iSearch => $aSearch)
701           {
702             $sHash = serialize($aSearch);
703             if (isset($aSearchHash[$sHash]))
704             {
705               unset($aNewPhraseSearches[$iSearch]);
706             }
707             else
708             {
709               $aSearchHash[$sHash] = 1;
710             }
711           }
712
713                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
714                                         }
715
716                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
717                                         $aGroupedSearches = array();
718                                         foreach($aNewPhraseSearches 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                                         $iSearchCount = 0;
729                                         $aSearches = array();
730                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
731                                         {
732                                                 $iSearchCount += sizeof($aNewSearches);
733                                                 $aSearches = array_merge($aSearches, $aNewSearches);
734                                                 if ($iSearchCount > 50) break;
735                                         }
736
737 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
738
739                                 }
740                         }
741                         else
742                         {
743                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
744                                         $aGroupedSearches = array();
745                                         foreach($aSearches as $aSearch)
746                                         {
747                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
748                                                 {
749                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
750                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
751                                                 }
752                                         }
753                                         ksort($aGroupedSearches);
754                         }
755                                 
756                                 if (CONST_Debug) var_Dump($aGroupedSearches);
757
758                                 if ($bReverseInPlan)
759                                 {
760                                         $aCopyGroupedSearches = $aGroupedSearches;
761                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
762                                         {
763                                                 foreach($aSearches as $iSearch => $aSearch)
764                                                 {
765                                                         if (sizeof($aSearch['aAddress']))
766                                                         {
767                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
768                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
769                                                                 {
770                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
771                                                                         $aSearch['aName'] = array($iReverseItem);
772                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
773                                                                 }
774 //                                                              $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
775         //                                                      $aGroupedSearches[$iGroup][] = $aReverseSearch;
776                                                         }
777                                                 }
778                                         }
779                                 }
780
781                                 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
782                                 {
783                                         $aCopyGroupedSearches = $aGroupedSearches;
784                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
785                                         {
786                                                 foreach($aSearches as $iSearch => $aSearch)
787                                                 {
788                                                         $aReductionsList = array($aSearch['aAddress']);
789                                                         $iSearchRank = $aSearch['iSearchRank'];
790                                                         while(sizeof($aReductionsList) > 0)
791                                                         {
792                                                                 $iSearchRank += 5;
793                                                                 if ($iSearchRank > iMaxRank) break 3;
794                                                                 $aNewReductionsList = array();
795                                                                 foreach($aReductionsList as $aReductionsWordList)
796                                                                 {
797                                                                         for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
798                                                                         {
799                                                                                 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
800                                                                                 $aReverseSearch = $aSearch;
801                                                                                 $aSearch['aAddress'] = $aReductionsWordListResult;
802                                                                                 $aSearch['iSearchRank'] = $iSearchRank;
803                                                                                 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
804                                                                                 if (sizeof($aReductionsWordListResult) > 0)
805                                                                                 {
806                                                                                         $aNewReductionsList[] = $aReductionsWordListResult;
807                                                                                 }
808                                                                         }
809                                                                 }
810                                                                 $aReductionsList = $aNewReductionsList;
811                                                         }
812                                                 }
813                                         }
814                                         ksort($aGroupedSearches);
815                                 }
816
817                                 // Filter out duplicate searches
818                                 $aSearchHash = array();
819                                 foreach($aGroupedSearches as $iGroup => $aSearches)
820                                 {
821                                         foreach($aSearches as $iSearch => $aSearch)
822                                         {
823                                                 $sHash = serialize($aSearch);
824                                                 if (isset($aSearchHash[$sHash]))
825                                                 {
826                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
827                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
828                                                 }
829                                                 else
830                                                 {
831                                                         $aSearchHash[$sHash] = 1;
832                                                 }
833                                         }
834                                 }
835
836                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
837
838                                 $iGroupLoop = 0;
839                                 $iQueryLoop = 0;
840                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
841                                 {
842                                         $iGroupLoop++;
843                                         foreach($aSearches as $aSearch)
844                                         {
845                                                 $iQueryLoop++;
846
847                                                 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
848                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
849
850
851                                                 // Must have a location term
852                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
853                                                 {
854                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
855                                                         {
856                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
857                                                                 {
858                                                                         $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
859                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
860                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
861                                                                         if (CONST_Debug) var_dump($sSQL);
862                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
863                                                                 }
864                                                         }
865                                                         else
866                                                         {
867                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
868                                                                 if (!$aSearch['sClass']) continue;
869                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
870                                                                 if ($oDB->getOne($sSQL))
871                                                                 {
872                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
873                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
874                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, ct.centroid)";
875                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
876                                                                 if (sizeof($aExcludePlaceIDs))
877                                                                 {
878                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
879                                                                 }
880                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
881                                                                 $sSQL .= " limit $iLimit";
882                                                                 if (CONST_Debug) var_dump($sSQL);
883                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
884
885                                                                 // If excluded place IDs are given, it is fair to assume that
886                                                                 // there have been results in the small box, so no further
887                                                                 // expansion in that case.
888                                                                 if (!sizeof($aPlaceIDs) && !sizeof($aExcludePlaceIDs))
889                                                                 {
890                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
891                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
892                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, ct.centroid)";
893                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
894                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
895                                                                         $sSQL .= " limit $iLimit";
896                                                                         if (CONST_Debug) var_dump($sSQL);
897                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
898                                                                 }
899                                                         }
900                                                         else
901                                                         {
902                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
903                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, geometry) and linked_place_id is null";
904                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
905                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
906                                                                 $sSQL .= " limit $iLimit";
907                                                                 if (CONST_Debug) var_dump($sSQL);
908                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
909                                                         }
910                                                         }
911                                                 }
912                                                 else
913                                                 {
914                                                         $aPlaceIDs = array();
915
916                                                         // First we need a position, either aName or fLat or both
917                                                         $aTerms = array();
918                                                         $aOrder = array();
919
920                                                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
921                                                         // they might be right - but they are just too darned expensive to run
922                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
923                                                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
924                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) 
925                                                         {
926                                                                 // For infrequent name terms disable index usage for address
927                                                                 if (CONST_Search_NameOnlySearchFrequencyThreshold && 
928                                                                         sizeof($aSearch['aName']) == 1 && 
929                                                                         $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
930                                                                 {
931                                                                         $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
932                                                                 }
933                                                                 else
934                                                                 {
935                                                                         $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
936                                                                         if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
937                                                                 }
938                                                         }
939                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
940                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
941                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
942                                                         {
943                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
944                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
945                                                         }
946                                                         if (sizeof($aExcludePlaceIDs))
947                                                         {
948                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
949                                                         }
950                                                         if ($sCountryCodesSQL)
951                                                         {
952                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
953                                                         }
954
955                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
956                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
957
958                                                         $sImportanceSQL = 'case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end';
959
960                                                         if ($sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
961                                                         if ($sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
962                                                         $aOrder[] = "$sImportanceSQL DESC";
963                                                 
964                                                         if (sizeof($aTerms))
965                                                         {
966                                                                 $sSQL = "select place_id";
967                                                                 $sSQL .= " from search_name";
968                                                                 $sSQL .= " where ".join(' and ',$aTerms);
969                                                                 $sSQL .= " order by ".join(', ',$aOrder);
970                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
971                                                                         $sSQL .= " limit 50";
972                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
973                                                                         $sSQL .= " limit 1";
974                                                                 else
975                                                                         $sSQL .= " limit ".$iLimit;
976
977                                                                 if (CONST_Debug) { var_dump($sSQL); }
978                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
979                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
980                                                                 {
981                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
982                                                                 }
983 //var_dump($aViewBoxPlaceIDs);
984                                                                 // Did we have an viewbox matches?
985                                                                 $aPlaceIDs = array();
986                                                                 $bViewBoxMatch = false;
987                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
988                                                                 {
989 //                                                                      if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
990 //                                                                      if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
991 //                                                                      if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
992 //                                                                      else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
993                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
994                                                                 }
995                                                         }
996 //var_Dump($aPlaceIDs);
997 //exit;
998
999                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1000                                                         {
1001                                                                 $aRoadPlaceIDs = $aPlaceIDs;
1002                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1003         
1004                                                                 // Now they are indexed look for a house attached to a street we found
1005                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';                                                
1006                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1007                                                                 if (sizeof($aExcludePlaceIDs))
1008                                                                 {
1009                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1010                                                                 }
1011                                                                 $sSQL .= " limit $iLimit";
1012                                                                 if (CONST_Debug) var_dump($sSQL);
1013                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
1014
1015                                                                 // If not try the aux fallback table
1016                                                                 if (!sizeof($aPlaceIDs))
1017                                                                 {
1018                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1019                                                                         if (sizeof($aExcludePlaceIDs))
1020                                                                         {
1021                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1022                                                                         }
1023 //                                                                      $sSQL .= " limit $iLimit";
1024                                                                         if (CONST_Debug) var_dump($sSQL);
1025                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
1026                                                                 }
1027
1028                                                                 if (!sizeof($aPlaceIDs))
1029                                                                 {
1030                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1031                                                                         if (sizeof($aExcludePlaceIDs))
1032                                                                         {
1033                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
1034                                                                         }
1035 //                                                                      $sSQL .= " limit $iLimit";
1036                                                                         if (CONST_Debug) var_dump($sSQL);
1037                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
1038                                                                 }
1039
1040                                                                 // Fallback to the road
1041                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1042                                                                 {
1043                                                                         $aPlaceIDs = $aRoadPlaceIDs;
1044                                                                 }
1045                                                                 
1046                                                         }
1047                                                 
1048                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1049                                                         {
1050                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1051
1052                                                                 $aClassPlaceIDs = array();
1053
1054                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1055                                                                 {
1056                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1057                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1058                                                                         $sSQL .= " and linked_place_id is null";
1059                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1060                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
1061                                                                         if (CONST_Debug) var_dump($sSQL);
1062                                                                         $aClassPlaceIDs = $oDB->getCol($sSQL);
1063                                                                 }
1064                                                                 
1065                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1066                                                                 {
1067                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1068                                                                         $bCacheTable = $oDB->getOne($sSQL);
1069
1070                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1071
1072                                                                         if (CONST_Debug) var_dump($sSQL);
1073                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL));
1074
1075                                                                         // For state / country level searches the normal radius search doesn't work very well
1076                                                                         $sPlaceGeom = false;
1077                                                                         if ($iMaxRank < 9 && $bCacheTable)
1078                                                                         {
1079                                                                                 // Try and get a polygon to search in instead
1080                                                                                 $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";
1081                                                                                 if (CONST_Debug) var_dump($sSQL);
1082                                                                                 $sPlaceGeom = $oDB->getOne($sSQL);
1083                                                                         }
1084                                                                         
1085                                                                         if ($sPlaceGeom)
1086                                                                         {
1087                                                                                 $sPlaceIDs = false;
1088                                                                         }
1089                                                                         else
1090                                                                         {
1091                                                                                 $iMaxRank += 5;
1092                                                                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
1093                                                                                 if (CONST_Debug) var_dump($sSQL);
1094                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
1095                                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1096                                                                         }
1097
1098                                                                         if ($sPlaceIDs || $sPlaceGeom)
1099                                                                         {
1100
1101                                                                         $fRange = 0.01;
1102                                                                         if ($bCacheTable)
1103                                                                         {
1104                                                                                 // More efficient - can make the range bigger
1105                                                                                 $fRange = 0.05;
1106
1107                                                                                 $sOrderBySQL = '';
1108                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1109                                                                                 else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1110                                                                                 else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1111
1112                                                                                 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1113                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1114                                                                                 if ($sPlaceIDs)
1115                                                                                 {
1116                                                                                         $sSQL .= ",placex as f where ";
1117                                                                                         $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1118                                                                                 }
1119                                                                                 if ($sPlaceGeom)
1120                                                                                 {
1121                                                                                         $sSQL .= " where ";
1122                                                                                         $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1123                                                                                 }
1124                                                                                 if (sizeof($aExcludePlaceIDs))
1125                                                                                 {
1126                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1127                                                                                 }
1128                                                                                 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1129                                                                                 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1130                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
1131                                                                                 $sSQL .= " limit $iLimit";
1132                                                                                 if (CONST_Debug) var_dump($sSQL);
1133                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1134                                                                         }
1135                                                                         else
1136                                                                         {
1137                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1138
1139                                                                                 $sOrderBySQL = '';
1140                                                                                 if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1141                                                                                 else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1142
1143                                                                                 $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1144                                                                                 $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1145                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1146                                                                                 if (sizeof($aExcludePlaceIDs))
1147                                                                                 {
1148                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
1149                                                                                 }
1150                                                                                 if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";                                                                
1151                                                                                 if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1152                                                                                 if ($iOffset) $sSQL .= " offset $iOffset";
1153                                                                                 $sSQL .= " limit $iLimit";
1154                                                                                 if (CONST_Debug) var_dump($sSQL);
1155                                                                                 $aClassPlaceIDs = array_merge($aClassPlaceIDs, $oDB->getCol($sSQL));
1156                                                                         }
1157                                                                         }
1158                                                                 }
1159
1160                                                                 $aPlaceIDs = $aClassPlaceIDs;
1161
1162                                                         }
1163                                                 
1164                                                 }
1165
1166                                                 if (PEAR::IsError($aPlaceIDs))
1167                                                 {
1168                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1169                                                 }
1170
1171                                                 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1172
1173                                                 foreach($aPlaceIDs as $iPlaceID)
1174                                                 {
1175                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1176                                                 }
1177                                                 if ($iQueryLoop > 20) break;
1178                                         }
1179
1180                                         //exit;
1181                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1182                                         if ($iGroupLoop > 4) break;
1183                                         if ($iQueryLoop > 30) break;
1184                                 }
1185
1186                                 // Did we find anything?        
1187                                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1188                                 {
1189 //var_Dump($aResultPlaceIDs);exit;
1190                                         // Get the details for display (is this a redundant extra step?)
1191                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1192                                         $sOrderSQL = 'CASE ';
1193                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1194                                         {
1195                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1196                                         }
1197                                         $sOrderSQL .= ' ELSE 10000000 END';
1198                                         $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,";
1199                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1200                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1201                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1202                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1203 //                                      $sSQL .= $sOrderSQL." as porder, ";
1204                                         $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1205                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1206                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1207                                         if ($sAllowedTypesSQLList) $sSQL .= "and placex.class in $sAllowedTypesSQLList ";
1208                                         $sSQL .= "and linked_place_id is null ";
1209                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1210                                         if (!$bDeDupe) $sSQL .= ",place_id";
1211                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1212                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1213                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1214                                         $sSQL .= " union ";
1215                                         $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,";
1216                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1217                                         $sSQL .= "null as placename,";
1218                                         $sSQL .= "null as ref,";
1219                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1220 //                                      $sSQL .= $sOrderSQL." as porder, ";
1221                                         $sSQL .= "-0.15 as importance ";
1222                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1223                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1224                                         $sSQL .= "group by place_id";
1225                                         if (!$bDeDupe) $sSQL .= ",place_id";
1226                                         $sSQL .= " union ";
1227                                         $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,";
1228                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1229                                         $sSQL .= "null as placename,";
1230                                         $sSQL .= "null as ref,";
1231                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1232 //                                      $sSQL .= $sOrderSQL." as porder, ";
1233                                         $sSQL .= "-0.10 as importance ";
1234                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1235                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1236                                         $sSQL .= "group by place_id";
1237                                         if (!$bDeDupe) $sSQL .= ",place_id";
1238                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1239                                         $sSQL .= "order by importance desc";
1240 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1241                                         if (CONST_Debug) { echo "<hr>"; var_dump($sSQL); }
1242                                         $aSearchResults = $oDB->getAll($sSQL);
1243 //var_dump($sSQL,$aSearchResults);exit;
1244
1245                                         if (PEAR::IsError($aSearchResults))
1246                                         {
1247                                                 failInternalError("Could not get details for place.", $sSQL, $aSearchResults);
1248                                         }
1249                                 }
1250                         } // end if ($sQuery)
1251                         else
1252                         {
1253                                 if (isset($_GET['nearlat']) && trim($_GET['nearlat'])!=='' && isset($_GET['nearlon']) && trim($_GET['nearlon']) !== '')
1254                                 {
1255                                         $iPlaceID = geocodeReverse($_GET['nearlat'], $_GET['nearlon']);
1256                                         $aResultPlaceIDs = array($iPlaceID);
1257
1258                                         // TODO: this needs refactoring!
1259
1260                                         // Get the details for display (is this a redundant extra step?)
1261                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
1262                                         $sOrderSQL = 'CASE ';
1263                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
1264                                         {
1265                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
1266                                         }
1267                                         $sOrderSQL .= ' ELSE 10000000 END';
1268                                         $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,";
1269                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1270                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
1271                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
1272                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1273 //                                      $sSQL .= $sOrderSQL." as porder, ";
1274                                         $sSQL .= "coalesce(importance,0.75-(rank_search::float/40)) as importance ";
1275                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
1276                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
1277                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
1278                                         if (!$bDeDupe) $sSQL .= ",place_id";
1279                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1280                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
1281                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
1282                                         $sSQL .= " union ";
1283                                         $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,";
1284                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1285                                         $sSQL .= "null as placename,";
1286                                         $sSQL .= "null as ref,";
1287                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1288 //                                      $sSQL .= $sOrderSQL." as porder, ";
1289                                         $sSQL .= "-0.15 as importance ";
1290                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
1291                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1292                                         $sSQL .= "group by place_id";
1293                                         if (!$bDeDupe) $sSQL .= ",place_id";
1294                                         $sSQL .= " union ";
1295                                         $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,";
1296                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
1297                                         $sSQL .= "null as placename,";
1298                                         $sSQL .= "null as ref,";
1299                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
1300 //                                      $sSQL .= $sOrderSQL." as porder, ";
1301                                         $sSQL .= "-0.10 as importance ";
1302                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
1303                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
1304                                         $sSQL .= "group by place_id";
1305                                         if (!$bDeDupe) $sSQL .= ",place_id";
1306                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
1307                                         $sSQL .= "order by importance desc";
1308 //                                      $sSQL .= "order by rank_search,rank_address,porder asc";
1309                                         if (CONST_Debug) { echo "<hr>", var_dump($sSQL); }
1310                                         $aSearchResults = $oDB->getAll($sSQL);
1311 //var_dump($sSQL,$aSearchResults);exit;
1312
1313                                         if (PEAR::IsError($aSearchResults))
1314                                         {
1315                         failInternalError("Could not get details for place (near).", $sSQL, $aSearchResults);
1316                                         }
1317                                 }
1318                         }
1319                 }
1320         
1321         $sSearchResult = '';
1322         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
1323         {
1324                 $sSearchResult = 'No Results Found';
1325         }
1326 //var_Dump($aSearchResults);
1327 //exit;
1328         $aClassType = getClassTypesWithImportance();
1329         $aRecheckWords = preg_split('/\b/',$sQuery);
1330         foreach($aRecheckWords as $i => $sWord)
1331         {
1332                 if (!$sWord) unset($aRecheckWords[$i]);
1333         }
1334         foreach($aSearchResults as $iResNum => $aResult)
1335         {
1336                 if (CONST_Search_AreaPolygons)
1337                 {
1338                         // Get the bounding box and outline polygon
1339                         $sSQL = "select place_id,numfeatures,area,outline,";
1340                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(outline)),2)) as maxlat,";
1341                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(outline)),3)) as maxlon,";
1342                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
1343
1344                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1345                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1346                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1347                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1348                         if ($bAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1349                         if ($bAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1350                         if ($bAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1351                         if ($bAsText || $bShowPolygons) $sSQL .= ",ST_AsText(geometry) as astext";
1352                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1353                         $aPointPolygon = $oDB->getRow($sSQL);
1354                         if (PEAR::IsError($aPointPolygon))
1355                         {
1356                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1357                         }
1358                         if ($aPointPolygon['place_id'])
1359                         {
1360                                 if ($bAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1361                                 if ($bAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1362                                 if ($bAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1363                                 if ($bAsText) $aResult['astext'] = $aPointPolygon['astext'];
1364
1365                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null ) {
1366                                         $aResult['lat'] = $aPointPolygon['centrelat'];
1367                                         $aResult['lon'] = $aPointPolygon['centrelon'];
1368                                 }
1369                                 if ($bShowPolygons) 
1370                                 {
1371                                         // Translate geometary string to point array
1372                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1373                                         {
1374                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1375                                         }
1376                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1377                                         {
1378                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1379                                         }
1380                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1381                                         {
1382                                                 $fRadius = 0.01;
1383                                                 $iSteps = ($fRadius * 40000)^2;
1384                                                 $fStepSize = (2*pi())/$iSteps;
1385                                                 $aPolyPoints = array();
1386                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1387                                                 {
1388                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1389                                                 }
1390                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1391                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1392                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1393                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1394                                         }
1395                                 }
1396
1397                                 // Output data suitable for display (points and a bounding box)
1398                                 if ($bShowPolygons && isset($aPolyPoints))
1399                                 {
1400                                         $aResult['aPolyPoints'] = array();
1401                                         foreach($aPolyPoints as $aPoint)
1402                                         {
1403                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1404                                         }
1405                                 }
1406                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1407                         }
1408                 }
1409
1410                 if (!isset($aResult['aBoundingBox']))
1411                 {
1412                         // Default
1413                         $fDiameter = 0.0001;
1414
1415                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
1416                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1417                         {
1418                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1419                         }
1420                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
1421                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1422                         {
1423                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1424                         }
1425                         $fRadius = $fDiameter / 2;
1426
1427                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1428                         $fStepSize = (2*pi())/$iSteps;
1429                         $aPolyPoints = array();
1430                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1431                         {
1432                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1433                         }
1434                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1435                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1436                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1437                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1438
1439                         // Output data suitable for display (points and a bounding box)
1440                         if ($bShowPolygons)
1441                         {
1442                                 $aResult['aPolyPoints'] = array();
1443                                 foreach($aPolyPoints as $aPoint)
1444                                 {
1445                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1446                                 }
1447                         }
1448                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1449                 }
1450
1451                 // Is there an icon set for this type of result?
1452                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
1453                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1454                 {
1455                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1456                 }
1457
1458                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label']) 
1459                         && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1460                 {
1461                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1462                 }
1463
1464                 if ($bShowAddressDetails)
1465                 {
1466                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1467 //var_dump($aResult['address']);
1468 //exit;
1469                 }
1470
1471                 // Adjust importance for the number of exact string matches in the result
1472                 $aResult['importance'] = max(0.001,$aResult['importance']);
1473                 $iCountWords = 0;
1474                 $sAddress = $aResult['langaddress'];
1475                 foreach($aRecheckWords as $i => $sWord)
1476                 {
1477                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1478                 }
1479                 $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
1480
1481 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1482 /*
1483                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
1484                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1485                 {
1486                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1487                 }
1488                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
1489                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1490                 {
1491                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1492                 }
1493                 else
1494                 {
1495                         $aResult['importance'] = 1000000000000000;
1496                 }
1497 */
1498                 $aResult['name'] = $aResult['langaddress'];
1499                 $aResult['foundorder'] = $iResNum;
1500                 $aSearchResults[$iResNum] = $aResult;
1501         }
1502         uasort($aSearchResults, 'byImportance');
1503
1504         $aOSMIDDone = array();
1505         $aClassTypeNameDone = array();
1506         $aToFilter = $aSearchResults;
1507         $aSearchResults = array();
1508
1509         $bFirst = true;
1510         foreach($aToFilter as $iResNum => $aResult)
1511         {
1512                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1513                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1514                 if ($bFirst)
1515                 {
1516                         $fLat = $aResult['lat'];
1517                         $fLon = $aResult['lon'];
1518                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1519                         $bFirst = false;
1520                 }
1521                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1522                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']])))
1523                 {
1524                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1525                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['name']] = true;
1526                         $aSearchResults[] = $aResult;
1527                 }
1528
1529                 // Absolute limit on number of results
1530                 if (sizeof($aSearchResults) >= $iFinalLimit) break;
1531         }
1532
1533         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1534
1535         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1536         {
1537                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1538         }
1539
1540         if ($sQuery)
1541         {
1542                 logEnd($oDB, $hLog, sizeof($aToFilter));
1543         }
1544         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1545         if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1546         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1547         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1548         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1549         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1550         if ($sSuggestion)
1551         {
1552                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1553         }
1554         $sMoreURL .= '&q='.urlencode($sQuery);
1555
1556         if (CONST_Debug) exit;
1557
1558         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');