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