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