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