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