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