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