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