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