]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
check if query is valid unicode string
[nominatim.git] / lib / Geocode.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
6 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
7
8 class Geocode
9 {
10     protected $oDB;
11
12     protected $aLangPrefOrder = array();
13
14     protected $bIncludeAddressDetails = false;
15     protected $bIncludeExtraTags = false;
16     protected $bIncludeNameDetails = false;
17
18     protected $bIncludePolygonAsPoints = false;
19     protected $bIncludePolygonAsText = false;
20     protected $bIncludePolygonAsGeoJSON = false;
21     protected $bIncludePolygonAsKML = false;
22     protected $bIncludePolygonAsSVG = false;
23     protected $fPolygonSimplificationThreshold = 0.0;
24
25     protected $aExcludePlaceIDs = array();
26     protected $bDeDupe = true;
27     protected $bReverseInPlan = false;
28
29     protected $iLimit = 20;
30     protected $iFinalLimit = 10;
31     protected $iOffset = 0;
32     protected $bFallback = false;
33
34     protected $aCountryCodes = false;
35     protected $aNearPoint = false;
36
37     protected $bBoundedSearch = false;
38     protected $aViewBox = false;
39     protected $sViewboxCentreSQL = false;
40     protected $sViewboxSmallSQL = false;
41     protected $sViewboxLargeSQL = false;
42
43     protected $iMaxRank = 20;
44     protected $iMinAddressRank = 0;
45     protected $iMaxAddressRank = 30;
46     protected $aAddressRankList = array();
47     protected $exactMatchCache = array();
48
49     protected $sAllowedTypesSQLList = false;
50
51     protected $sQuery = false;
52     protected $aStructuredQuery = false;
53
54
55     public function __construct(&$oDB)
56     {
57         $this->oDB =& $oDB;
58     }
59
60     public function setReverseInPlan($bReverse)
61     {
62         $this->bReverseInPlan = $bReverse;
63     }
64
65     public function setLanguagePreference($aLangPref)
66     {
67         $this->aLangPrefOrder = $aLangPref;
68     }
69
70     public function getIncludeAddressDetails()
71     {
72         return $this->bIncludeAddressDetails;
73     }
74
75     public function getIncludeExtraTags()
76     {
77         return $this->bIncludeExtraTags;
78     }
79
80     public function getIncludeNameDetails()
81     {
82         return $this->bIncludeNameDetails;
83     }
84
85     public function setIncludePolygonAsPoints($b = true)
86     {
87         $this->bIncludePolygonAsPoints = $b;
88     }
89
90     public function setIncludePolygonAsText($b = true)
91     {
92         $this->bIncludePolygonAsText = $b;
93     }
94
95     public function setIncludePolygonAsGeoJSON($b = true)
96     {
97         $this->bIncludePolygonAsGeoJSON = $b;
98     }
99
100     public function setIncludePolygonAsKML($b = true)
101     {
102         $this->bIncludePolygonAsKML = $b;
103     }
104
105     public function setIncludePolygonAsSVG($b = true)
106     {
107         $this->bIncludePolygonAsSVG = $b;
108     }
109
110     public function setPolygonSimplificationThreshold($f)
111     {
112         $this->fPolygonSimplificationThreshold = $f;
113     }
114
115     public function setLimit($iLimit = 10)
116     {
117         if ($iLimit > 50) $iLimit = 50;
118         if ($iLimit < 1) $iLimit = 1;
119
120         $this->iFinalLimit = $iLimit;
121         $this->iLimit = $iLimit + min($iLimit, 10);
122     }
123
124     public function getExcludedPlaceIDs()
125     {
126         return $this->aExcludePlaceIDs;
127     }
128
129     public function getViewBoxString()
130     {
131         if (!$this->aViewBox) return null;
132         return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
133     }
134
135     public function setFeatureType($sFeatureType)
136     {
137         switch ($sFeatureType) {
138             case 'country':
139                 $this->setRankRange(4, 4);
140                 break;
141             case 'state':
142                 $this->setRankRange(8, 8);
143                 break;
144             case 'city':
145                 $this->setRankRange(14, 16);
146                 break;
147             case 'settlement':
148                 $this->setRankRange(8, 20);
149                 break;
150         }
151     }
152
153     public function setRankRange($iMin, $iMax)
154     {
155         $this->iMinAddressRank = $iMin;
156         $this->iMaxAddressRank = $iMax;
157     }
158
159     public function setRoute($aRoutePoints, $fRouteWidth)
160     {
161         $this->aViewBox = false;
162
163         $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
164         $sSep = '';
165         foreach ($aRoutePoints as $aPoint) {
166             $fPoint = (float)$aPoint;
167             $this->sViewboxCentreSQL .= $sSep.$fPoint;
168             $sSep = ($sSep == ' ') ? ',' : ' ';
169         }
170         $this->sViewboxCentreSQL .= ")'::geometry,4326)";
171
172         $this->sViewboxSmallSQL = 'st_buffer('.$this->sViewboxCentreSQL;
173         $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
174
175         $this->sViewboxLargeSQL = 'st_buffer('.$this->sViewboxCentreSQL;
176         $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
177     }
178
179     public function setViewbox($aViewbox)
180     {
181         $this->aViewBox = array_map('floatval', $aViewbox);
182
183         if ($this->aViewBox[0] < -180
184             || $this->aViewBox[2] > 180
185             || $this->aViewBox[0] >= $this->aViewBox[2]
186             || $this->aViewBox[1] < -90
187             || $this->aViewBox[3] > 90
188             || $this->aViewBox[1] >= $this->aViewBox[3]
189         ) {
190             userError("Bad parameter 'viewbox'. Out of range".$this->aViewBox[0]."|".$this->aViewBox[1]."|".$this->aViewBox[2]."|".$this->aViewBox[3]);
191         }
192
193         $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
194         $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
195         $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
196         $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
197         $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
198         $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
199
200         $this->sViewboxCentreSQL = false;
201         $this->sViewboxSmallSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$this->aViewBox[0].",".$this->aViewBox[1]."),ST_Point(".$this->aViewBox[2].",".$this->aViewBox[3].")),4326)";
202         $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".$aBigViewBox[0].",".$aBigViewBox[1]."),ST_Point(".$aBigViewBox[2].",".$aBigViewBox[3].")),4326)";
203     }
204
205     public function setNearPoint($aNearPoint, $fRadiusDeg = 0.1)
206     {
207         $this->aNearPoint = array((float)$aNearPoint[0], (float)$aNearPoint[1], (float)$fRadiusDeg);
208     }
209
210     public function setQuery($sQueryString)
211     {
212         $this->sQuery = $sQueryString;
213         $this->aStructuredQuery = false;
214     }
215
216     public function getQueryString()
217     {
218         return $this->sQuery;
219     }
220
221
222     public function loadParamArray($oParams)
223     {
224         $this->bIncludeAddressDetails
225          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
226         $this->bIncludeExtraTags
227          = $oParams->getBool('extratags', $this->bIncludeExtraTags);
228         $this->bIncludeNameDetails
229          = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
230
231         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
232         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
233
234         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
235         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
236
237         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
238
239         // List of excluded Place IDs - used for more acurate pageing
240         $sExcluded = $oParams->getStringList('exclude_place_ids');
241         if ($sExcluded) {
242             foreach ($sExcluded as $iExcludedPlaceID) {
243                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
244                 if ($iExcludedPlaceID)
245                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
246             }
247
248             if (isset($aExcludePlaceIDs))
249                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
250         }
251
252         // Only certain ranks of feature
253         $sFeatureType = $oParams->getString('featureType');
254         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
255         if ($sFeatureType) $this->setFeatureType($sFeatureType);
256
257         // Country code list
258         $sCountries = $oParams->getStringList('countrycodes');
259         if ($sCountries) {
260             foreach ($sCountries as $sCountryCode) {
261                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
262                     $aCountries[] = strtolower($sCountryCode);
263                 }
264             }
265             if (isset($aCountries))
266                 $this->aCountryCodes = $aCountries;
267         }
268
269         $aViewbox = $oParams->getStringList('viewboxlbrt');
270         if ($aViewbox) {
271             if (count($aViewbox) != 4) {
272                 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
273             }
274             $this->setViewbox($aViewbox);
275         } else {
276             $aViewbox = $oParams->getStringList('viewbox');
277             if ($aViewbox) {
278                 if (count($aViewbox) != 4) {
279                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
280                 }
281                 $this->setViewBox(array(
282                                    $aViewbox[0],
283                                    $aViewbox[3],
284                                    $aViewbox[2],
285                                    $aViewbox[1]
286                                   ));
287             } else {
288                 $aRoute = $oParams->getStringList('route');
289                 $fRouteWidth = $oParams->getFloat('routewidth');
290                 if ($aRoute && $fRouteWidth) {
291                     $this->setRoute($aRoute, $fRouteWidth);
292                 }
293             }
294         }
295     }
296
297     public function setQueryFromParams($oParams)
298     {
299         // Search query
300         $sQuery = $oParams->getString('q');
301         if (!$sQuery) {
302             $this->setStructuredQuery(
303                 $oParams->getString('amenity'),
304                 $oParams->getString('street'),
305                 $oParams->getString('city'),
306                 $oParams->getString('county'),
307                 $oParams->getString('state'),
308                 $oParams->getString('country'),
309                 $oParams->getString('postalcode')
310             );
311             $this->setReverseInPlan(false);
312         } else {
313             $this->setQuery($sQuery);
314         }
315     }
316
317     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
318     {
319         $sValue = trim($sValue);
320         if (!$sValue) return false;
321         $this->aStructuredQuery[$sKey] = $sValue;
322         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
323             $this->iMinAddressRank = $iNewMinAddressRank;
324             $this->iMaxAddressRank = $iNewMaxAddressRank;
325         }
326         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
327         return true;
328     }
329
330     public function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
331     {
332         $this->sQuery = false;
333
334         // Reset
335         $this->iMinAddressRank = 0;
336         $this->iMaxAddressRank = 30;
337         $this->aAddressRankList = array();
338
339         $this->aStructuredQuery = array();
340         $this->sAllowedTypesSQLList = '';
341
342         $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
343         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
344         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
345         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
346         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
347         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
348         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
349
350         if (sizeof($this->aStructuredQuery) > 0) {
351             $this->sQuery = join(', ', $this->aStructuredQuery);
352             if ($this->iMaxAddressRank < 30) {
353                 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
354             }
355         }
356     }
357
358     public function fallbackStructuredQuery()
359     {
360         if (!$this->aStructuredQuery) return false;
361
362         $aParams = $this->aStructuredQuery;
363
364         if (sizeof($aParams) == 1) return false;
365
366         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
367
368         foreach ($aOrderToFallback as $sType) {
369             if (isset($aParams[$sType])) {
370                 unset($aParams[$sType]);
371                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
372                 return true;
373             }
374         }
375
376         return false;
377     }
378
379     public function getDetails($aPlaceIDs)
380     {
381         //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
382         if (sizeof($aPlaceIDs) == 0) return array();
383
384         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
385
386         // Get the details for display (is this a redundant extra step?)
387         $sPlaceIDs = join(',', array_keys($aPlaceIDs));
388
389         $sImportanceSQL = '';
390         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
391         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " case when ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
392
393         $sSQL = "select osm_type,osm_id,class,type,admin_level,rank_search,rank_address,min(place_id) as place_id, min(parent_place_id) as parent_place_id, calculated_country_code as country_code,";
394         $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress,";
395         $sSQL .= "get_name_by_language(name, $sLanguagePrefArraySQL) as placename,";
396         $sSQL .= "get_name_by_language(name, ARRAY['ref']) as ref,";
397         if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text as extra,";
398         if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text as names,";
399         $sSQL .= "avg(ST_X(centroid)) as lon,avg(ST_Y(centroid)) as lat, ";
400         $sSQL .= $sImportanceSQL."coalesce(importance,0.75-(rank_search::float/40)) as importance, ";
401         $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
402         $sSQL .= "(extratags->'place') as extra_place ";
403         $sSQL .= "from placex where place_id in ($sPlaceIDs) ";
404         $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
405         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
406         if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
407         $sSQL .= ") ";
408         if ($this->sAllowedTypesSQLList) $sSQL .= "and placex.class in $this->sAllowedTypesSQLList ";
409         $sSQL .= "and linked_place_id is null ";
410         $sSQL .= "group by osm_type,osm_id,class,type,admin_level,rank_search,rank_address,calculated_country_code,importance";
411         if (!$this->bDeDupe) $sSQL .= ",place_id";
412         $sSQL .= ",langaddress ";
413         $sSQL .= ",placename ";
414         $sSQL .= ",ref ";
415         if ($this->bIncludeExtraTags) $sSQL .= ",extratags";
416         if ($this->bIncludeNameDetails) $sSQL .= ",name";
417         $sSQL .= ",extratags->'place' ";
418
419         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
420             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
421             // with start- and endnumber, the common osm housenumbers are usually saved as points
422             $sHousenumbers = "";
423             $i = 0;
424             $length = count($aPlaceIDs);
425             foreach ($aPlaceIDs as $placeID => $housenumber) {
426                 $i++;
427                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
428                 if ($i<$length) $sHousenumbers .= ", ";
429             }
430             if (CONST_Use_US_Tiger_Data) {
431                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
432                 $sSQL .= " union";
433                 $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, min(parent_place_id) as parent_place_id, 'us' as country_code";
434                 $sSQL .= ", get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress ";
435                 $sSQL .= ", null as placename";
436                 $sSQL .= ", null as ref";
437                 if ($this->bIncludeExtraTags) $sSQL .= ", null as extra";
438                 if ($this->bIncludeNameDetails) $sSQL .= ", null as names";
439                 $sSQL .= ", avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
440                 $sSQL .= $sImportanceSQL."-1.15 as importance ";
441                 $sSQL .= ", (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance ";
442                 $sSQL .= ", null as extra_place ";
443                 $sSQL .= " from (select place_id";
444                 // interpolate the Tiger housenumbers here
445                 $sSQL .= ", ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) as centroid, parent_place_id, housenumber_for_place";
446                 $sSQL .= " from (location_property_tiger ";
447                 $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
448                 $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
449                 $sSQL .= " group by place_id, housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
450                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
451             }
452             // osmline
453             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
454             $sSQL .= " union ";
455             $sSQL .= "select 'W' 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, min(parent_place_id) as parent_place_id, calculated_country_code as country_code, ";
456             $sSQL .= "get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) as langaddress, ";
457             $sSQL .= "null as placename, ";
458             $sSQL .= "null as ref, ";
459             if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
460             if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
461             $sSQL .= " avg(st_x(centroid)) as lon, avg(st_y(centroid)) as lat,";
462             $sSQL .= $sImportanceSQL."-0.1 as importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
463             $sSQL .= " (select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p";
464             $sSQL .= " where s.place_id = min(blub.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance,";
465             $sSQL .= " null as extra_place ";
466             $sSQL .= " from (select place_id, calculated_country_code ";
467             // interpolate the housenumbers here
468             $sSQL .= ", CASE WHEN startnumber != endnumber THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
469             $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) END as centroid";
470             $sSQL .= ", parent_place_id, housenumber_for_place ";
471             $sSQL .= " from (location_property_osmline ";
472             $sSQL .= " join (values ".$sHousenumbers.") as housenumbers(place_id, housenumber_for_place) using(place_id)) ";
473             $sSQL .= " where housenumber_for_place>=0 and 30 between $this->iMinAddressRank and $this->iMaxAddressRank) as blub"; //postgres wants an alias here
474             $sSQL .= " group by place_id, housenumber_for_place, calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
475             if (!$this->bDeDupe) $sSQL .= ", place_id ";
476
477             if (CONST_Use_Aux_Location_data) {
478                 $sSQL .= " union ";
479                 $sSQL .= "select 'L' as osm_type, place_id as osm_id, 'place' as class, 'house' as type, null as admin_level, 0 as rank_search, 0 as rank_address, min(place_id) as place_id, min(parent_place_id) as parent_place_id, 'us' as country_code, ";
480                 $sSQL .= "get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) as langaddress, ";
481                 $sSQL .= "null as placename, ";
482                 $sSQL .= "null as ref, ";
483                 if ($this->bIncludeExtraTags) $sSQL .= "null as extra, ";
484                 if ($this->bIncludeNameDetails) $sSQL .= "null as names, ";
485                 $sSQL .= "avg(ST_X(centroid)) as lon, avg(ST_Y(centroid)) as lat, ";
486                 $sSQL .= $sImportanceSQL."-1.10 as importance, ";
487                 $sSQL .= "(select max(p.importance*(p.rank_address+2)) from place_addressline s, placex p where s.place_id = min(location_property_aux.parent_place_id) and p.place_id = s.address_place_id and s.isaddress and p.importance is not null) as addressimportance, ";
488                 $sSQL .= "null as extra_place ";
489                 $sSQL .= "from location_property_aux where place_id in ($sPlaceIDs) ";
490                 $sSQL .= "and 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
491                 $sSQL .= "group by place_id";
492                 if (!$this->bDeDupe) $sSQL .= ", place_id";
493                 $sSQL .= ", get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
494             }
495         }
496
497         $sSQL .= " order by importance desc";
498         if (CONST_Debug) {
499             echo "<hr>";
500             var_dump($sSQL);
501         }
502         $aSearchResults = chksql(
503             $this->oDB->getAll($sSQL),
504             "Could not get details for place."
505         );
506
507         return $aSearchResults;
508     }
509
510     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
511     {
512         /*
513              Calculate all searches using aValidTokens i.e.
514              'Wodsworth Road, Sheffield' =>
515
516              Phrase Wordset
517              0      0       (wodsworth road)
518              0      1       (wodsworth)(road)
519              1      0       (sheffield)
520
521              Score how good the search is so they can be ordered
522          */
523         foreach ($aPhrases as $iPhrase => $sPhrase) {
524             $aNewPhraseSearches = array();
525             if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
526             else $sPhraseType = '';
527
528             foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
529                 // Too many permutations - too expensive
530                 if ($iWordSet > 120) break;
531
532                 $aWordsetSearches = $aSearches;
533
534                 // Add all words from this wordset
535                 foreach ($aWordset as $iToken => $sToken) {
536                     //echo "<br><b>$sToken</b>";
537                     $aNewWordsetSearches = array();
538
539                     foreach ($aWordsetSearches as $aCurrentSearch) {
540                         //echo "<i>";
541                         //var_dump($aCurrentSearch);
542                         //echo "</i>";
543
544                         // If the token is valid
545                         if (isset($aValidTokens[' '.$sToken])) {
546                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
547                                 $aSearch = $aCurrentSearch;
548                                 $aSearch['iSearchRank']++;
549                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
550                                     if ($aSearch['sCountryCode'] === false) {
551                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
552                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
553                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
554                                             $aSearch['iSearchRank'] += 5;
555                                         }
556                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
557                                     }
558                                 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
559                                     if ($aSearch['fLat'] === '') {
560                                         $aSearch['fLat'] = $aSearchTerm['lat'];
561                                         $aSearch['fLon'] = $aSearchTerm['lon'];
562                                         $aSearch['fRadius'] = $aSearchTerm['radius'];
563                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
564                                     }
565                                 } elseif ($sPhraseType == 'postalcode') {
566                                     // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
567                                     if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
568                                         // If we already have a name try putting the postcode first
569                                         if (sizeof($aSearch['aName'])) {
570                                             $aNewSearch = $aSearch;
571                                             $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
572                                             $aNewSearch['aName'] = array();
573                                             $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
574                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
575                                         }
576
577                                         if (sizeof($aSearch['aName'])) {
578                                             if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
579                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
580                                             } else {
581                                                 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
582                                                 $aSearch['iSearchRank'] += 1000; // skip;
583                                             }
584                                         } else {
585                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
586                                             //$aSearch['iNamePhrase'] = $iPhrase;
587                                         }
588                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
589                                     }
590                                 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
591                                     if ($aSearch['sHouseNumber'] === '') {
592                                         $aSearch['sHouseNumber'] = $sToken;
593                                         // sanity check: if the housenumber is not mainly made
594                                         // up of numbers, add a penalty
595                                         if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
596                                         // also housenumbers should appear in the first or second phrase
597                                         if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
598                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
599                                         /*
600                                         // Fall back to not searching for this item (better than nothing)
601                                         $aSearch = $aCurrentSearch;
602                                         $aSearch['iSearchRank'] += 1;
603                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
604                                          */
605                                     }
606                                 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
607                                     if ($aSearch['sClass'] === '') {
608                                         $aSearch['sOperator'] = $aSearchTerm['operator'];
609                                         $aSearch['sClass'] = $aSearchTerm['class'];
610                                         $aSearch['sType'] = $aSearchTerm['type'];
611                                         if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
612                                         else $aSearch['sOperator'] = 'near'; // near = in for the moment
613                                         if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
614
615                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
616                                     }
617                                 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
618                                     if (sizeof($aSearch['aName'])) {
619                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
620                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
621                                         } else {
622                                             $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
623                                             $aSearch['iSearchRank'] += 1000; // skip;
624                                         }
625                                     } else {
626                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
627                                         //$aSearch['iNamePhrase'] = $iPhrase;
628                                     }
629                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
630                                 }
631                             }
632                         }
633                         // Look for partial matches.
634                         // Note that there is no point in adding country terms here
635                         // because country are omitted in the address.
636                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
637                             // Allow searching for a word - but at extra cost
638                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
639                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
640                                     if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
641                                         $aSearch = $aCurrentSearch;
642                                         $aSearch['iSearchRank'] += 1;
643                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
644                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
645                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
646                                         } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
647                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
648                                             $aSearch['iSearchRank'] += 1;
649                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
650                                             foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
651                                                 if (empty($aSearchTermToken['country_code'])
652                                                     && empty($aSearchTermToken['lat'])
653                                                     && empty($aSearchTermToken['class'])
654                                                 ) {
655                                                     $aSearch = $aCurrentSearch;
656                                                     $aSearch['iSearchRank'] += 1;
657                                                     $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
658                                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
659                                                 }
660                                             }
661                                         } else {
662                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
663                                             if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
664                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
665                                         }
666                                     }
667
668                                     if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
669                                         $aSearch = $aCurrentSearch;
670                                         $aSearch['iSearchRank'] += 1;
671                                         if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
672                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
673                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
674                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
675                                         } else {
676                                             $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
677                                         }
678                                         $aSearch['iNamePhrase'] = $iPhrase;
679                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
680                                     }
681                                 }
682                             }
683                         } else {
684                             // Allow skipping a word - but at EXTREAM cost
685                             //$aSearch = $aCurrentSearch;
686                             //$aSearch['iSearchRank']+=100;
687                             //$aNewWordsetSearches[] = $aSearch;
688                         }
689                     }
690                     // Sort and cut
691                     usort($aNewWordsetSearches, 'bySearchRank');
692                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
693                 }
694                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
695
696                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
697                 usort($aNewPhraseSearches, 'bySearchRank');
698
699                 $aSearchHash = array();
700                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
701                     $sHash = serialize($aSearch);
702                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
703                     else $aSearchHash[$sHash] = 1;
704                 }
705
706                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
707             }
708
709             // Re-group the searches by their score, junk anything over 20 as just not worth trying
710             $aGroupedSearches = array();
711             foreach ($aNewPhraseSearches as $aSearch) {
712                 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
713                     if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
714                     $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
715                 }
716             }
717             ksort($aGroupedSearches);
718
719             $iSearchCount = 0;
720             $aSearches = array();
721             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
722                 $iSearchCount += sizeof($aNewSearches);
723                 $aSearches = array_merge($aSearches, $aNewSearches);
724                 if ($iSearchCount > 50) break;
725             }
726
727             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
728         }
729         return $aGroupedSearches;
730     }
731
732     /* Perform the actual query lookup.
733
734         Returns an ordered list of results, each with the following fields:
735             osm_type: type of corresponding OSM object
736                         N - node
737                         W - way
738                         R - relation
739                         P - postcode (internally computed)
740             osm_id: id of corresponding OSM object
741             class: general object class (corresponds to tag key of primary OSM tag)
742             type: subclass of object (corresponds to tag value of primary OSM tag)
743             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
744             rank_search: rank in search hierarchy
745                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
746             rank_address: rank in address hierarchy (determines orer in address)
747             place_id: internal key (may differ between different instances)
748             country_code: ISO country code
749             langaddress: localized full address
750             placename: localized name of object
751             ref: content of ref tag (if available)
752             lon: longitude
753             lat: latitude
754             importance: importance of place based on Wikipedia link count
755             addressimportance: cumulated importance of address elements
756             extra_place: type of place (for admin boundaries, if there is a place tag)
757             aBoundingBox: bounding Box
758             label: short description of the object class/type (English only)
759             name: full name (currently the same as langaddress)
760             foundorder: secondary ordering for places with same importance
761     */
762
763
764     public function lookup()
765     {
766         if (!$this->sQuery && !$this->aStructuredQuery) return false;
767
768         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
769         $sCountryCodesSQL = false;
770         if ($this->aCountryCodes) {
771             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
772         }
773
774         $sQuery = $this->sQuery;
775         if (!preg_match('//u', $sQuery)) {
776             userError("Query string is not UTF-8 encoded.");
777         }
778
779         // Conflicts between US state abreviations and various words for 'the' in different languages
780         if (isset($this->aLangPrefOrder['name:en'])) {
781             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
782             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
783             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
784         }
785
786         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
787         if ($this->sViewboxCentreSQL) {
788             // For complex viewboxes (routes) precompute the bounding geometry
789             $sGeom = chksql(
790                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
791                 "Could not get small viewbox"
792             );
793             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
794
795             $sGeom = chksql(
796                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
797                 "Could not get large viewbox"
798             );
799             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
800         }
801
802         // Do we have anything that looks like a lat/lon pair?
803         if ($aLooksLike = looksLikeLatLonPair($sQuery)) {
804             $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
805             $sQuery = $aLooksLike['query'];
806         }
807
808         $aSearchResults = array();
809         if ($sQuery || $this->aStructuredQuery) {
810             // Start with a blank search
811             $aSearches = array(
812                           array(
813                            'iSearchRank' => 0,
814                            'iNamePhrase' => -1,
815                            'sCountryCode' => false,
816                            'aName' => array(),
817                            'aAddress' => array(),
818                            'aFullNameAddress' => array(),
819                            'aNameNonSearch' => array(),
820                            'aAddressNonSearch' => array(),
821                            'sOperator' => '',
822                            'aFeatureName' => array(),
823                            'sClass' => '',
824                            'sType' => '',
825                            'sHouseNumber' => '',
826                            'fLat' => '',
827                            'fLon' => '',
828                            'fRadius' => ''
829                           )
830                          );
831
832             // Do we have a radius search?
833             $sNearPointSQL = false;
834             if ($this->aNearPoint) {
835                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
836                 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
837                 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
838                 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
839             }
840
841             // Any 'special' terms in the search?
842             $bSpecialTerms = false;
843             preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
844             $aSpecialTerms = array();
845             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
846                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
847                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
848             }
849
850             preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
851             $aSpecialTerms = array();
852             if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
853                 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
854                 unset($this->aStructuredQuery['amenity']);
855             }
856
857             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
858                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
859                 $sToken = chksql($this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string"));
860                 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
861                 $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';
862                 if (CONST_Debug) var_Dump($sSQL);
863                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
864                 $aNewSearches = array();
865                 foreach ($aSearches as $aSearch) {
866                     foreach ($aSearchWords as $aSearchTerm) {
867                         $aNewSearch = $aSearch;
868                         if ($aSearchTerm['country_code']) {
869                             $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
870                             $aNewSearches[] = $aNewSearch;
871                             $bSpecialTerms = true;
872                         }
873                         if ($aSearchTerm['class']) {
874                             $aNewSearch['sClass'] = $aSearchTerm['class'];
875                             $aNewSearch['sType'] = $aSearchTerm['type'];
876                             $aNewSearches[] = $aNewSearch;
877                             $bSpecialTerms = true;
878                         }
879                     }
880                 }
881                 $aSearches = $aNewSearches;
882             }
883
884             // Split query into phrases
885             // Commas are used to reduce the search space by indicating where phrases split
886             if ($this->aStructuredQuery) {
887                 $aPhrases = $this->aStructuredQuery;
888                 $bStructuredPhrases = true;
889             } else {
890                 $aPhrases = explode(',', $sQuery);
891                 $bStructuredPhrases = false;
892             }
893
894             // Convert each phrase to standard form
895             // Create a list of standard words
896             // Get all 'sets' of words
897             // Generate a complete list of all
898             $aTokens = array();
899             foreach ($aPhrases as $iPhrase => $sPhrase) {
900                 $aPhrase = chksql(
901                     $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"),
902                     "Cannot normalize query string (is it a UTF-8 string?)"
903                 );
904                 if (trim($aPhrase['string'])) {
905                     $aPhrases[$iPhrase] = $aPhrase;
906                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
907                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
908                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
909                 } else {
910                     unset($aPhrases[$iPhrase]);
911                 }
912             }
913
914             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
915             $aPhraseTypes = array_keys($aPhrases);
916             $aPhrases = array_values($aPhrases);
917
918             if (sizeof($aTokens)) {
919                 // Check which tokens we have, get the ID numbers
920                 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
921                 $sSQL .= ' from word where word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
922
923                 if (CONST_Debug) var_Dump($sSQL);
924
925                 $aValidTokens = array();
926                 if (sizeof($aTokens)) {
927                     $aDatabaseWords = chksql(
928                         $this->oDB->getAll($sSQL),
929                         "Could not get word tokens."
930                     );
931                 } else {
932                     $aDatabaseWords = array();
933                 }
934                 $aPossibleMainWordIDs = array();
935                 $aWordFrequencyScores = array();
936                 foreach ($aDatabaseWords as $aToken) {
937                     // Very special case - require 2 letter country param to match the country code found
938                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
939                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
940                     ) {
941                         continue;
942                     }
943
944                     if (isset($aValidTokens[$aToken['word_token']])) {
945                         $aValidTokens[$aToken['word_token']][] = $aToken;
946                     } else {
947                         $aValidTokens[$aToken['word_token']] = array($aToken);
948                     }
949                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
950                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
951                 }
952                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
953
954                 // Try and calculate GB postcodes we might be missing
955                 foreach ($aTokens as $sToken) {
956                     // Source of gb postcodes is now definitive - always use
957                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
958                         if (substr($aData[1], -2, 1) != ' ') {
959                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
960                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
961                         }
962                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
963                         if ($aGBPostcodeLocation) {
964                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
965                         }
966                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
967                         // US ZIP+4 codes - if there is no token,
968                         // merge in the 5-digit ZIP code
969                         if (isset($aValidTokens[$aData[1]])) {
970                             foreach ($aValidTokens[$aData[1]] as $aToken) {
971                                 if (!$aToken['class']) {
972                                     if (isset($aValidTokens[$sToken])) {
973                                         $aValidTokens[$sToken][] = $aToken;
974                                     } else {
975                                         $aValidTokens[$sToken] = array($aToken);
976                                     }
977                                 }
978                             }
979                         }
980                     }
981                 }
982
983                 foreach ($aTokens as $sToken) {
984                     // Unknown single word token with a number - assume it is a house number
985                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
986                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
987                     }
988                 }
989
990                 // Any words that have failed completely?
991                 // TODO: suggestions
992
993                 // Start the search process
994                 // array with: placeid => -1 | tiger-housenumber
995                 $aResultPlaceIDs = array();
996
997                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
998
999                 if ($this->bReverseInPlan) {
1000                     // Reverse phrase array and also reverse the order of the wordsets in
1001                     // the first and final phrase. Don't bother about phrases in the middle
1002                     // because order in the address doesn't matter.
1003                     $aPhrases = array_reverse($aPhrases);
1004                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1005                     if (sizeof($aPhrases) > 1) {
1006                         $aFinalPhrase = end($aPhrases);
1007                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1008                     }
1009                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1010
1011                     foreach ($aGroupedSearches as $aSearches) {
1012                         foreach ($aSearches as $aSearch) {
1013                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1014                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1015                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1016                             }
1017                         }
1018                     }
1019
1020                     $aGroupedSearches = $aReverseGroupedSearches;
1021                     ksort($aGroupedSearches);
1022                 }
1023             } else {
1024                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1025                 $aGroupedSearches = array();
1026                 foreach ($aSearches as $aSearch) {
1027                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1028                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1029                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1030                     }
1031                 }
1032                 ksort($aGroupedSearches);
1033             }
1034
1035             if (CONST_Debug) var_Dump($aGroupedSearches);
1036             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1037                 $aCopyGroupedSearches = $aGroupedSearches;
1038                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1039                     foreach ($aSearches as $iSearch => $aSearch) {
1040                         $aReductionsList = array($aSearch['aAddress']);
1041                         $iSearchRank = $aSearch['iSearchRank'];
1042                         while (sizeof($aReductionsList) > 0) {
1043                             $iSearchRank += 5;
1044                             if ($iSearchRank > iMaxRank) break 3;
1045                             $aNewReductionsList = array();
1046                             foreach ($aReductionsList as $aReductionsWordList) {
1047                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1048                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1049                                     $aReverseSearch = $aSearch;
1050                                     $aSearch['aAddress'] = $aReductionsWordListResult;
1051                                     $aSearch['iSearchRank'] = $iSearchRank;
1052                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1053                                     if (sizeof($aReductionsWordListResult) > 0) {
1054                                         $aNewReductionsList[] = $aReductionsWordListResult;
1055                                     }
1056                                 }
1057                             }
1058                             $aReductionsList = $aNewReductionsList;
1059                         }
1060                     }
1061                 }
1062                 ksort($aGroupedSearches);
1063             }
1064
1065             // Filter out duplicate searches
1066             $aSearchHash = array();
1067             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1068                 foreach ($aSearches as $iSearch => $aSearch) {
1069                     $sHash = serialize($aSearch);
1070                     if (isset($aSearchHash[$sHash])) {
1071                         unset($aGroupedSearches[$iGroup][$iSearch]);
1072                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1073                     } else {
1074                         $aSearchHash[$sHash] = 1;
1075                     }
1076                 }
1077             }
1078
1079             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1080
1081             $iGroupLoop = 0;
1082             $iQueryLoop = 0;
1083             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1084                 $iGroupLoop++;
1085                 foreach ($aSearches as $aSearch) {
1086                     $iQueryLoop++;
1087                     $searchedHousenumber = -1;
1088
1089                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1090                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1091
1092                     // No location term?
1093                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
1094                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1095                             // Just looking for a country by code - look it up
1096                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1097                                 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1098                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1099                                 if ($bBoundingBoxSearch)
1100                                     $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1101                                 $sSQL .= " order by st_area(geometry) desc limit 1";
1102                                 if (CONST_Debug) var_dump($sSQL);
1103                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1104                             } else {
1105                                 $aPlaceIDs = array();
1106                             }
1107                         } else {
1108                             if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1109                             if (!$aSearch['sClass']) continue;
1110
1111                             $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1112                             if (chksql($this->oDB->getOne($sSQL))) {
1113                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1114                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1115                                 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1116                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1117                                 if (sizeof($this->aExcludePlaceIDs)) {
1118                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1119                                 }
1120                                 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1121                                 $sSQL .= " limit $this->iLimit";
1122                                 if (CONST_Debug) var_dump($sSQL);
1123                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1124
1125                                 // If excluded place IDs are given, it is fair to assume that
1126                                 // there have been results in the small box, so no further
1127                                 // expansion in that case.
1128                                 // Also don't expand if bounded results were requested.
1129                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1130                                     $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1131                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1132                                     $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1133                                     if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1134                                     if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1135                                     $sSQL .= " limit $this->iLimit";
1136                                     if (CONST_Debug) var_dump($sSQL);
1137                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1138                                 }
1139                             } else {
1140                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1141                                 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1142                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1143                                 if ($this->sViewboxCentreSQL)   $sSQL .= " order by st_distance($this->sViewboxCentreSQL, centroid) asc";
1144                                 $sSQL .= " limit $this->iLimit";
1145                                 if (CONST_Debug) var_dump($sSQL);
1146                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1147                             }
1148                         }
1149                     } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1150                         // If a coordinate is given, the search must either
1151                         // be for a name or a special search. Ignore everythin else.
1152                         $aPlaceIDs = array();
1153                     } else {
1154                         $aPlaceIDs = array();
1155
1156                         // First we need a position, either aName or fLat or both
1157                         $aTerms = array();
1158                         $aOrder = array();
1159
1160                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1161                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1162                             $aOrder[] = "";
1163                             $aOrder[0] = " (exists(select place_id from placex where parent_place_id = search_name.place_id";
1164                             $aOrder[0] .= " and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) ";
1165                             // also housenumbers from interpolation lines table are needed
1166                             $aOrder[0] .= " or exists(select place_id from location_property_osmline where parent_place_id = search_name.place_id";
1167                             $aOrder[0] .= " and ".intval($aSearch['sHouseNumber']).">=startnumber and ".intval($aSearch['sHouseNumber'])."<=endnumber limit 1))";
1168                             $aOrder[0] .= " desc";
1169                         }
1170
1171                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1172                         // they might be right - but they are just too darned expensive to run
1173                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1174                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1175                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1176                             // For infrequent name terms disable index usage for address
1177                             if (CONST_Search_NameOnlySearchFrequencyThreshold
1178                                 && sizeof($aSearch['aName']) == 1
1179                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1180                             ) {
1181                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1182                             } else {
1183                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1184                                 if (sizeof($aSearch['aAddressNonSearch'])) {
1185                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1186                                 }
1187                             }
1188                         }
1189                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1190                         if ($aSearch['sHouseNumber']) {
1191                             $aTerms[] = "address_rank between 16 and 27";
1192                         } else {
1193                             if ($this->iMinAddressRank > 0) {
1194                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1195                             }
1196                             if ($this->iMaxAddressRank < 30) {
1197                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1198                             }
1199                         }
1200                         if ($aSearch['fLon'] && $aSearch['fLat']) {
1201                             $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1202                             $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1203                         }
1204                         if (sizeof($this->aExcludePlaceIDs)) {
1205                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1206                         }
1207                         if ($sCountryCodesSQL) {
1208                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
1209                         }
1210
1211                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1212                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1213
1214                         if ($aSearch['sHouseNumber']) {
1215                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
1216                         } else {
1217                             $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1218                         }
1219                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1220                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1221
1222                         $aOrder[] = "$sImportanceSQL DESC";
1223                         if (sizeof($aSearch['aFullNameAddress'])) {
1224                             $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1225                             $aOrder[] = 'exactmatch DESC';
1226                         } else {
1227                             $sExactMatchSQL = '0::int as exactmatch';
1228                         }
1229
1230                         if (sizeof($aTerms)) {
1231                             $sSQL = "select place_id, ";
1232                             $sSQL .= $sExactMatchSQL;
1233                             $sSQL .= " from search_name";
1234                             $sSQL .= " where ".join(' and ', $aTerms);
1235                             $sSQL .= " order by ".join(', ', $aOrder);
1236                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1237                                 $sSQL .= " limit 20";
1238                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1239                                 $sSQL .= " limit 1";
1240                             } else {
1241                                 $sSQL .= " limit ".$this->iLimit;
1242                             }
1243
1244                             if (CONST_Debug) var_dump($sSQL);
1245                             $aViewBoxPlaceIDs = chksql(
1246                                 $this->oDB->getAll($sSQL),
1247                                 "Could not get places for search terms."
1248                             );
1249                             //var_dump($aViewBoxPlaceIDs);
1250                             // Did we have an viewbox matches?
1251                             $aPlaceIDs = array();
1252                             $bViewBoxMatch = false;
1253                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1254                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1255                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1256                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1257                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1258                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1259                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1260                             }
1261                         }
1262                         //var_Dump($aPlaceIDs);
1263                         //exit;
1264
1265                         //now search for housenumber, if housenumber provided
1266                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1267                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
1268                             $aRoadPlaceIDs = $aPlaceIDs;
1269                             $sPlaceIDs = join(',', $aPlaceIDs);
1270
1271                             // Now they are indexed, look for a house attached to a street we found
1272                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1273                             $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1274                             if (sizeof($this->aExcludePlaceIDs)) {
1275                                 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1276                             }
1277                             $sSQL .= " limit $this->iLimit";
1278                             if (CONST_Debug) var_dump($sSQL);
1279                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1280                             
1281                             // if nothing found, search in the interpolation line table
1282                             if (!sizeof($aPlaceIDs)) {
1283                                 // do we need to use transliteration and the regex for housenumbers???
1284                                 //new query for lines, not housenumbers anymore
1285                                 if ($searchedHousenumber%2 == 0) {
1286                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1287                                     $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1288                                 } else {
1289                                     //look for housenumber in streets with interpolationtype odd or all
1290                                     $sSQL = "select distinct place_id from location_property_osmline where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1291                                 }
1292
1293                                 if (sizeof($this->aExcludePlaceIDs)) {
1294                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1295                                 }
1296                                 //$sSQL .= " limit $this->iLimit";
1297                                 if (CONST_Debug) var_dump($sSQL);
1298                                 //get place IDs
1299                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1300                             }
1301                                 
1302                             // If nothing found try the aux fallback table
1303                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1304                                 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1305                                 if (sizeof($this->aExcludePlaceIDs)) {
1306                                     $sSQL .= " and parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1307                                 }
1308                                 //$sSQL .= " limit $this->iLimit";
1309                                 if (CONST_Debug) var_dump($sSQL);
1310                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1311                             }
1312
1313                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1314                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1315                                 //new query for lines, not housenumbers anymore
1316                                 if ($searchedHousenumber%2 == 0) {
1317                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1318                                     $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='even' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1319                                 } else {
1320                                     //look for housenumber in streets with interpolationtype odd or all
1321                                     $sSQL = "select distinct place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and (interpolationtype='odd' or interpolationtype='all') and ".$searchedHousenumber.">=startnumber and ".$searchedHousenumber."<=endnumber";
1322                                 }
1323
1324                                 if (sizeof($this->aExcludePlaceIDs)) {
1325                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1326                                 }
1327                                 //$sSQL .= " limit $this->iLimit";
1328                                 if (CONST_Debug) var_dump($sSQL);
1329                                 //get place IDs
1330                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1331                             }
1332
1333                             // Fallback to the road (if no housenumber was found)
1334                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1335                                 $aPlaceIDs = $aRoadPlaceIDs;
1336                                 //set to -1, if no housenumbers were found
1337                                 $searchedHousenumber = -1;
1338                             }
1339                             //else: housenumber was found, remains saved in searchedHousenumber
1340                         }
1341
1342
1343                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1344                             $sPlaceIDs = join(',', $aPlaceIDs);
1345                             $aClassPlaceIDs = array();
1346
1347                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1348                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1349                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1350                                 $sSQL .= " and linked_place_id is null";
1351                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1352                                 $sSQL .= " order by rank_search asc limit $this->iLimit";
1353                                 if (CONST_Debug) var_dump($sSQL);
1354                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1355                             }
1356
1357                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1358                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1359                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1360
1361                                 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1362
1363                                 if (CONST_Debug) var_dump($sSQL);
1364                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1365
1366                                 // For state / country level searches the normal radius search doesn't work very well
1367                                 $sPlaceGeom = false;
1368                                 if ($this->iMaxRank < 9 && $bCacheTable) {
1369                                     // Try and get a polygon to search in instead
1370                                     $sSQL = "select geometry from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank + 5 and st_geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon') order by rank_search asc limit 1";
1371                                     if (CONST_Debug) var_dump($sSQL);
1372                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1373                                 }
1374
1375                                 if ($sPlaceGeom) {
1376                                     $sPlaceIDs = false;
1377                                 } else {
1378                                     $this->iMaxRank += 5;
1379                                     $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1380                                     if (CONST_Debug) var_dump($sSQL);
1381                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1382                                     $sPlaceIDs = join(',', $aPlaceIDs);
1383                                 }
1384
1385                                 if ($sPlaceIDs || $sPlaceGeom) {
1386                                     $fRange = 0.01;
1387                                     if ($bCacheTable) {
1388                                         // More efficient - can make the range bigger
1389                                         $fRange = 0.05;
1390
1391                                         $sOrderBySQL = '';
1392                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1393                                         elseif ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1394                                         elseif ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1395
1396                                         $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1397                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1398                                         if ($sPlaceIDs) {
1399                                             $sSQL .= ",placex as f where ";
1400                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1401                                         }
1402                                         if ($sPlaceGeom) {
1403                                             $sSQL .= " where ";
1404                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1405                                         }
1406                                         if (sizeof($this->aExcludePlaceIDs)) {
1407                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1408                                         }
1409                                         if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1410                                         if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1411                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1412                                         $sSQL .= " limit $this->iLimit";
1413                                         if (CONST_Debug) var_dump($sSQL);
1414                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1415                                     } else {
1416                                         if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1417
1418                                         $sOrderBySQL = '';
1419                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1420                                         else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1421
1422                                         $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1423                                         $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1424                                         $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1425                                         if (sizeof($this->aExcludePlaceIDs)) {
1426                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1427                                         }
1428                                         if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1429                                         if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1430                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1431                                         $sSQL .= " limit $this->iLimit";
1432                                         if (CONST_Debug) var_dump($sSQL);
1433                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1434                                     }
1435                                 }
1436                             }
1437                             $aPlaceIDs = $aClassPlaceIDs;
1438                         }
1439                     }
1440
1441                     if (CONST_Debug) {
1442                         echo "<br><b>Place IDs:</b> ";
1443                         var_Dump($aPlaceIDs);
1444                     }
1445
1446                     foreach ($aPlaceIDs as $iPlaceID) {
1447                         // array for placeID => -1 | Tiger housenumber
1448                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1449                     }
1450                     if ($iQueryLoop > 20) break;
1451                 }
1452
1453                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1454                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1455                     // reduces the number of place ids, like a filter
1456                     // rank_address is 30 for interpolated housenumbers
1457                     $sSQL = "select place_id from placex where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1458                     $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1459                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1460                     if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1461                     if (CONST_Use_US_Tiger_Data) {
1462                         $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1463                         $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1464                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1465                     }
1466                     $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1467                     $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1468                     if (CONST_Debug) var_dump($sSQL);
1469                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1470                     $tempIDs = array();
1471                     foreach ($aFilteredPlaceIDs as $placeID) {
1472                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1473                     }
1474                     $aResultPlaceIDs = $tempIDs;
1475                 }
1476
1477                 //exit;
1478                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1479                 if ($iGroupLoop > 4) break;
1480                 if ($iQueryLoop > 30) break;
1481             }
1482
1483             // Did we find anything?
1484             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1485                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1486             }
1487         } else {
1488             // Just interpret as a reverse geocode
1489             $oReverse = new ReverseGeocode($this->oDB);
1490             $oReverse->setZoom(18);
1491
1492             $aLookup = $oReverse->lookup(
1493                 (float)$this->aNearPoint[0],
1494                 (float)$this->aNearPoint[1],
1495                 false
1496             );
1497
1498             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1499
1500             if ($aLookup['place_id']) {
1501                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1502                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1503             } else {
1504                 $aSearchResults = array();
1505             }
1506         }
1507
1508         // No results? Done
1509         if (!sizeof($aSearchResults)) {
1510             if ($this->bFallback) {
1511                 if ($this->fallbackStructuredQuery()) {
1512                     return $this->lookup();
1513                 }
1514             }
1515
1516             return array();
1517         }
1518
1519         $aClassType = getClassTypesWithImportance();
1520         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1521         foreach ($aRecheckWords as $i => $sWord) {
1522             if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1523         }
1524
1525         if (CONST_Debug) {
1526             echo '<i>Recheck words:<\i>';
1527             var_dump($aRecheckWords);
1528         }
1529
1530         $oPlaceLookup = new PlaceLookup($this->oDB);
1531         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1532         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1533         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1534         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1535         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1536         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1537
1538         foreach ($aSearchResults as $iResNum => $aResult) {
1539             // Default
1540             $fDiameter = getResultDiameter($aResult);
1541
1542             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1543             if ($aOutlineResult) {
1544                 $aResult = array_merge($aResult, $aOutlineResult);
1545             }
1546             
1547             if ($aResult['extra_place'] == 'city') {
1548                 $aResult['class'] = 'place';
1549                 $aResult['type'] = 'city';
1550                 $aResult['rank_search'] = 16;
1551             }
1552
1553             // Is there an icon set for this type of result?
1554             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1555                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1556             ) {
1557                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1558             }
1559
1560             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1561                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1562             ) {
1563                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1564             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1565                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1566             ) {
1567                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1568             }
1569             // if tag '&addressdetails=1' is set in query
1570             if ($this->bIncludeAddressDetails) {
1571                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1572                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1573                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1574                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1575                 }
1576             }
1577
1578             if ($this->bIncludeExtraTags) {
1579                 if ($aResult['extra']) {
1580                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1581                 } else {
1582                     $aResult['sExtraTags'] = (object) array();
1583                 }
1584             }
1585
1586             if ($this->bIncludeNameDetails) {
1587                 if ($aResult['names']) {
1588                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1589                 } else {
1590                     $aResult['sNameDetails'] = (object) array();
1591                 }
1592             }
1593
1594             // Adjust importance for the number of exact string matches in the result
1595             $aResult['importance'] = max(0.001, $aResult['importance']);
1596             $iCountWords = 0;
1597             $sAddress = $aResult['langaddress'];
1598             foreach ($aRecheckWords as $i => $sWord) {
1599                 if (stripos($sAddress, $sWord)!==false) {
1600                     $iCountWords++;
1601                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1602                 }
1603             }
1604
1605             $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
1606
1607             $aResult['name'] = $aResult['langaddress'];
1608             // secondary ordering (for results with same importance (the smaller the better):
1609             // - approximate importance of address parts
1610             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1611             // - number of exact matches from the query
1612             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1613                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1614             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1615                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1616             }
1617             // - importance of the class/type
1618             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1619                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1620             ) {
1621                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1622             } else {
1623                 $aResult['foundorder'] += 0.01;
1624             }
1625             if (CONST_Debug) var_dump($aResult);
1626             $aSearchResults[$iResNum] = $aResult;
1627         }
1628         uasort($aSearchResults, 'byImportance');
1629
1630         $aOSMIDDone = array();
1631         $aClassTypeNameDone = array();
1632         $aToFilter = $aSearchResults;
1633         $aSearchResults = array();
1634
1635         $bFirst = true;
1636         foreach ($aToFilter as $iResNum => $aResult) {
1637             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1638             if ($bFirst) {
1639                 $fLat = $aResult['lat'];
1640                 $fLon = $aResult['lon'];
1641                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1642                 $bFirst = false;
1643             }
1644             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1645                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1646             ) {
1647                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1648                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1649                 $aSearchResults[] = $aResult;
1650             }
1651
1652             // Absolute limit on number of results
1653             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1654         }
1655
1656         return $aSearchResults;
1657     } // end lookup()
1658 } // end class