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