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