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