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