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