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