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