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