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