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