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