]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
ae82498f2b847e35ab2da436377cb69d0f3857c7
[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
776         // Conflicts between US state abreviations and various words for 'the' in different languages
777         if (isset($this->aLangPrefOrder['name:en'])) {
778             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
779             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
780             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
781         }
782
783         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
784         if ($this->sViewboxCentreSQL) {
785             // For complex viewboxes (routes) precompute the bounding geometry
786             $sGeom = chksql(
787                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
788                 "Could not get small viewbox"
789             );
790             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
791
792             $sGeom = chksql(
793                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
794                 "Could not get large viewbox"
795             );
796             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
797         }
798
799         // Do we have anything that looks like a lat/lon pair?
800         if ($aLooksLike = looksLikeLatLonPair($sQuery)) {
801             $this->setNearPoint(array($aLooksLike['lat'], $aLooksLike['lon']));
802             $sQuery = $aLooksLike['query'];
803         }
804
805         $aSearchResults = array();
806         if ($sQuery || $this->aStructuredQuery) {
807             // Start with a blank search
808             $aSearches = array(
809                           array(
810                            'iSearchRank' => 0,
811                            'iNamePhrase' => -1,
812                            'sCountryCode' => false,
813                            'aName' => array(),
814                            'aAddress' => array(),
815                            'aFullNameAddress' => array(),
816                            'aNameNonSearch' => array(),
817                            'aAddressNonSearch' => array(),
818                            'sOperator' => '',
819                            'aFeatureName' => array(),
820                            'sClass' => '',
821                            'sType' => '',
822                            'sHouseNumber' => '',
823                            'fLat' => '',
824                            'fLon' => '',
825                            'fRadius' => ''
826                           )
827                          );
828
829             // Do we have a radius search?
830             $sNearPointSQL = false;
831             if ($this->aNearPoint) {
832                 $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
833                 $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
834                 $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
835                 $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
836             }
837
838             // Any 'special' terms in the search?
839             $bSpecialTerms = false;
840             preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
841             $aSpecialTerms = array();
842             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
843                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
844                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
845             }
846
847             preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
848             $aSpecialTerms = array();
849             if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
850                 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
851                 unset($this->aStructuredQuery['amenity']);
852             }
853
854             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
855                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
856                 $sToken = chksql($this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string"));
857                 $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
858                 $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';
859                 if (CONST_Debug) var_Dump($sSQL);
860                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
861                 $aNewSearches = array();
862                 foreach ($aSearches as $aSearch) {
863                     foreach ($aSearchWords as $aSearchTerm) {
864                         $aNewSearch = $aSearch;
865                         if ($aSearchTerm['country_code']) {
866                             $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
867                             $aNewSearches[] = $aNewSearch;
868                             $bSpecialTerms = true;
869                         }
870                         if ($aSearchTerm['class']) {
871                             $aNewSearch['sClass'] = $aSearchTerm['class'];
872                             $aNewSearch['sType'] = $aSearchTerm['type'];
873                             $aNewSearches[] = $aNewSearch;
874                             $bSpecialTerms = true;
875                         }
876                     }
877                 }
878                 $aSearches = $aNewSearches;
879             }
880
881             // Split query into phrases
882             // Commas are used to reduce the search space by indicating where phrases split
883             if ($this->aStructuredQuery) {
884                 $aPhrases = $this->aStructuredQuery;
885                 $bStructuredPhrases = true;
886             } else {
887                 $aPhrases = explode(',', $sQuery);
888                 $bStructuredPhrases = false;
889             }
890
891             // Convert each phrase to standard form
892             // Create a list of standard words
893             // Get all 'sets' of words
894             // Generate a complete list of all
895             $aTokens = array();
896             foreach ($aPhrases as $iPhrase => $sPhrase) {
897                 $aPhrase = chksql(
898                     $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string"),
899                     "Cannot normalize query string (is it a UTF-8 string?)"
900                 );
901                 if (trim($aPhrase['string'])) {
902                     $aPhrases[$iPhrase] = $aPhrase;
903                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
904                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
905                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
906                 } else {
907                     unset($aPhrases[$iPhrase]);
908                 }
909             }
910
911             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
912             $aPhraseTypes = array_keys($aPhrases);
913             $aPhrases = array_values($aPhrases);
914
915             if (sizeof($aTokens)) {
916                 // Check which tokens we have, get the ID numbers
917                 $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
918                 $sSQL .= ' from word where word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
919
920                 if (CONST_Debug) var_Dump($sSQL);
921
922                 $aValidTokens = array();
923                 if (sizeof($aTokens)) {
924                     $aDatabaseWords = chksql(
925                         $this->oDB->getAll($sSQL),
926                         "Could not get word tokens."
927                     );
928                 } else {
929                     $aDatabaseWords = array();
930                 }
931                 $aPossibleMainWordIDs = array();
932                 $aWordFrequencyScores = array();
933                 foreach ($aDatabaseWords as $aToken) {
934                     // Very special case - require 2 letter country param to match the country code found
935                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
936                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
937                     ) {
938                         continue;
939                     }
940
941                     if (isset($aValidTokens[$aToken['word_token']])) {
942                         $aValidTokens[$aToken['word_token']][] = $aToken;
943                     } else {
944                         $aValidTokens[$aToken['word_token']] = array($aToken);
945                     }
946                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
947                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
948                 }
949                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
950
951                 // Try and calculate GB postcodes we might be missing
952                 foreach ($aTokens as $sToken) {
953                     // Source of gb postcodes is now definitive - always use
954                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
955                         if (substr($aData[1], -2, 1) != ' ') {
956                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
957                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
958                         }
959                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
960                         if ($aGBPostcodeLocation) {
961                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
962                         }
963                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
964                         // US ZIP+4 codes - if there is no token,
965                         // merge in the 5-digit ZIP code
966                         if (isset($aValidTokens[$aData[1]])) {
967                             foreach ($aValidTokens[$aData[1]] as $aToken) {
968                                 if (!$aToken['class']) {
969                                     if (isset($aValidTokens[$sToken])) {
970                                         $aValidTokens[$sToken][] = $aToken;
971                                     } else {
972                                         $aValidTokens[$sToken] = array($aToken);
973                                     }
974                                 }
975                             }
976                         }
977                     }
978                 }
979
980                 foreach ($aTokens as $sToken) {
981                     // Unknown single word token with a number - assume it is a house number
982                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
983                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
984                     }
985                 }
986
987                 // Any words that have failed completely?
988                 // TODO: suggestions
989
990                 // Start the search process
991                 // array with: placeid => -1 | tiger-housenumber
992                 $aResultPlaceIDs = array();
993
994                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
995
996                 if ($this->bReverseInPlan) {
997                     // Reverse phrase array and also reverse the order of the wordsets in
998                     // the first and final phrase. Don't bother about phrases in the middle
999                     // because order in the address doesn't matter.
1000                     $aPhrases = array_reverse($aPhrases);
1001                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1002                     if (sizeof($aPhrases) > 1) {
1003                         $aFinalPhrase = end($aPhrases);
1004                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1005                     }
1006                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1007
1008                     foreach ($aGroupedSearches as $aSearches) {
1009                         foreach ($aSearches as $aSearch) {
1010                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1011                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1012                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1013                             }
1014                         }
1015                     }
1016
1017                     $aGroupedSearches = $aReverseGroupedSearches;
1018                     ksort($aGroupedSearches);
1019                 }
1020             } else {
1021                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1022                 $aGroupedSearches = array();
1023                 foreach ($aSearches as $aSearch) {
1024                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1025                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1026                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1027                     }
1028                 }
1029                 ksort($aGroupedSearches);
1030             }
1031
1032             if (CONST_Debug) var_Dump($aGroupedSearches);
1033             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1034                 $aCopyGroupedSearches = $aGroupedSearches;
1035                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1036                     foreach ($aSearches as $iSearch => $aSearch) {
1037                         $aReductionsList = array($aSearch['aAddress']);
1038                         $iSearchRank = $aSearch['iSearchRank'];
1039                         while (sizeof($aReductionsList) > 0) {
1040                             $iSearchRank += 5;
1041                             if ($iSearchRank > iMaxRank) break 3;
1042                             $aNewReductionsList = array();
1043                             foreach ($aReductionsList as $aReductionsWordList) {
1044                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1045                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1046                                     $aReverseSearch = $aSearch;
1047                                     $aSearch['aAddress'] = $aReductionsWordListResult;
1048                                     $aSearch['iSearchRank'] = $iSearchRank;
1049                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1050                                     if (sizeof($aReductionsWordListResult) > 0) {
1051                                         $aNewReductionsList[] = $aReductionsWordListResult;
1052                                     }
1053                                 }
1054                             }
1055                             $aReductionsList = $aNewReductionsList;
1056                         }
1057                     }
1058                 }
1059                 ksort($aGroupedSearches);
1060             }
1061
1062             // Filter out duplicate searches
1063             $aSearchHash = array();
1064             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1065                 foreach ($aSearches as $iSearch => $aSearch) {
1066                     $sHash = serialize($aSearch);
1067                     if (isset($aSearchHash[$sHash])) {
1068                         unset($aGroupedSearches[$iGroup][$iSearch]);
1069                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1070                     } else {
1071                         $aSearchHash[$sHash] = 1;
1072                     }
1073                 }
1074             }
1075
1076             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1077
1078             $iGroupLoop = 0;
1079             $iQueryLoop = 0;
1080             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1081                 $iGroupLoop++;
1082                 foreach ($aSearches as $aSearch) {
1083                     $iQueryLoop++;
1084                     $searchedHousenumber = -1;
1085
1086                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1087                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1088
1089                     // No location term?
1090                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
1091                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1092                             // Just looking for a country by code - look it up
1093                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1094                                 $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1095                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1096                                 if ($bBoundingBoxSearch)
1097                                     $sSQL .= " and _st_intersects($this->sViewboxSmallSQL, geometry)";
1098                                 $sSQL .= " order by st_area(geometry) desc limit 1";
1099                                 if (CONST_Debug) var_dump($sSQL);
1100                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1101                             } else {
1102                                 $aPlaceIDs = array();
1103                             }
1104                         } else {
1105                             if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1106                             if (!$aSearch['sClass']) continue;
1107
1108                             $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1109                             if (chksql($this->oDB->getOne($sSQL))) {
1110                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1111                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1112                                 $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1113                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1114                                 if (sizeof($this->aExcludePlaceIDs)) {
1115                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1116                                 }
1117                                 if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1118                                 $sSQL .= " limit $this->iLimit";
1119                                 if (CONST_Debug) var_dump($sSQL);
1120                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1121
1122                                 // If excluded place IDs are given, it is fair to assume that
1123                                 // there have been results in the small box, so no further
1124                                 // expansion in that case.
1125                                 // Also don't expand if bounded results were requested.
1126                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1127                                     $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1128                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1129                                     $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1130                                     if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1131                                     if ($this->sViewboxCentreSQL) $sSQL .= " order by st_distance($this->sViewboxCentreSQL, ct.centroid) asc";
1132                                     $sSQL .= " limit $this->iLimit";
1133                                     if (CONST_Debug) var_dump($sSQL);
1134                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1135                                 }
1136                             } else {
1137                                 $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1138                                 $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1139                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1140                                 if ($this->sViewboxCentreSQL)   $sSQL .= " order by st_distance($this->sViewboxCentreSQL, centroid) asc";
1141                                 $sSQL .= " limit $this->iLimit";
1142                                 if (CONST_Debug) var_dump($sSQL);
1143                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1144                             }
1145                         }
1146                     } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1147                         // If a coordinate is given, the search must either
1148                         // be for a name or a special search. Ignore everythin else.
1149                         $aPlaceIDs = array();
1150                     } else {
1151                         $aPlaceIDs = array();
1152
1153                         // First we need a position, either aName or fLat or both
1154                         $aTerms = array();
1155                         $aOrder = array();
1156
1157                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1158                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1159                             $aOrder[] = "";
1160                             $aOrder[0] = " (exists(select place_id from placex where parent_place_id = search_name.place_id";
1161                             $aOrder[0] .= " and transliteration(housenumber) ~* E'".$sHouseNumberRegex."' limit 1) ";
1162                             // also housenumbers from interpolation lines table are needed
1163                             $aOrder[0] .= " or exists(select place_id from location_property_osmline where parent_place_id = search_name.place_id";
1164                             $aOrder[0] .= " and ".intval($aSearch['sHouseNumber']).">=startnumber and ".intval($aSearch['sHouseNumber'])."<=endnumber limit 1))";
1165                             $aOrder[0] .= " desc";
1166                         }
1167
1168                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1169                         // they might be right - but they are just too darned expensive to run
1170                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1171                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1172                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1173                             // For infrequent name terms disable index usage for address
1174                             if (CONST_Search_NameOnlySearchFrequencyThreshold
1175                                 && sizeof($aSearch['aName']) == 1
1176                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1177                             ) {
1178                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1179                             } else {
1180                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1181                                 if (sizeof($aSearch['aAddressNonSearch'])) {
1182                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1183                                 }
1184                             }
1185                         }
1186                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1187                         if ($aSearch['sHouseNumber']) {
1188                             $aTerms[] = "address_rank between 16 and 27";
1189                         } else {
1190                             if ($this->iMinAddressRank > 0) {
1191                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1192                             }
1193                             if ($this->iMaxAddressRank < 30) {
1194                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1195                             }
1196                         }
1197                         if ($aSearch['fLon'] && $aSearch['fLat']) {
1198                             $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1199                             $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1200                         }
1201                         if (sizeof($this->aExcludePlaceIDs)) {
1202                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1203                         }
1204                         if ($sCountryCodesSQL) {
1205                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
1206                         }
1207
1208                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1209                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1210
1211                         if ($aSearch['sHouseNumber']) {
1212                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
1213                         } else {
1214                             $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1215                         }
1216                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1217                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1218
1219                         $aOrder[] = "$sImportanceSQL DESC";
1220                         if (sizeof($aSearch['aFullNameAddress'])) {
1221                             $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1222                             $aOrder[] = 'exactmatch DESC';
1223                         } else {
1224                             $sExactMatchSQL = '0::int as exactmatch';
1225                         }
1226
1227                         if (sizeof($aTerms)) {
1228                             $sSQL = "select place_id, ";
1229                             $sSQL .= $sExactMatchSQL;
1230                             $sSQL .= " from search_name";
1231                             $sSQL .= " where ".join(' and ', $aTerms);
1232                             $sSQL .= " order by ".join(', ', $aOrder);
1233                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1234                                 $sSQL .= " limit 20";
1235                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1236                                 $sSQL .= " limit 1";
1237                             } else {
1238                                 $sSQL .= " limit ".$this->iLimit;
1239                             }
1240
1241                             if (CONST_Debug) var_dump($sSQL);
1242                             $aViewBoxPlaceIDs = chksql(
1243                                 $this->oDB->getAll($sSQL),
1244                                 "Could not get places for search terms."
1245                             );
1246                             //var_dump($aViewBoxPlaceIDs);
1247                             // Did we have an viewbox matches?
1248                             $aPlaceIDs = array();
1249                             $bViewBoxMatch = false;
1250                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1251                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1252                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1253                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1254                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1255                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1256                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1257                             }
1258                         }
1259                         //var_Dump($aPlaceIDs);
1260                         //exit;
1261
1262                         //now search for housenumber, if housenumber provided
1263                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1264                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
1265                             $aRoadPlaceIDs = $aPlaceIDs;
1266                             $sPlaceIDs = join(',', $aPlaceIDs);
1267
1268                             // Now they are indexed, look for a house attached to a street we found
1269                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1270                             $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1271                             if (sizeof($this->aExcludePlaceIDs)) {
1272                                 $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1273                             }
1274                             $sSQL .= " limit $this->iLimit";
1275                             if (CONST_Debug) var_dump($sSQL);
1276                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1277                             
1278                             // if nothing found, search in the interpolation line table
1279                             if (!sizeof($aPlaceIDs)) {
1280                                 // do we need to use transliteration and the regex for housenumbers???
1281                                 //new query for lines, not housenumbers anymore
1282                                 if ($searchedHousenumber%2 == 0) {
1283                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1284                                     $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";
1285                                 } else {
1286                                     //look for housenumber in streets with interpolationtype odd or all
1287                                     $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";
1288                                 }
1289
1290                                 if (sizeof($this->aExcludePlaceIDs)) {
1291                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1292                                 }
1293                                 //$sSQL .= " limit $this->iLimit";
1294                                 if (CONST_Debug) var_dump($sSQL);
1295                                 //get place IDs
1296                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1297                             }
1298                                 
1299                             // If nothing found try the aux fallback table
1300                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1301                                 $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1302                                 if (sizeof($this->aExcludePlaceIDs)) {
1303                                     $sSQL .= " and parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1304                                 }
1305                                 //$sSQL .= " limit $this->iLimit";
1306                                 if (CONST_Debug) var_dump($sSQL);
1307                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1308                             }
1309
1310                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1311                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1312                                 //new query for lines, not housenumbers anymore
1313                                 if ($searchedHousenumber%2 == 0) {
1314                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1315                                     $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";
1316                                 } else {
1317                                     //look for housenumber in streets with interpolationtype odd or all
1318                                     $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";
1319                                 }
1320
1321                                 if (sizeof($this->aExcludePlaceIDs)) {
1322                                     $sSQL .= " and place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1323                                 }
1324                                 //$sSQL .= " limit $this->iLimit";
1325                                 if (CONST_Debug) var_dump($sSQL);
1326                                 //get place IDs
1327                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1328                             }
1329
1330                             // Fallback to the road (if no housenumber was found)
1331                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1332                                 $aPlaceIDs = $aRoadPlaceIDs;
1333                                 //set to -1, if no housenumbers were found
1334                                 $searchedHousenumber = -1;
1335                             }
1336                             //else: housenumber was found, remains saved in searchedHousenumber
1337                         }
1338
1339
1340                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1341                             $sPlaceIDs = join(',', $aPlaceIDs);
1342                             $aClassPlaceIDs = array();
1343
1344                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1345                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1346                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1347                                 $sSQL .= " and linked_place_id is null";
1348                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1349                                 $sSQL .= " order by rank_search asc limit $this->iLimit";
1350                                 if (CONST_Debug) var_dump($sSQL);
1351                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1352                             }
1353
1354                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1355                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1356                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1357
1358                                 $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1359
1360                                 if (CONST_Debug) var_dump($sSQL);
1361                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1362
1363                                 // For state / country level searches the normal radius search doesn't work very well
1364                                 $sPlaceGeom = false;
1365                                 if ($this->iMaxRank < 9 && $bCacheTable) {
1366                                     // Try and get a polygon to search in instead
1367                                     $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";
1368                                     if (CONST_Debug) var_dump($sSQL);
1369                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1370                                 }
1371
1372                                 if ($sPlaceGeom) {
1373                                     $sPlaceIDs = false;
1374                                 } else {
1375                                     $this->iMaxRank += 5;
1376                                     $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1377                                     if (CONST_Debug) var_dump($sSQL);
1378                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1379                                     $sPlaceIDs = join(',', $aPlaceIDs);
1380                                 }
1381
1382                                 if ($sPlaceIDs || $sPlaceGeom) {
1383                                     $fRange = 0.01;
1384                                     if ($bCacheTable) {
1385                                         // More efficient - can make the range bigger
1386                                         $fRange = 0.05;
1387
1388                                         $sOrderBySQL = '';
1389                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1390                                         elseif ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1391                                         elseif ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1392
1393                                         $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1394                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1395                                         if ($sPlaceIDs) {
1396                                             $sSQL .= ",placex as f where ";
1397                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1398                                         }
1399                                         if ($sPlaceGeom) {
1400                                             $sSQL .= " where ";
1401                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1402                                         }
1403                                         if (sizeof($this->aExcludePlaceIDs)) {
1404                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1405                                         }
1406                                         if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1407                                         if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1408                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1409                                         $sSQL .= " limit $this->iLimit";
1410                                         if (CONST_Debug) var_dump($sSQL);
1411                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1412                                     } else {
1413                                         if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1414
1415                                         $sOrderBySQL = '';
1416                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1417                                         else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1418
1419                                         $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1420                                         $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1421                                         $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1422                                         if (sizeof($this->aExcludePlaceIDs)) {
1423                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1424                                         }
1425                                         if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1426                                         if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1427                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1428                                         $sSQL .= " limit $this->iLimit";
1429                                         if (CONST_Debug) var_dump($sSQL);
1430                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1431                                     }
1432                                 }
1433                             }
1434                             $aPlaceIDs = $aClassPlaceIDs;
1435                         }
1436                     }
1437
1438                     if (CONST_Debug) {
1439                         echo "<br><b>Place IDs:</b> ";
1440                         var_Dump($aPlaceIDs);
1441                     }
1442
1443                     foreach ($aPlaceIDs as $iPlaceID) {
1444                         // array for placeID => -1 | Tiger housenumber
1445                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1446                     }
1447                     if ($iQueryLoop > 20) break;
1448                 }
1449
1450                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1451                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1452                     // reduces the number of place ids, like a filter
1453                     // rank_address is 30 for interpolated housenumbers
1454                     $sSQL = "select place_id from placex where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1455                     $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1456                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1457                     if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1458                     if (CONST_Use_US_Tiger_Data) {
1459                         $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1460                         $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1461                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1462                     }
1463                     $sSQL .= ") UNION select place_id from location_property_osmline where place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1464                     $sSQL .= " and (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1465                     if (CONST_Debug) var_dump($sSQL);
1466                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1467                     $tempIDs = array();
1468                     foreach ($aFilteredPlaceIDs as $placeID) {
1469                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1470                     }
1471                     $aResultPlaceIDs = $tempIDs;
1472                 }
1473
1474                 //exit;
1475                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1476                 if ($iGroupLoop > 4) break;
1477                 if ($iQueryLoop > 30) break;
1478             }
1479
1480             // Did we find anything?
1481             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1482                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1483             }
1484         } else {
1485             // Just interpret as a reverse geocode
1486             $oReverse = new ReverseGeocode($this->oDB);
1487             $oReverse->setZoom(18);
1488
1489             $aLookup = $oReverse->lookup(
1490                 (float)$this->aNearPoint[0],
1491                 (float)$this->aNearPoint[1],
1492                 false
1493             );
1494
1495             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1496
1497             if ($aLookup['place_id']) {
1498                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1499                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1500             } else {
1501                 $aSearchResults = array();
1502             }
1503         }
1504
1505         // No results? Done
1506         if (!sizeof($aSearchResults)) {
1507             if ($this->bFallback) {
1508                 if ($this->fallbackStructuredQuery()) {
1509                     return $this->lookup();
1510                 }
1511             }
1512
1513             return array();
1514         }
1515
1516         $aClassType = getClassTypesWithImportance();
1517         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1518         foreach ($aRecheckWords as $i => $sWord) {
1519             if (!preg_match('/\pL/', $sWord)) unset($aRecheckWords[$i]);
1520         }
1521
1522         if (CONST_Debug) {
1523             echo '<i>Recheck words:<\i>';
1524             var_dump($aRecheckWords);
1525         }
1526
1527         $oPlaceLookup = new PlaceLookup($this->oDB);
1528         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1529         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1530         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1531         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1532         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1533         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1534
1535         foreach ($aSearchResults as $iResNum => $aResult) {
1536             // Default
1537             $fDiameter = getResultDiameter($aResult);
1538
1539             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1540             if ($aOutlineResult) {
1541                 $aResult = array_merge($aResult, $aOutlineResult);
1542             }
1543             
1544             if ($aResult['extra_place'] == 'city') {
1545                 $aResult['class'] = 'place';
1546                 $aResult['type'] = 'city';
1547                 $aResult['rank_search'] = 16;
1548             }
1549
1550             // Is there an icon set for this type of result?
1551             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1552                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1553             ) {
1554                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1555             }
1556
1557             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1558                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1559             ) {
1560                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1561             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1562                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1563             ) {
1564                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1565             }
1566             // if tag '&addressdetails=1' is set in query
1567             if ($this->bIncludeAddressDetails) {
1568                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1569                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1570                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1571                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1572                 }
1573             }
1574
1575             if ($this->bIncludeExtraTags) {
1576                 if ($aResult['extra']) {
1577                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1578                 } else {
1579                     $aResult['sExtraTags'] = (object) array();
1580                 }
1581             }
1582
1583             if ($this->bIncludeNameDetails) {
1584                 if ($aResult['names']) {
1585                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1586                 } else {
1587                     $aResult['sNameDetails'] = (object) array();
1588                 }
1589             }
1590
1591             // Adjust importance for the number of exact string matches in the result
1592             $aResult['importance'] = max(0.001, $aResult['importance']);
1593             $iCountWords = 0;
1594             $sAddress = $aResult['langaddress'];
1595             foreach ($aRecheckWords as $i => $sWord) {
1596                 if (stripos($sAddress, $sWord)!==false) {
1597                     $iCountWords++;
1598                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1599                 }
1600             }
1601
1602             $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
1603
1604             $aResult['name'] = $aResult['langaddress'];
1605             // secondary ordering (for results with same importance (the smaller the better):
1606             // - approximate importance of address parts
1607             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1608             // - number of exact matches from the query
1609             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1610                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1611             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1612                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1613             }
1614             // - importance of the class/type
1615             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1616                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1617             ) {
1618                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1619             } else {
1620                 $aResult['foundorder'] += 0.01;
1621             }
1622             if (CONST_Debug) var_dump($aResult);
1623             $aSearchResults[$iResNum] = $aResult;
1624         }
1625         uasort($aSearchResults, 'byImportance');
1626
1627         $aOSMIDDone = array();
1628         $aClassTypeNameDone = array();
1629         $aToFilter = $aSearchResults;
1630         $aSearchResults = array();
1631
1632         $bFirst = true;
1633         foreach ($aToFilter as $iResNum => $aResult) {
1634             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1635             if ($bFirst) {
1636                 $fLat = $aResult['lat'];
1637                 $fLon = $aResult['lon'];
1638                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1639                 $bFirst = false;
1640             }
1641             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1642                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1643             ) {
1644                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1645                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1646                 $aSearchResults[] = $aResult;
1647             }
1648
1649             // Absolute limit on number of results
1650             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1651         }
1652
1653         return $aSearchResults;
1654     } // end lookup()
1655 } // end class