]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
09c1ccb4589742e29a4252a88f4151230c26820e
[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/Phrase.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
8 require_once(CONST_BasePath.'/lib/SearchDescription.php');
9 require_once(CONST_BasePath.'/lib/SearchContext.php');
10
11 class Geocode
12 {
13     protected $oDB;
14
15     protected $aLangPrefOrder = array();
16
17     protected $bIncludeAddressDetails = false;
18     protected $bIncludeExtraTags = false;
19     protected $bIncludeNameDetails = false;
20
21     protected $bIncludePolygonAsPoints = false;
22     protected $bIncludePolygonAsText = false;
23     protected $bIncludePolygonAsGeoJSON = false;
24     protected $bIncludePolygonAsKML = false;
25     protected $bIncludePolygonAsSVG = false;
26     protected $fPolygonSimplificationThreshold = 0.0;
27
28     protected $aExcludePlaceIDs = array();
29     protected $bDeDupe = true;
30     protected $bReverseInPlan = false;
31
32     protected $iLimit = 20;
33     protected $iFinalLimit = 10;
34     protected $iOffset = 0;
35     protected $bFallback = false;
36
37     protected $aCountryCodes = false;
38
39     protected $bBoundedSearch = false;
40     protected $aViewBox = false;
41     protected $aRoutePoints = false;
42     protected $aRouteWidth = false;
43
44     protected $iMaxRank = 20;
45     protected $iMinAddressRank = 0;
46     protected $iMaxAddressRank = 30;
47     protected $aAddressRankList = array();
48
49     protected $sAllowedTypesSQLList = false;
50
51     protected $sQuery = false;
52     protected $aStructuredQuery = false;
53
54     protected $oNormalizer = null;
55
56
57     public function __construct(&$oDB)
58     {
59         $this->oDB =& $oDB;
60         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
61     }
62
63     private function normTerm($sTerm)
64     {
65         if ($this->oNormalizer === null) {
66             return $sTerm;
67         }
68
69         return $this->oNormalizer->transliterate($sTerm);
70     }
71
72     public function setReverseInPlan($bReverse)
73     {
74         $this->bReverseInPlan = $bReverse;
75     }
76
77     public function setLanguagePreference($aLangPref)
78     {
79         $this->aLangPrefOrder = $aLangPref;
80     }
81
82     public function getMoreUrlParams()
83     {
84         if ($this->aStructuredQuery) {
85             $aParams = $this->aStructuredQuery;
86         } else {
87             $aParams = array('q' => $this->sQuery);
88         }
89
90         if ($this->aExcludePlaceIDs) {
91             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
92         }
93
94         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
95         if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
96         if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
97
98         if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
99         if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
100         if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
101         if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
102         if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
103
104         if ($this->fPolygonSimplificationThreshold > 0.0) {
105             $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
106         }
107
108         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
109         if (!$this->bDeDupe) $aParams['dedupe'] = '0';
110
111         if ($this->aCountryCodes) {
112             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
113         }
114
115         if ($this->aViewBox) {
116             $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
117                                   .','.$this->aViewBox[2].','.$this->aViewBox[1];
118         }
119
120         return $aParams;
121     }
122
123     public function setIncludePolygonAsPoints($b = true)
124     {
125         $this->bIncludePolygonAsPoints = $b;
126     }
127
128     public function setIncludePolygonAsText($b = true)
129     {
130         $this->bIncludePolygonAsText = $b;
131     }
132
133     public function setIncludePolygonAsGeoJSON($b = true)
134     {
135         $this->bIncludePolygonAsGeoJSON = $b;
136     }
137
138     public function setIncludePolygonAsKML($b = true)
139     {
140         $this->bIncludePolygonAsKML = $b;
141     }
142
143     public function setIncludePolygonAsSVG($b = true)
144     {
145         $this->bIncludePolygonAsSVG = $b;
146     }
147
148     public function setPolygonSimplificationThreshold($f)
149     {
150         $this->fPolygonSimplificationThreshold = $f;
151     }
152
153     public function setLimit($iLimit = 10)
154     {
155         if ($iLimit > 50) $iLimit = 50;
156         if ($iLimit < 1) $iLimit = 1;
157
158         $this->iFinalLimit = $iLimit;
159         $this->iLimit = $iLimit + min($iLimit, 10);
160     }
161
162     public function setFeatureType($sFeatureType)
163     {
164         switch ($sFeatureType) {
165             case 'country':
166                 $this->setRankRange(4, 4);
167                 break;
168             case 'state':
169                 $this->setRankRange(8, 8);
170                 break;
171             case 'city':
172                 $this->setRankRange(14, 16);
173                 break;
174             case 'settlement':
175                 $this->setRankRange(8, 20);
176                 break;
177         }
178     }
179
180     public function setRankRange($iMin, $iMax)
181     {
182         $this->iMinAddressRank = $iMin;
183         $this->iMaxAddressRank = $iMax;
184     }
185
186     public function setViewbox($aViewbox)
187     {
188         $this->aViewBox = array_map('floatval', $aViewbox);
189
190         $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
191         $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
192         $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
193         $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
194
195         if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
196             || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
197         ) {
198             userError("Bad parameter 'viewbox'. Not a box.");
199         }
200     }
201
202     public function setQuery($sQueryString)
203     {
204         $this->sQuery = $sQueryString;
205         $this->aStructuredQuery = false;
206     }
207
208     public function getQueryString()
209     {
210         return $this->sQuery;
211     }
212
213
214     public function loadParamArray($oParams)
215     {
216         $this->bIncludeAddressDetails
217          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
218         $this->bIncludeExtraTags
219          = $oParams->getBool('extratags', $this->bIncludeExtraTags);
220         $this->bIncludeNameDetails
221          = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
222
223         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
224         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
225
226         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
227         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
228
229         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
230
231         // List of excluded Place IDs - used for more acurate pageing
232         $sExcluded = $oParams->getStringList('exclude_place_ids');
233         if ($sExcluded) {
234             foreach ($sExcluded as $iExcludedPlaceID) {
235                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
236                 if ($iExcludedPlaceID)
237                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
238             }
239
240             if (isset($aExcludePlaceIDs))
241                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
242         }
243
244         // Only certain ranks of feature
245         $sFeatureType = $oParams->getString('featureType');
246         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
247         if ($sFeatureType) $this->setFeatureType($sFeatureType);
248
249         // Country code list
250         $sCountries = $oParams->getStringList('countrycodes');
251         if ($sCountries) {
252             foreach ($sCountries as $sCountryCode) {
253                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
254                     $aCountries[] = strtolower($sCountryCode);
255                 }
256             }
257             if (isset($aCountries))
258                 $this->aCountryCodes = $aCountries;
259         }
260
261         $aViewbox = $oParams->getStringList('viewboxlbrt');
262         if ($aViewbox) {
263             if (count($aViewbox) != 4) {
264                 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
265             }
266             $this->setViewbox($aViewbox);
267         } else {
268             $aViewbox = $oParams->getStringList('viewbox');
269             if ($aViewbox) {
270                 if (count($aViewbox) != 4) {
271                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
272                 }
273                 $this->setViewBox($aViewbox);
274             } else {
275                 $aRoute = $oParams->getStringList('route');
276                 $fRouteWidth = $oParams->getFloat('routewidth');
277                 if ($aRoute && $fRouteWidth) {
278                     $this->aRoutePoints = $aRoute;
279                     $this->aRouteWidth = $fRouteWidth;
280                 }
281             }
282         }
283     }
284
285     public function setQueryFromParams($oParams)
286     {
287         // Search query
288         $sQuery = $oParams->getString('q');
289         if (!$sQuery) {
290             $this->setStructuredQuery(
291                 $oParams->getString('amenity'),
292                 $oParams->getString('street'),
293                 $oParams->getString('city'),
294                 $oParams->getString('county'),
295                 $oParams->getString('state'),
296                 $oParams->getString('country'),
297                 $oParams->getString('postalcode')
298             );
299             $this->setReverseInPlan(false);
300         } else {
301             $this->setQuery($sQuery);
302         }
303     }
304
305     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
306     {
307         $sValue = trim($sValue);
308         if (!$sValue) return false;
309         $this->aStructuredQuery[$sKey] = $sValue;
310         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
311             $this->iMinAddressRank = $iNewMinAddressRank;
312             $this->iMaxAddressRank = $iNewMaxAddressRank;
313         }
314         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
315         return true;
316     }
317
318     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
319     {
320         $this->sQuery = false;
321
322         // Reset
323         $this->iMinAddressRank = 0;
324         $this->iMaxAddressRank = 30;
325         $this->aAddressRankList = array();
326
327         $this->aStructuredQuery = array();
328         $this->sAllowedTypesSQLList = false;
329
330         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
331         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
332         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
333         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
334         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
335         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
336         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
337
338         if (sizeof($this->aStructuredQuery) > 0) {
339             $this->sQuery = join(', ', $this->aStructuredQuery);
340             if ($this->iMaxAddressRank < 30) {
341                 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
342             }
343         }
344     }
345
346     public function fallbackStructuredQuery()
347     {
348         if (!$this->aStructuredQuery) return false;
349
350         $aParams = $this->aStructuredQuery;
351
352         if (sizeof($aParams) == 1) return false;
353
354         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
355
356         foreach ($aOrderToFallback as $sType) {
357             if (isset($aParams[$sType])) {
358                 unset($aParams[$sType]);
359                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
360                 return true;
361             }
362         }
363
364         return false;
365     }
366
367     public function getDetails($aResults, $oCtx)
368     {
369         // Get the details for display (is this a redundant extra step?)
370         //$aResults is an array of Result objects
371         if (sizeof($aResults) == 0) return array();
372
373         $sLanguagePrefArraySQL = getArraySQL(
374             array_map("getDBQuoted", $this->aLangPrefOrder)
375         );
376
377         $sImportanceSQL = $oCtx->viewboxImportanceSQL('ST_Collect(centroid)');
378         $sImportanceSQLGeom = $oCtx->viewboxImportanceSQL('geometry');
379
380         $aSubSelects = array();
381
382         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
383         if ($sPlaceIDs) {
384             $sSQL  = "SELECT ";
385             $sSQL .= "    osm_type,";
386             $sSQL .= "    osm_id,";
387             $sSQL .= "    class,";
388             $sSQL .= "    type,";
389             $sSQL .= "    admin_level,";
390             $sSQL .= "    rank_search,";
391             $sSQL .= "    rank_address,";
392             $sSQL .= "    min(place_id) AS place_id, ";
393             $sSQL .= "    min(parent_place_id) AS parent_place_id, ";
394             $sSQL .= "    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, ";
401             $sSQL .= "    avg(ST_Y(centroid)) AS lat, ";
402             $sSQL .= "    COALESCE(importance,0.75-(rank_search::float/40)) $sImportanceSQL AS importance, ";
403             if ($oCtx->hasNearPoint()) {
404                 $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
405             } else {
406                 $sSQL .= "    ( ";
407                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
408                 $sSQL .= "       FROM ";
409                 $sSQL .= "         place_addressline s, ";
410                 $sSQL .= "         placex p";
411                 $sSQL .= "       WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
412                 $sSQL .= "         AND p.place_id = s.address_place_id ";
413                 $sSQL .= "         AND s.isaddress ";
414                 $sSQL .= "         AND p.importance is not null ";
415                 $sSQL .= "    ) AS addressimportance, ";
416             }
417             $sSQL .= "    (extratags->'place') AS extra_place ";
418             $sSQL .= " FROM placex";
419             $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
420             $sSQL .= "   AND (";
421             $sSQL .= "            placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
422             if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
423                 $sSQL .= "        OR (extratags->'place') = 'city'";
424             }
425             if ($this->aAddressRankList) {
426                 $sSQL .= "        OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
427             }
428             $sSQL .= "       ) ";
429             if ($this->sAllowedTypesSQLList) {
430                 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
431             }
432             $sSQL .= "    AND linked_place_id is null ";
433             $sSQL .= " GROUP BY ";
434             $sSQL .= "     osm_type, ";
435             $sSQL .= "     osm_id, ";
436             $sSQL .= "     class, ";
437             $sSQL .= "     type, ";
438             $sSQL .= "     admin_level, ";
439             $sSQL .= "     rank_search, ";
440             $sSQL .= "     rank_address, ";
441             $sSQL .= "     country_code, ";
442             $sSQL .= "     importance, ";
443             if (!$this->bDeDupe) $sSQL .= "place_id,";
444             $sSQL .= "     langaddress, ";
445             $sSQL .= "     placename, ";
446             $sSQL .= "     ref, ";
447             if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
448             if ($this->bIncludeNameDetails) $sSQL .= "name, ";
449             $sSQL .= "     extratags->'place' ";
450
451             $aSubSelects[] = $sSQL;
452         }
453
454         // postcode table
455         $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
456         if ($sPlaceIDs) {
457             $sSQL = 'SELECT';
458             $sSQL .= "  'P' as osm_type,";
459             $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
460             $sSQL .= "  'place' as class, 'postcode' as type,";
461             $sSQL .= "  null as admin_level, rank_search, rank_address,";
462             $sSQL .= "  place_id, parent_place_id, country_code,";
463             $sSQL .= "  get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
464             $sSQL .= "  postcode as placename,";
465             $sSQL .= "  postcode as ref,";
466             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
467             if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
468             $sSQL .= "  ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
469             $sSQL .= "  (0.75-(rank_search::float/40)) $sImportanceSQLGeom AS importance, ";
470             if ($oCtx->hasNearPoint()) {
471                 $sSQL .= $oCtx->distanceSQL('geometry')." AS addressimportance,";
472             } else {
473                 $sSQL .= "  (";
474                 $sSQL .= "     SELECT max(p.importance*(p.rank_address+2))";
475                 $sSQL .= "     FROM ";
476                 $sSQL .= "       place_addressline s, ";
477                 $sSQL .= "       placex p";
478                 $sSQL .= "     WHERE s.place_id = lp.parent_place_id";
479                 $sSQL .= "       AND p.place_id = s.address_place_id ";
480                 $sSQL .= "       AND s.isaddress";
481                 $sSQL .= "       AND p.importance is not null";
482                 $sSQL .= "  ) AS addressimportance, ";
483             }
484             $sSQL .= "  null AS extra_place ";
485             $sSQL .= "FROM location_postcode lp";
486             $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
487
488             $aSubSelects[] = $sSQL;
489         }
490
491         // All other tables are rank 30 only.
492         if ($this->iMaxAddressRank == 30) {
493             // TIGER table
494             if (CONST_Use_US_Tiger_Data) {
495                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_TIGER);
496                 if ($sPlaceIDs) {
497                     $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_TIGER);
498                     // Tiger search only if a housenumber was searched and if it was found
499                     // (realized through a join)
500                     $sSQL = " SELECT ";
501                     $sSQL .= "     'T' AS osm_type, ";
502                     $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
503                     $sSQL .= "     'place' AS class, ";
504                     $sSQL .= "     'house' AS type, ";
505                     $sSQL .= "     null AS admin_level, ";
506                     $sSQL .= "     30 AS rank_search, ";
507                     $sSQL .= "     30 AS rank_address, ";
508                     $sSQL .= "     min(place_id) AS place_id, ";
509                     $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
510                     $sSQL .= "     'us' AS country_code, ";
511                     $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
512                     $sSQL .= "     null AS placename, ";
513                     $sSQL .= "     null AS ref, ";
514                     if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
515                     if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
516                     $sSQL .= "     avg(st_x(centroid)) AS lon, ";
517                     $sSQL .= "     avg(st_y(centroid)) AS lat,";
518                     $sSQL .= "     -1.15".$sImportanceSQL." AS importance, ";
519                     if ($oCtx->hasNearPoint()) {
520                         $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
521                     } else {
522                         $sSQL .= "     (";
523                         $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
524                         $sSQL .= "        FROM ";
525                         $sSQL .= "          place_addressline s, ";
526                         $sSQL .= "          placex p";
527                         $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
528                         $sSQL .= "          AND p.place_id = s.address_place_id ";
529                         $sSQL .= "          AND s.isaddress";
530                         $sSQL .= "          AND p.importance is not null";
531                         $sSQL .= "     ) AS addressimportance, ";
532                     }
533                     $sSQL .= "     null AS extra_place ";
534                     $sSQL .= " FROM (";
535                     $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
536                     $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
537                     $sSQL .= "         parent_place_id, ";
538                     $sSQL .= "         housenumber_for_place";
539                     $sSQL .= "     FROM (";
540                     $sSQL .= "            location_property_tiger ";
541                     $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
542                     $sSQL .= "     WHERE ";
543                     $sSQL .= "         housenumber_for_place >= startnumber";
544                     $sSQL .= "         AND housenumber_for_place <= endnumber";
545                     $sSQL .= " ) AS blub"; //postgres wants an alias here
546                     $sSQL .= " GROUP BY";
547                     $sSQL .= "      place_id, ";
548                     $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
549                     if (!$this->bDeDupe) $sSQL .= ", place_id ";
550
551                     $aSubSelects[] = $sSQL;
552                 }
553             }
554
555             // osmline - interpolated housenumbers
556             $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_OSMLINE);
557             if ($sPlaceIDs) {
558                 $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_OSMLINE);
559                 // interpolation line search only if a housenumber was searched
560                 // (realized through a join)
561                 $sSQL = "SELECT ";
562                 $sSQL .= "  'W' AS osm_type, ";
563                 $sSQL .= "  osm_id, ";
564                 $sSQL .= "  'place' AS class, ";
565                 $sSQL .= "  'house' AS type, ";
566                 $sSQL .= "  null AS admin_level, ";
567                 $sSQL .= "  30 AS rank_search, ";
568                 $sSQL .= "  30 AS rank_address, ";
569                 $sSQL .= "  min(place_id) as place_id, ";
570                 $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
571                 $sSQL .= "  country_code, ";
572                 $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
573                 $sSQL .= "  null AS placename, ";
574                 $sSQL .= "  null AS ref, ";
575                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
576                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
577                 $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
578                 $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
579                 $sSQL .= "  -0.1".$sImportanceSQL." AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
580                 if ($oCtx->hasNearPoint()) {
581                     $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
582                 } else {
583                     $sSQL .= "  (";
584                     $sSQL .= "     SELECT ";
585                     $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
586                     $sSQL .= "     FROM";
587                     $sSQL .= "       place_addressline s, ";
588                     $sSQL .= "       placex p";
589                     $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
590                     $sSQL .= "       AND p.place_id = s.address_place_id ";
591                     $sSQL .= "       AND s.isaddress ";
592                     $sSQL .= "       AND p.importance is not null";
593                     $sSQL .= "  ) AS addressimportance,";
594                 }
595                 $sSQL .= "  null AS extra_place ";
596                 $sSQL .= "  FROM (";
597                 $sSQL .= "     SELECT ";
598                 $sSQL .= "         osm_id, ";
599                 $sSQL .= "         place_id, ";
600                 $sSQL .= "         country_code, ";
601                 $sSQL .= "         CASE ";             // interpolate the housenumbers here
602                 $sSQL .= "           WHEN startnumber != endnumber ";
603                 $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
604                 $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
605                 $sSQL .= "         END as centroid, ";
606                 $sSQL .= "         parent_place_id, ";
607                 $sSQL .= "         housenumber_for_place ";
608                 $sSQL .= "     FROM (";
609                 $sSQL .= "            location_property_osmline ";
610                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
611                 $sSQL .= "          ) ";
612                 $sSQL .= "     WHERE housenumber_for_place>=0 ";
613                 $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
614                 $sSQL .= "  ) as blub"; //postgres wants an alias here
615                 $sSQL .= "  GROUP BY ";
616                 $sSQL .= "    osm_id, ";
617                 $sSQL .= "    place_id, ";
618                 $sSQL .= "    housenumber_for_place, ";
619                 $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
620                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
621
622                 $aSubSelects[] = $sSQL;
623             }
624
625             if (CONST_Use_Aux_Location_data) {
626                 $sPlaceIDs = Result::joinIdsByTable($aResults, Result::TABLE_AUX);
627                 if ($sPlaceIDs) {
628                     $sHousenumbers = Result::sqlHouseNumberTable($aResults, Result::TABLE_AUX);
629                     $sSQL = "  SELECT ";
630                     $sSQL .= "     'L' AS osm_type, ";
631                     $sSQL .= "     place_id AS osm_id, ";
632                     $sSQL .= "     'place' AS class,";
633                     $sSQL .= "     'house' AS type, ";
634                     $sSQL .= "     null AS admin_level, ";
635                     $sSQL .= "     0 AS rank_search,";
636                     $sSQL .= "     0 AS rank_address, ";
637                     $sSQL .= "     min(place_id) AS place_id,";
638                     $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
639                     $sSQL .= "     'us' AS country_code, ";
640                     $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
641                     $sSQL .= "     null AS placename, ";
642                     $sSQL .= "     null AS ref, ";
643                     if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
644                     if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
645                     $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
646                     $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
647                     $sSQL .= "     -1.10".$sImportanceSQL." AS importance, ";
648                     if ($oCtx->hasNearPoint()) {
649                         $sSQL .= $oCtx->distanceSQL('ST_Collect(centroid)')." AS addressimportance,";
650                     } else {
651                         $sSQL .= "     ( ";
652                         $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
653                         $sSQL .= "       FROM ";
654                         $sSQL .= "          place_addressline s, ";
655                         $sSQL .= "          placex p";
656                         $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
657                         $sSQL .= "         AND p.place_id = s.address_place_id ";
658                         $sSQL .= "         AND s.isaddress";
659                         $sSQL .= "         AND p.importance is not null";
660                         $sSQL .= "     ) AS addressimportance, ";
661                     }
662                     $sSQL .= "     null AS extra_place ";
663                     $sSQL .= "  FROM location_property_aux ";
664                     $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
665                     $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
666                     $sSQL .= "  GROUP BY ";
667                     $sSQL .= "     place_id, ";
668                     if (!$this->bDeDupe) $sSQL .= "place_id, ";
669                     $sSQL .= "     langaddress ";
670
671                     $aSubSelects[] = $sSQL;
672                 }
673             }
674         }
675
676         if (!sizeof($aSubSelects)) {
677             return array();
678         }
679
680         $sSQL = join(' UNION ', $aSubSelects)." order by importance desc";
681         if (CONST_Debug) {
682             echo "<hr>";
683             var_dump($sSQL);
684         }
685         $aSearchResults = chksql(
686             $this->oDB->getAll($sSQL),
687             "Could not get details for place."
688         );
689
690         return $aSearchResults;
691     }
692
693     public function getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bIsStructured)
694     {
695         /*
696              Calculate all searches using aValidTokens i.e.
697              'Wodsworth Road, Sheffield' =>
698
699              Phrase Wordset
700              0      0       (wodsworth road)
701              0      1       (wodsworth)(road)
702              1      0       (sheffield)
703
704              Score how good the search is so they can be ordered
705          */
706         $iGlobalRank = 0;
707
708         foreach ($aPhrases as $iPhrase => $oPhrase) {
709             $aNewPhraseSearches = array();
710             $sPhraseType = $bIsStructured ? $oPhrase->getPhraseType() : '';
711
712             foreach ($oPhrase->getWordSets() as $iWordSet => $aWordset) {
713                 // Too many permutations - too expensive
714                 if ($iWordSet > 120) break;
715
716                 $aWordsetSearches = $aSearches;
717
718                 // Add all words from this wordset
719                 foreach ($aWordset as $iToken => $sToken) {
720                     //echo "<br><b>$sToken</b>";
721                     $aNewWordsetSearches = array();
722
723                     foreach ($aWordsetSearches as $oCurrentSearch) {
724                         //echo "<i>";
725                         //var_dump($oCurrentSearch);
726                         //echo "</i>";
727
728                         // If the token is valid
729                         if (isset($aValidTokens[' '.$sToken])) {
730                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
731                                 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
732                                     $aSearchTerm,
733                                     isset($aValidTokens[$sToken])
734                                       && strpos($sToken, ' ') === false,
735                                     $sPhraseType,
736                                     $iToken == 0 && $iPhrase == 0,
737                                     $iPhrase == 0,
738                                     $iToken + 1 == sizeof($aWordset)
739                                       && $iPhrase + 1 == sizeof($aPhrases),
740                                     $iGlobalRank
741                                 );
742
743                                 foreach ($aNewSearches as $oSearch) {
744                                     if ($oSearch->getRank() < $this->iMaxRank) {
745                                         $aNewWordsetSearches[] = $oSearch;
746                                     }
747                                 }
748                             }
749                         }
750                         // Look for partial matches.
751                         // Note that there is no point in adding country terms here
752                         // because country is omitted in the address.
753                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
754                             // Allow searching for a word - but at extra cost
755                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
756                                 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
757                                     $aSearchTerm,
758                                     $bIsStructured,
759                                     $iPhrase,
760                                     isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
761                                 );
762
763                                 foreach ($aNewSearches as $oSearch) {
764                                     if ($oSearch->getRank() < $this->iMaxRank) {
765                                         $aNewWordsetSearches[] = $oSearch;
766                                     }
767                                 }
768                             }
769                         }
770                     }
771                     // Sort and cut
772                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
773                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
774                 }
775                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
776
777                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
778                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
779
780                 $aSearchHash = array();
781                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
782                     $sHash = serialize($aSearch);
783                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
784                     else $aSearchHash[$sHash] = 1;
785                 }
786
787                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
788             }
789
790             // Re-group the searches by their score, junk anything over 20 as just not worth trying
791             $aGroupedSearches = array();
792             foreach ($aNewPhraseSearches as $aSearch) {
793                 $iRank = $aSearch->getRank();
794                 if ($iRank < $this->iMaxRank) {
795                     if (!isset($aGroupedSearches[$iRank])) {
796                         $aGroupedSearches[$iRank] = array();
797                     }
798                     $aGroupedSearches[$iRank][] = $aSearch;
799                 }
800             }
801             ksort($aGroupedSearches);
802
803             $iSearchCount = 0;
804             $aSearches = array();
805             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
806                 $iSearchCount += sizeof($aNewSearches);
807                 $aSearches = array_merge($aSearches, $aNewSearches);
808                 if ($iSearchCount > 50) break;
809             }
810
811             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
812         }
813
814         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
815         $aGroupedSearches = array();
816         foreach ($aSearches as $oSearch) {
817             if (!$oSearch->isValidSearch()) {
818                 continue;
819             }
820
821             $iRank = $oSearch->addToRank($iGlobalRank);
822             if (!isset($aGroupedSearches[$iRank])) {
823                 $aGroupedSearches[$iRank] = array();
824             }
825             $aGroupedSearches[$iRank][] = $oSearch;
826         }
827         ksort($aGroupedSearches);
828
829         return $aGroupedSearches;
830     }
831
832     /* Perform the actual query lookup.
833
834         Returns an ordered list of results, each with the following fields:
835             osm_type: type of corresponding OSM object
836                         N - node
837                         W - way
838                         R - relation
839                         P - postcode (internally computed)
840             osm_id: id of corresponding OSM object
841             class: general object class (corresponds to tag key of primary OSM tag)
842             type: subclass of object (corresponds to tag value of primary OSM tag)
843             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
844             rank_search: rank in search hierarchy
845                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
846             rank_address: rank in address hierarchy (determines orer in address)
847             place_id: internal key (may differ between different instances)
848             country_code: ISO country code
849             langaddress: localized full address
850             placename: localized name of object
851             ref: content of ref tag (if available)
852             lon: longitude
853             lat: latitude
854             importance: importance of place based on Wikipedia link count
855             addressimportance: cumulated importance of address elements
856             extra_place: type of place (for admin boundaries, if there is a place tag)
857             aBoundingBox: bounding Box
858             label: short description of the object class/type (English only)
859             name: full name (currently the same as langaddress)
860             foundorder: secondary ordering for places with same importance
861     */
862
863
864     public function lookup()
865     {
866         if (!$this->sQuery && !$this->aStructuredQuery) return array();
867
868         $oCtx = new SearchContext();
869
870         if ($this->aRoutePoints) {
871             $oCtx->setViewboxFromRoute(
872                 $this->oDB,
873                 $this->aRoutePoints,
874                 $this->aRouteWidth,
875                 $this->bBoundedSearch
876             );
877         } elseif ($this->aViewBox) {
878             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
879         }
880         if ($this->aExcludePlaceIDs) {
881             $oCtx->setExcludeList($this->aExcludePlaceIDs);
882         }
883         if ($this->aCountryCodes) {
884             $oCtx->setCountryList($this->aCountryCodes);
885         }
886
887         $sNormQuery = $this->normTerm($this->sQuery);
888         $sLanguagePrefArraySQL = getArraySQL(
889             array_map("getDBQuoted", $this->aLangPrefOrder)
890         );
891
892         $sQuery = $this->sQuery;
893         if (!preg_match('//u', $sQuery)) {
894             userError("Query string is not UTF-8 encoded.");
895         }
896
897         // Conflicts between US state abreviations and various words for 'the' in different languages
898         if (isset($this->aLangPrefOrder['name:en'])) {
899             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
900             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
901             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
902         }
903
904         // Do we have anything that looks like a lat/lon pair?
905         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
906
907         $aSearchResults = array();
908         if ($sQuery || $this->aStructuredQuery) {
909             // Start with a single blank search
910             $aSearches = array(new SearchDescription($oCtx));
911
912             if ($sQuery) {
913                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
914             }
915
916             $sSpecialTerm = '';
917             if ($sQuery) {
918                 preg_match_all(
919                     '/\\[([\\w ]*)\\]/u',
920                     $sQuery,
921                     $aSpecialTermsRaw,
922                     PREG_SET_ORDER
923                 );
924                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
925                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
926                     if (!$sSpecialTerm) {
927                         $sSpecialTerm = $aSpecialTerm[1];
928                     }
929                 }
930             }
931             if (!$sSpecialTerm && $this->aStructuredQuery
932                 && isset($this->aStructuredQuery['amenity'])) {
933                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
934                 unset($this->aStructuredQuery['amenity']);
935             }
936
937             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
938                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
939                 $sToken = chksql(
940                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
941                     "Cannot decode query. Wrong encoding?"
942                 );
943                 $sSQL = 'SELECT class, type FROM word ';
944                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
945                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
946                 if (CONST_Debug) var_Dump($sSQL);
947                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
948                 $aNewSearches = array();
949                 foreach ($aSearches as $oSearch) {
950                     foreach ($aSearchWords as $aSearchTerm) {
951                         $oNewSearch = clone $oSearch;
952                         $oNewSearch->setPoiSearch(
953                             Operator::TYPE,
954                             $aSearchTerm['class'],
955                             $aSearchTerm['type']
956                         );
957                         $aNewSearches[] = $oNewSearch;
958                     }
959                 }
960                 $aSearches = $aNewSearches;
961             }
962
963             // Split query into phrases
964             // Commas are used to reduce the search space by indicating where phrases split
965             if ($this->aStructuredQuery) {
966                 $aInPhrases = $this->aStructuredQuery;
967                 $bStructuredPhrases = true;
968             } else {
969                 $aInPhrases = explode(',', $sQuery);
970                 $bStructuredPhrases = false;
971             }
972
973             // Convert each phrase to standard form
974             // Create a list of standard words
975             // Get all 'sets' of words
976             // Generate a complete list of all
977             $aTokens = array();
978             $aPhrases = array();
979             foreach ($aInPhrases as $iPhrase => $sPhrase) {
980                 $sPhrase = chksql(
981                     $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
982                     "Cannot normalize query string (is it a UTF-8 string?)"
983                 );
984                 if (trim($sPhrase)) {
985                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
986                     $oPhrase->addTokens($aTokens);
987                     $aPhrases[] = $oPhrase;
988                 }
989             }
990
991             if (sizeof($aTokens)) {
992                 // Check which tokens we have, get the ID numbers
993                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
994                 $sSQL .= ' FROM word ';
995                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
996
997                 if (CONST_Debug) var_Dump($sSQL);
998
999                 $aValidTokens = array();
1000                 $aDatabaseWords = chksql(
1001                     $this->oDB->getAll($sSQL),
1002                     "Could not get word tokens."
1003                 );
1004                 $aWordFrequencyScores = array();
1005                 foreach ($aDatabaseWords as $aToken) {
1006                     // Filter country tokens that do not match restricted countries.
1007                     if ($this->aCountryCodes
1008                         && $aToken['country_code']
1009                         && !in_array($aToken['country_code'], $this->aCountryCodes)
1010                     ) {
1011                         continue;
1012                     }
1013
1014                     // Special terms need to appear in their normalized form.
1015                     if ($aToken['word'] && $aToken['class']) {
1016                         $sNormWord = $this->normTerm($aToken['word']);
1017                         if (strpos($sNormQuery, $sNormWord) === false) {
1018                             continue;
1019                         }
1020                     }
1021
1022                     if (isset($aValidTokens[$aToken['word_token']])) {
1023                         $aValidTokens[$aToken['word_token']][] = $aToken;
1024                     } else {
1025                         $aValidTokens[$aToken['word_token']] = array($aToken);
1026                     }
1027                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1028                 }
1029                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1030
1031                 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1032                 foreach ($aTokens as $sToken) {
1033                     if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1034                         if (isset($aValidTokens[$aData[1]])) {
1035                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1036                                 if (!$aToken['class']) {
1037                                     if (isset($aValidTokens[$sToken])) {
1038                                         $aValidTokens[$sToken][] = $aToken;
1039                                     } else {
1040                                         $aValidTokens[$sToken] = array($aToken);
1041                                     }
1042                                 }
1043                             }
1044                         }
1045                     }
1046                 }
1047
1048                 foreach ($aTokens as $sToken) {
1049                     // Unknown single word token with a number - assume it is a house number
1050                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1051                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1052                     }
1053                 }
1054
1055                 // Any words that have failed completely?
1056                 // TODO: suggestions
1057
1058                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $bStructuredPhrases);
1059
1060                 if ($this->bReverseInPlan) {
1061                     // Reverse phrase array and also reverse the order of the wordsets in
1062                     // the first and final phrase. Don't bother about phrases in the middle
1063                     // because order in the address doesn't matter.
1064                     $aPhrases = array_reverse($aPhrases);
1065                     $aPhrases[0]->invertWordSets();
1066                     if (sizeof($aPhrases) > 1) {
1067                         $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
1068                     }
1069                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, false);
1070
1071                     foreach ($aGroupedSearches as $aSearches) {
1072                         foreach ($aSearches as $aSearch) {
1073                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1074                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1075                             }
1076                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1077                         }
1078                     }
1079
1080                     $aGroupedSearches = $aReverseGroupedSearches;
1081                     ksort($aGroupedSearches);
1082                 }
1083             } else {
1084                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1085                 $aGroupedSearches = array();
1086                 foreach ($aSearches as $aSearch) {
1087                     if ($aSearch->getRank() < $this->iMaxRank) {
1088                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1089                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1090                     }
1091                 }
1092                 ksort($aGroupedSearches);
1093             }
1094
1095             // Filter out duplicate searches
1096             $aSearchHash = array();
1097             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1098                 foreach ($aSearches as $iSearch => $aSearch) {
1099                     $sHash = serialize($aSearch);
1100                     if (isset($aSearchHash[$sHash])) {
1101                         unset($aGroupedSearches[$iGroup][$iSearch]);
1102                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1103                     } else {
1104                         $aSearchHash[$sHash] = 1;
1105                     }
1106                 }
1107             }
1108
1109             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1110
1111             // Start the search process
1112             $aResults = array();
1113             $iGroupLoop = 0;
1114             $iQueryLoop = 0;
1115             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1116                 $iGroupLoop++;
1117                 foreach ($aSearches as $oSearch) {
1118                     $iQueryLoop++;
1119
1120                     if (CONST_Debug) {
1121                         echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1122                         _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1123                     }
1124
1125                     $aResults += $oSearch->query(
1126                         $this->oDB,
1127                         $aWordFrequencyScores,
1128                         $this->iMinAddressRank,
1129                         $this->iMaxAddressRank,
1130                         $this->iLimit
1131                     );
1132
1133                     if ($iQueryLoop > 20) break;
1134                 }
1135
1136                 if (sizeof($aResults) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1137                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1138                     // reduces the number of place ids, like a filter
1139                     // rank_address is 30 for interpolated housenumbers
1140                     $aFilterSql = array();
1141                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
1142                     if ($sPlaceIds) {
1143                         $sSQL = 'SELECT place_id FROM placex ';
1144                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
1145                         $sSQL .= "  AND (";
1146                         $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1147                         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1148                             $sSQL .= "     OR (extratags->'place') = 'city'";
1149                         }
1150                         if ($this->aAddressRankList) {
1151                             $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1152                         }
1153                         $sSQL .= ")";
1154                         $aFilterSql[] = $sSQL;
1155                     }
1156                     $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_POSTCODE);
1157                     if ($sPlaceIds) {
1158                         $sSQL = ' SELECT place_id FROM location_postcode lp ';
1159                         $sSQL .= 'WHERE place_id in ('.$sPlaceIds.') ';
1160                         $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1161                         if ($this->aAddressRankList) {
1162                             $sSQL .= "     OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1163                         }
1164                         $sSQL .= ") ";
1165                         $aFilterSql[] = $sSQL;
1166                     }
1167
1168                     $aFilteredIDs = array();
1169                     if ($aFilterSql) {
1170                         $sSQL = join(' UNION ', $aFilterSql);
1171                         if (CONST_Debug) var_dump($sSQL);
1172                         $aFilteredIDs = chksql($this->oDB->getCol($sSQL));
1173                     }
1174
1175                     $tempIDs = array();
1176                     foreach ($aResults as $oResult) {
1177                         if (($this->iMaxAddressRank == 30 &&
1178                              ($oResult->iTable == Result::TABLE_OSMLINE
1179                               || $oResult->iTable == Result::TABLE_AUX
1180                               || $oResult->iTable == Result::TABLE_TIGER))
1181                             || in_array($oResult->iId, $aFilteredIDs)
1182                         ) {
1183                             $tempIDs[$oResult->iId] = $oResult;
1184                         }
1185                     }
1186                     $aResults = $tempIDs;
1187                 }
1188
1189                 if (sizeof($aResults)) break;
1190                 if ($iGroupLoop > 4) break;
1191                 if ($iQueryLoop > 30) break;
1192             }
1193
1194             $aSearchResults = $this->getDetails($aResults, $oCtx);
1195         } else {
1196             // Just interpret as a reverse geocode
1197             $oReverse = new ReverseGeocode($this->oDB);
1198             $oReverse->setZoom(18);
1199
1200             $oLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1201
1202             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1203
1204             if ($oLookup) {
1205                 $aResults = array($oLookup->iId => $oLookup);
1206                 $aSearchResults = $this->getDetails($aResults, $oCtx);
1207             } else {
1208                 $aSearchResults = array();
1209             }
1210         }
1211
1212         // No results? Done
1213         if (!sizeof($aSearchResults)) {
1214             if ($this->bFallback) {
1215                 if ($this->fallbackStructuredQuery()) {
1216                     return $this->lookup();
1217                 }
1218             }
1219
1220             return array();
1221         }
1222
1223         $aClassType = getClassTypesWithImportance();
1224         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1225         foreach ($aRecheckWords as $i => $sWord) {
1226             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1227         }
1228
1229         if (CONST_Debug) {
1230             echo '<i>Recheck words:<\i>';
1231             var_dump($aRecheckWords);
1232         }
1233
1234         $oPlaceLookup = new PlaceLookup($this->oDB);
1235         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1236         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1237         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1238         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1239         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1240         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1241
1242         foreach ($aSearchResults as $iResNum => $aResult) {
1243             // Default
1244             $fDiameter = getResultDiameter($aResult);
1245
1246             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1247             if ($aOutlineResult) {
1248                 $aResult = array_merge($aResult, $aOutlineResult);
1249             }
1250             
1251             if ($aResult['extra_place'] == 'city') {
1252                 $aResult['class'] = 'place';
1253                 $aResult['type'] = 'city';
1254                 $aResult['rank_search'] = 16;
1255             }
1256
1257             // Is there an icon set for this type of result?
1258             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1259                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1260             ) {
1261                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1262             }
1263
1264             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1265                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1266             ) {
1267                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1268             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1269                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1270             ) {
1271                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1272             }
1273             // if tag '&addressdetails=1' is set in query
1274             if ($this->bIncludeAddressDetails) {
1275                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1276                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResults[$aResult['place_id']]->iHouseNumber);
1277                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1278                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1279                 }
1280             }
1281
1282             if ($this->bIncludeExtraTags) {
1283                 if ($aResult['extra']) {
1284                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1285                 } else {
1286                     $aResult['sExtraTags'] = (object) array();
1287                 }
1288             }
1289
1290             if ($this->bIncludeNameDetails) {
1291                 if ($aResult['names']) {
1292                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1293                 } else {
1294                     $aResult['sNameDetails'] = (object) array();
1295                 }
1296             }
1297
1298             $aResult['name'] = $aResult['langaddress'];
1299
1300             if ($oCtx->hasNearPoint()) {
1301                 $aResult['importance'] = 0.001;
1302                 $aResult['foundorder'] = $aResult['addressimportance'];
1303             } else {
1304                 // Adjust importance for the number of exact string matches in the result
1305                 $aResult['importance'] = max(0.001, $aResult['importance']);
1306                 $iCountWords = 0;
1307                 $sAddress = $aResult['langaddress'];
1308                 foreach ($aRecheckWords as $i => $sWord) {
1309                     if (stripos($sAddress, $sWord)!==false) {
1310                         $iCountWords++;
1311                         if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1312                     }
1313                 }
1314
1315                 $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
1316
1317                 // secondary ordering (for results with same importance (the smaller the better):
1318                 // - approximate importance of address parts
1319                 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1320                 // - number of exact matches from the query
1321                 $aResult['foundorder'] -= $aResults[$aResult['place_id']]->iExactMatches;
1322                 // - importance of the class/type
1323                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1324                     && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1325                 ) {
1326                     $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1327                 } else {
1328                     $aResult['foundorder'] += 0.01;
1329                 }
1330             }
1331             if (CONST_Debug) var_dump($aResult);
1332             $aSearchResults[$iResNum] = $aResult;
1333         }
1334         uasort($aSearchResults, 'byImportance');
1335
1336         $aOSMIDDone = array();
1337         $aClassTypeNameDone = array();
1338         $aToFilter = $aSearchResults;
1339         $aSearchResults = array();
1340
1341         $bFirst = true;
1342         foreach ($aToFilter as $iResNum => $aResult) {
1343             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1344             if ($bFirst) {
1345                 $fLat = $aResult['lat'];
1346                 $fLon = $aResult['lon'];
1347                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1348                 $bFirst = false;
1349             }
1350             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1351                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1352             ) {
1353                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1354                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1355                 $aSearchResults[] = $aResult;
1356             }
1357
1358             // Absolute limit on number of results
1359             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1360         }
1361
1362         return $aSearchResults;
1363     } // end lookup()
1364 } // end class