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