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