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