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