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