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