]> git.openstreetmap.org Git - nominatim.git/blob - website/search.php
deduplicate search term graph slightly earlier
[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, ny', $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 || strpos($sToken, ' ') !== false)
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]))
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'])  && strlen($sToken) >= 4)
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'] += 2;
492                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
493                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
494                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
495                                                                                 if ($aSearch['iSearchRank'] < $iMaxRank) $aNewWordsetSearches[] = $aSearch;
496                                                                                 }
497                                                                         }
498                                                                 }
499                                                                 else
500                                                                 {
501                                                                         // Allow skipping a word - but at EXTREAM cost
502                                                                         //$aSearch = $aCurrentSearch;
503                                                                         //$aSearch['iSearchRank']+=100;
504                                                                         //$aNewWordsetSearches[] = $aSearch;
505                                                                 }
506                                                         }
507                                                         // Sort and cut
508                                                         usort($aNewWordsetSearches, 'bySearchRank');
509                                                         $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
510                                                 }                                               
511 //                                              var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
512
513                                                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
514                                                 usort($aNewPhraseSearches, 'bySearchRank');
515
516           $aSearchHash = array();
517           foreach($aNewPhraseSearches as $iSearch => $aSearch)
518           {
519             $sHash = serialize($aSearch);
520             if (isset($aSearchHash[$sHash]))
521             {
522               unset($aNewPhraseSearches[$iSearch]);
523             }
524             else
525             {
526               $aSearchHash[$sHash] = 1;
527             }
528           }
529
530                                                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
531                                         }
532
533                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
534                                         $aGroupedSearches = array();
535                                         foreach($aNewPhraseSearches as $aSearch)
536                                         {
537                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
538                                                 {
539                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
540                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
541                                                 }
542                                         }
543                                         ksort($aGroupedSearches);
544
545                                         $iSearchCount = 0;
546                                         $aSearches = array();
547                                         foreach($aGroupedSearches as $iScore => $aNewSearches)
548                                         {
549                                                 $iSearchCount += sizeof($aNewSearches);
550                                                 $aSearches = array_merge($aSearches, $aNewSearches);
551                                                 if ($iSearchCount > 50) break;
552                                         }
553
554 //                                      if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
555
556                                 }
557                         }
558                         else
559                         {
560                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
561                                         $aGroupedSearches = array();
562                                         foreach($aSearches as $aSearch)
563                                         {
564                                                 if ($aSearch['iSearchRank'] < $iMaxRank)
565                                                 {
566                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
567                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
568                                                 }
569                                         }
570                                         ksort($aGroupedSearches);
571                         }
572                                 
573                                 if (CONST_Debug) var_Dump($aGroupedSearches);
574
575                                 if ($bReverseInPlan && false)
576                                 {
577                                         foreach($aGroupedSearches as $iGroup => $aSearches)
578                                         {
579                                                 foreach($aSearches as $iSearch => $aSearch)
580                                                 {
581                                                         if (sizeof($aSearch['aAddress']))
582                                                         {
583                                                                 $aReverseSearch = $aSearch;
584                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
585                                                                 $aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
586                                                                 $aGroupedSearches[$iGroup][] = $aReverseSearch;
587                                                         }
588                                                 }
589                                         }
590                                 }
591
592                                 // Filter out duplicate searches
593                                 $aSearchHash = array();
594                                 foreach($aGroupedSearches as $iGroup => $aSearches)
595                                 {
596                                         foreach($aSearches as $iSearch => $aSearch)
597                                         {
598                                                 $sHash = serialize($aSearch);
599                                                 if (isset($aSearchHash[$sHash]))
600                                                 {
601                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
602                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
603                                                 }
604                                                 else
605                                                 {
606                                                         $aSearchHash[$sHash] = 1;
607                                                 }
608                                         }
609                                 }
610
611                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
612
613                                 $iGroupLoop = 0;
614                                 $iQueryLoop = 0;
615                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
616                                 {
617                                         $iGroupLoop++;
618                                         foreach($aSearches as $aSearch)
619                                         {
620                                                 $iQueryLoop++;
621
622                                                 // Must have a location term
623                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
624                                                 {
625                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'])
626                                                         {
627                                                                 if (4 >= $iMinAddressRank && 4 <= $iMaxAddressRank)
628                                                                 {
629                                                                         $sSQL = "select place_id from placex where country_code='".$aSearch['sCountryCode']."' and rank_search = 4 order by st_area(geometry) desc limit 1";
630                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
631                                                                 }
632                                                         }
633                                                         else
634                                                         {
635                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
636                                                                 if (!$aSearch['sClass']) continue;
637                                                                 if (CONST_Debug) var_dump('<hr>',$aSearch);
638                                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
639
640                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
641                                                                 if ($oDB->getOne($sSQL))
642                                                                 {
643                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
644                                                                 $sSQL .= " where st_contains($sViewboxSmallSQL, centroid)";
645                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
646                                                                 $sSQL .= " limit $iLimit";
647                                                                 if (CONST_Debug) var_dump($sSQL);
648                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
649
650                                                                 if (!sizeof($aPlaceIDs))
651                                                                 {
652                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType'];                                                               
653                                                                         $sSQL .= " where st_contains($sViewboxLargeSQL, centroid)";
654                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
655                                                                         $sSQL .= " limit $iLimit";
656                                                                         if (CONST_Debug) var_dump($sSQL);
657                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
658                                                                 }
659                                                         }
660                                                         else
661                                                         {
662                                                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
663                                                                 $sSQL .= " and st_contains($sViewboxSmallSQL, centroid)";
664                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
665                                                                 $sSQL .= " limit $iLimit";
666                                                                 if (CONST_Debug) var_dump($sSQL);
667                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
668                                                         }
669                                                         }
670                                                 }
671                                                 else
672                                                 {
673                                                         if (CONST_Debug) var_dump('<hr>',$aSearch);
674                                                         if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);     
675                                                         $aPlaceIDs = array();
676                                                 
677                                                         // First we need a position, either aName or fLat or both
678                                                         $aTerms = array();
679                                                         $aOrder = array();
680                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
681                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
682                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
683                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank in (26,27)";
684                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
685                                                         {
686                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
687                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
688                                                         }
689                                                         if (sizeof($aExcludePlaceIDs))
690                                                         {
691                                                                 $aTerms[] = "place_id not in (".join(',',$aExcludePlaceIDs).")";
692                                                         }
693                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $sViewboxSmallSQL";
694                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
695                                                         if ($sViewboxSmallSQL) $aOrder[] = "ST_Contains($sViewboxSmallSQL, centroid) desc";
696                                                         if ($sViewboxLargeSQL) $aOrder[] = "ST_Contains($sViewboxLargeSQL, centroid) desc";
697                                                         $aOrder[] = "search_rank ASC";
698                                                 
699                                                         if (sizeof($aTerms))
700                                                         {
701                                                                 $sSQL = "select place_id";
702                                                                 if ($sViewboxSmallSQL) $sSQL .= ",ST_Contains($sViewboxSmallSQL, centroid) as in_small";
703                                                                 else $sSQL .= ",false as in_small";
704                                                                 if ($sViewboxLargeSQL) $sSQL .= ",ST_Contains($sViewboxLargeSQL, centroid) as in_large";
705                                                                 else $sSQL .= ",false as in_large";
706                                                                 $sSQL .= " from search_name";
707                                                                 $sSQL .= " where ".join(' and ',$aTerms);
708                                                                 $sSQL .= " order by ".join(', ',$aOrder);
709                                                                 if ($aSearch['sHouseNumber'])
710                                                                         $sSQL .= " limit 50";
711                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
712                                                                         $sSQL .= " limit 1";
713                                                                 else
714                                                                         $sSQL .= " limit ".$iLimit;
715
716                                                                 if (CONST_Debug) var_dump($sSQL);
717                                                                 $aViewBoxPlaceIDs = $oDB->getAll($sSQL);
718                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
719                                                                 {
720                                                                         var_dump($sSQL, $aViewBoxPlaceIDs);                                     
721                                                                         exit;
722                                                                 }
723
724                                                                 // Did we have an viewbox matches?
725                                                                 $aPlaceIDs = array();
726                                                                 $bViewBoxMatch = false;
727                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
728                                                                 {
729                                                                         if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
730                                                                         if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
731                                                                         if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
732                                                                         else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
733                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
734                                                                 }
735                                                         }
736
737                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
738                                                         {
739                                                                 $aRoadPlaceIDs = $aPlaceIDs;
740                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
741         
742                                                                 // Now they are indexed look for a house attached to a street we found
743                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-, ]',$aSearch['sHouseNumber']).'\\\\M';                                         
744                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
745                                                                 if (sizeof($aExcludePlaceIDs))
746                                                                 {
747                                                                         $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
748                                                                 }
749                                                                 $sSQL .= " limit $iLimit";
750                                                                 if (CONST_Debug) var_dump($sSQL);
751                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
752
753                                                                 // If not try the aux fallback table
754                                                                 if (!sizeof($aPlaceIDs))
755                                                                 {
756                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
757                                                                         if (sizeof($aExcludePlaceIDs))
758                                                                         {
759                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
760                                                                         }
761 //                                                                      $sSQL .= " limit $iLimit";
762                                                                         if (CONST_Debug) var_dump($sSQL);
763                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
764                                                                 }
765
766                                                                 if (!sizeof($aPlaceIDs))
767                                                                 {
768                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
769                                                                         if (sizeof($aExcludePlaceIDs))
770                                                                         {
771                                                                                 $sSQL .= " and place_id not in (".join(',',$aExcludePlaceIDs).")";
772                                                                         }
773 //                                                                      $sSQL .= " limit $iLimit";
774                                                                         if (CONST_Debug) var_dump($sSQL);
775                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
776                                                                 }
777
778                                                                 // Fallback to the road
779                                                                 if (!sizeof($aPlaceIDs))
780                                                                 {
781                                                                         $aPlaceIDs = $aRoadPlaceIDs;
782                                                                 }
783                                                                 
784                                                         }
785                                                 
786                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
787                                                         {
788                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
789
790                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
791                                                                 {
792                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
793                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
794                                                                         $sSQL .= " order by rank_search asc limit $iLimit";
795                                                                         if (CONST_Debug) var_dump($sSQL);
796                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
797                                                                 }
798                                                                 
799                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
800                                                                 {
801                                                                         $sSQL = "select rank_search from placex where place_id in ($sPlaceIDs) order by rank_search asc limit 1";
802                                                                         if (CONST_Debug) var_dump($sSQL);
803                                                                         $iMaxRank = ((int)$oDB->getOne($sSQL)) + 5;
804
805                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
806                                                                         if (CONST_Debug) var_dump($sSQL);
807                                                                         $aPlaceIDs = $oDB->getCol($sSQL);
808                                                                         $sPlaceIDs = join(',',$aPlaceIDs);
809
810                                                                         $fRange = 0.01;
811                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
812                                                                         if ($oDB->getOne($sSQL))
813                                                                         {
814                                                                                 // More efficient - can make the range bigger
815                                                                         $fRange = 0.05;
816                                                                                 $sSQL = "select l.place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
817                                                                                 $sSQL .= ",placex as f where ";
818                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, st_centroid(f.geometry), $fRange) ";
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.centroid) ASC";
824                                                                                 else $sSQL .= " order by ST_Distance(l.centroid, f.geometry) asc";
825                                                                                 $sSQL .= " limit $iLimit";
826                                                                                 if (CONST_Debug) var_dump($sSQL);
827                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
828                                                                         }
829                                                                         else
830                                                                         {
831                                                                                 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
832                                                                                 $sSQL = "select l.place_id from placex as l,placex as f where ";
833                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.geometry, st_centroid(f.geometry), $fRange) ";
834                                                                                 $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
835                                                                                 if (sizeof($aExcludePlaceIDs))
836                                                                                 {
837                                                                                         $sSQL .= " and l.place_id not in (".join(',',$aExcludePlaceIDs).")";
838                                                                                 }
839                                                                                 if ($sNearPointSQL) $sSQL .= " order by ST_Distance($sNearPointSQL, l.geometry) ASC";
840                                                                                 else $sSQL .= " order by ST_Distance(l.geometry, f.geometry) asc, l.rank_search ASC";
841                                                                                 $sSQL .= " limit $iLimit";
842                                                                                 if (CONST_Debug) var_dump($sSQL);
843                                                                                 $aPlaceIDs = $oDB->getCol($sSQL);
844                                                                         }
845                                                                 }
846                                                         }
847                                                 
848                                                 }
849
850                                                 if (PEAR::IsError($aPlaceIDs))
851                                                 {
852                                                         var_dump($sSQL, $aPlaceIDs);                                    
853                                                         exit;
854                                                 }
855
856                                                 if (CONST_Debug) var_Dump($aPlaceIDs);
857
858                                                 foreach($aPlaceIDs as $iPlaceID)
859                                                 {
860                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
861                                                 }
862                                                 if ($iQueryLoop > 20) break;
863                                         }
864                                         //exit;
865                                         if (sizeof($aResultPlaceIDs)) break;
866                                         if ($iGroupLoop > 4) break;
867                                         if ($iQueryLoop > 30) break;
868                                 }
869 //exit;
870                                 // Did we find anything?        
871                                 if (sizeof($aResultPlaceIDs))
872                                 {
873 //var_Dump($aResultPlaceIDs);exit;
874                                         // Get the details for display (is this a redundant extra step?)
875                                         $sPlaceIDs = join(',',$aResultPlaceIDs);
876                                         $sOrderSQL = 'CASE ';
877                                         foreach(array_keys($aResultPlaceIDs) as $iOrder => $iPlaceID)
878                                         {
879                                                 $sOrderSQL .= 'when min(place_id) = '.$iPlaceID.' then '.$iOrder.' ';
880                                         }
881                                         $sOrderSQL .= ' ELSE 10000000 END';
882                                         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id,country_code,";
883                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
884                                         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
885                                         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
886                                         $sSQL .= "avg(ST_X(ST_Centroid(geometry))) as lon,avg(ST_Y(ST_Centroid(geometry))) as lat, ";
887                                         $sSQL .= $sOrderSQL." as porder ";
888                                         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
889                                         $sSQL .= "and placex.rank_address between $iMinAddressRank and $iMaxAddressRank ";
890                                         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,country_code";
891                                         if (!$bDeDupe) $sSQL .= ",place_id";
892                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
893                                         $sSQL .= ",get_name_by_language(name, $sLanguagePrefArraySQL) ";
894                                         $sSQL .= ",get_name_by_language(name, ARRAY['ref']) ";
895                                         $sSQL .= " union ";
896                                         $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,";
897                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
898                                         $sSQL .= "null as placename,";
899                                         $sSQL .= "null as ref,";
900                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
901                                         $sSQL .= $sOrderSQL." as porder ";
902                                         $sSQL .= "from location_property_tiger where place_id in ($sPlaceIDs) ";
903                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
904                                         $sSQL .= "group by place_id";
905                                         if (!$bDeDupe) $sSQL .= ",place_id";
906                                         $sSQL .= " union ";
907                                         $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,";
908                                         $sSQL .= "get_address_by_language(place_id, $sLanguagePrefArraySQL) as langaddress,";
909                                         $sSQL .= "null as placename,";
910                                         $sSQL .= "null as ref,";
911                                         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
912                                         $sSQL .= $sOrderSQL." as porder ";
913                                         $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
914                                         $sSQL .= "and 30 between $iMinAddressRank and $iMaxAddressRank ";
915                                         $sSQL .= "group by place_id";
916                                         if (!$bDeDupe) $sSQL .= ",place_id";
917                                         $sSQL .= ",get_address_by_language(place_id, $sLanguagePrefArraySQL) ";
918                                         $sSQL .= "order by rank_search,rank_address,porder asc";
919                                         if (CONST_Debug) var_dump('<hr>',$sSQL);
920                                         $aSearchResults = $oDB->getAll($sSQL);
921 //var_dump($sSQL,$aSearchResults);exit;
922
923                                         if (PEAR::IsError($aSearchResults))
924                                         {
925                                                 var_dump($sSQL, $aSearchResults);                                       
926                                                 exit;
927                                         }
928                                 }
929                         }
930                 }
931         
932         $sSearchResult = '';
933         if (!sizeof($aSearchResults) && isset($_GET['q']) && $_GET['q'])
934         {
935                 $sSearchResult = 'No Results Found';
936         }
937         
938         $aClassType = getClassTypesWithImportance();
939
940         foreach($aSearchResults as $iResNum => $aResult)
941         {
942                 if (CONST_Search_AreaPolygons || true)
943                 {
944                         // Get the bounding box and outline polygon
945                         $sSQL = "select place_id,numfeatures,area,outline,";
946                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(outline)),2)) as maxlat,";
947                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(outline)),3)) as maxlon,";
948                         $sSQL .= "ST_AsText(outline) as outlinestring from get_place_boundingbox_quick(".$aResult['place_id'].")";
949
950                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
951                         $sSQL .= "ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ExteriorRing(ST_Box2D(geometry)),2)) as maxlat,";
952                         $sSQL .= "ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ExteriorRing(ST_Box2D(geometry)),3)) as maxlon,";
953                         $sSQL .= "ST_AsText(geometry) as outlinestring from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(ST_Box2D(geometry)) = \'ST_Polygon\'';
954                         $aPointPolygon = $oDB->getRow($sSQL);
955                         if (PEAR::IsError($aPointPolygon))
956                         {
957                                 var_dump($sSQL, $aPointPolygon);
958                                 exit;
959                         }
960                         if ($aPointPolygon['place_id'])
961                         {
962                                 // Translate geometary string to point array
963                                 if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['outlinestring'],$aMatch))
964                                 {
965                                         preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
966                                 }
967                                 elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['outlinestring'],$aMatch))
968                                 {
969                                         $fRadius = 0.01;
970                                         $iSteps = ($fRadius * 40000)^2;
971                                         $fStepSize = (2*pi())/$iSteps;
972                                         $aPolyPoints = array();
973                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
974                                         {
975                                                 $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
976                                         }
977                                         $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
978                                         $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
979                                         $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
980                                         $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
981                                 }
982
983                                 // Output data suitable for display (points and a bounding box)
984                                 if ($bShowPolygons)
985                                 {
986                                         $aResult['aPolyPoints'] = array();
987                                         foreach($aPolyPoints as $aPoint)
988                                         {
989                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
990                                         }
991                                 }
992                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
993                         }
994                 }
995
996                 if (!isset($aResult['aBoundingBox']))
997                 {
998                         // Default
999                         $fDiameter = 0.0001;
1000
1001                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter']) 
1002                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1003                         {
1004                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1005                         }
1006                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter']) 
1007                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1008                         {
1009                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1010                         }
1011                         $fRadius = $fDiameter / 2;
1012
1013                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1014                         $fStepSize = (2*pi())/$iSteps;
1015                         $aPolyPoints = array();
1016                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1017                         {
1018                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1019                         }
1020                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1021                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1022                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1023                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1024
1025                         // Output data suitable for display (points and a bounding box)
1026                         if ($bShowPolygons)
1027                         {
1028                                 $aResult['aPolyPoints'] = array();
1029                                 foreach($aPolyPoints as $aPoint)
1030                                 {
1031                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1032                                 }
1033                         }
1034                         $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1035                 }
1036
1037                 // Is there an icon set for this type of result?
1038                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon']) 
1039                         && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1040                 {
1041                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1042                 }
1043
1044                 if ($bShowAddressDetails)
1045                 {
1046                         $aResult['address'] = getAddressDetails($oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1047 //var_dump($aResult['address']);
1048 //exit;
1049                 }
1050
1051 //if (CONST_Debug) var_dump($aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']);
1052
1053                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance']) 
1054                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'])
1055                 {
1056                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['importance'];
1057                 }
1058                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance']) 
1059                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1060                 {
1061                         $aResult['importance'] = $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1062                 }
1063                 else
1064                 {
1065                         $aResult['importance'] = 1000000000000000;
1066                 }
1067
1068                 $aResult['name'] = $aResult['langaddress'];
1069                 $aResult['foundorder'] = $iResNum;
1070                 $aSearchResults[$iResNum] = $aResult;
1071         }
1072
1073 //var_dump($aSearchResults);exit;
1074         
1075         uasort($aSearchResults, 'byImportance');
1076         
1077         $aOSMIDDone = array();
1078         $aClassTypeNameDone = array();
1079         $aToFilter = $aSearchResults;
1080         $aSearchResults = array();
1081
1082         $bFirst = true;
1083         foreach($aToFilter as $iResNum => $aResult)
1084         {
1085                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1086                 $aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1087                 if ($bFirst)
1088                 {
1089                         $fLat = $aResult['lat'];
1090                         $fLon = $aResult['lon'];
1091                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1092                         $bFirst = false;
1093                 }
1094                 if (!$bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1095                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']])))
1096                 {
1097                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1098                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['osm_class'].$aResult['name']] = true;
1099                         $aSearchResults[] = $aResult;
1100                 }
1101         }
1102
1103         $sDataDate = $oDB->getOne("select TO_CHAR(lastimportdate - '1 day'::interval,'YYYY/MM/DD') from import_status limit 1");
1104
1105         if (isset($_GET['nearlat']) && isset($_GET['nearlon']))
1106         {
1107                 $sQuery .= ' ['.$_GET['nearlat'].','.$_GET['nearlon'].']';
1108         }
1109
1110         if ($sQuery)
1111         {
1112                 logEnd($oDB, $hLog, sizeof($aToFilter));
1113         }
1114         $sMoreURL = CONST_Website_BaseURL.'search?format='.urlencode($sOutputFormat).'&exclude_place_ids='.join(',',$aExcludePlaceIDs);
1115         $sMoreURL .= '&accept-language='.$_SERVER["HTTP_ACCEPT_LANGUAGE"];
1116         if ($bShowPolygons) $sMoreURL .= '&polygon=1';
1117         if ($bShowAddressDetails) $sMoreURL .= '&addressdetails=1';
1118         if (isset($_GET['viewbox']) && $_GET['viewbox']) $sMoreURL .= '&viewbox='.urlencode($_GET['viewbox']);
1119         if (isset($_GET['nearlat']) && isset($_GET['nearlon'])) $sMoreURL .= '&nearlat='.(float)$_GET['nearlat'].'&nearlon='.(float)$_GET['nearlon'];
1120         if ($sSuggestion)
1121         {
1122                 $sSuggestionURL = $sMoreURL.'&q='.urlencode($sSuggestion);
1123         }
1124         $sMoreURL .= '&q='.urlencode($sQuery);
1125
1126         if (CONST_Debug) exit;
1127
1128         include(CONST_BasePath.'/lib/template/search-'.$sOutputFormat.'.php');