]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
move viewbox sql to new SearchContext
[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 require_once(CONST_BasePath.'/lib/SearchDescription.php');
8 require_once(CONST_BasePath.'/lib/SearchContext.php');
9
10 class Geocode
11 {
12     protected $oDB;
13
14     protected $aLangPrefOrder = array();
15
16     protected $bIncludeAddressDetails = false;
17     protected $bIncludeExtraTags = false;
18     protected $bIncludeNameDetails = false;
19
20     protected $bIncludePolygonAsPoints = false;
21     protected $bIncludePolygonAsText = false;
22     protected $bIncludePolygonAsGeoJSON = false;
23     protected $bIncludePolygonAsKML = false;
24     protected $bIncludePolygonAsSVG = false;
25     protected $fPolygonSimplificationThreshold = 0.0;
26
27     protected $aExcludePlaceIDs = array();
28     protected $bDeDupe = true;
29     protected $bReverseInPlan = false;
30
31     protected $iLimit = 20;
32     protected $iFinalLimit = 10;
33     protected $iOffset = 0;
34     protected $bFallback = false;
35
36     protected $aCountryCodes = false;
37
38     protected $bBoundedSearch = false;
39     protected $aViewBox = false;
40     protected $aRoutePoints = false;
41     protected $aRouteWidth = 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     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($aPlaceIDs, $oCtx)
368     {
369         //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
370         if (sizeof($aPlaceIDs) == 0) return array();
371
372         $sLanguagePrefArraySQL = getArraySQL(
373             array_map("getDBQuoted", $this->aLangPrefOrder)
374         );
375
376         // Get the details for display (is this a redundant extra step?)
377         $sPlaceIDs = join(',', array_keys($aPlaceIDs));
378
379         $sImportanceSQL = $oCtx->viewboxImportanceSQL('ST_Collect(centroid)');
380         $sImportanceSQLGeom = $oCtx->viewboxImportanceSQL('geometry');
381
382         $sSQL  = "SELECT ";
383         $sSQL .= "    osm_type,";
384         $sSQL .= "    osm_id,";
385         $sSQL .= "    class,";
386         $sSQL .= "    type,";
387         $sSQL .= "    admin_level,";
388         $sSQL .= "    rank_search,";
389         $sSQL .= "    rank_address,";
390         $sSQL .= "    min(place_id) AS place_id, ";
391         $sSQL .= "    min(parent_place_id) AS parent_place_id, ";
392         $sSQL .= "    country_code, ";
393         $sSQL .= "    get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
394         $sSQL .= "    get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
395         $sSQL .= "    get_name_by_language(name, ARRAY['ref']) AS ref,";
396         if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
397         if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
398         $sSQL .= "    avg(ST_X(centroid)) AS lon, ";
399         $sSQL .= "    avg(ST_Y(centroid)) AS lat, ";
400         $sSQL .= "    COALESCE(importance,0.75-(rank_search::float/40)) $sImportanceSQL AS importance, ";
401         $sSQL .= "    ( ";
402         $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
403         $sSQL .= "       FROM ";
404         $sSQL .= "         place_addressline s, ";
405         $sSQL .= "         placex p";
406         $sSQL .= "       WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
407         $sSQL .= "         AND p.place_id = s.address_place_id ";
408         $sSQL .= "         AND s.isaddress ";
409         $sSQL .= "         AND p.importance is not null ";
410         $sSQL .= "    ) AS addressimportance, ";
411         $sSQL .= "    (extratags->'place') AS extra_place ";
412         $sSQL .= " FROM placex";
413         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
414         $sSQL .= "   AND (";
415         $sSQL .= "            placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
416         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
417             $sSQL .= "        OR (extratags->'place') = 'city'";
418         }
419         if ($this->aAddressRankList) {
420             $sSQL .= "        OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
421         }
422         $sSQL .= "       ) ";
423         if ($this->sAllowedTypesSQLList) {
424             $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
425         }
426         $sSQL .= "    AND linked_place_id is null ";
427         $sSQL .= " GROUP BY ";
428         $sSQL .= "     osm_type, ";
429         $sSQL .= "     osm_id, ";
430         $sSQL .= "     class, ";
431         $sSQL .= "     type, ";
432         $sSQL .= "     admin_level, ";
433         $sSQL .= "     rank_search, ";
434         $sSQL .= "     rank_address, ";
435         $sSQL .= "     country_code, ";
436         $sSQL .= "     importance, ";
437         if (!$this->bDeDupe) $sSQL .= "place_id,";
438         $sSQL .= "     langaddress, ";
439         $sSQL .= "     placename, ";
440         $sSQL .= "     ref, ";
441         if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
442         if ($this->bIncludeNameDetails) $sSQL .= "name, ";
443         $sSQL .= "     extratags->'place' ";
444
445         // postcode table
446         $sSQL .= "UNION ";
447         $sSQL .= "SELECT";
448         $sSQL .= "  'P' as osm_type,";
449         $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
450         $sSQL .= "  'place' as class, 'postcode' as type,";
451         $sSQL .= "  null as admin_level, rank_search, rank_address,";
452         $sSQL .= "  place_id, parent_place_id, country_code,";
453         $sSQL .= "  get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
454         $sSQL .= "  postcode as placename,";
455         $sSQL .= "  postcode as ref,";
456         if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
457         if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
458         $sSQL .= "  ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
459         $sSQL .= "  (0.75-(rank_search::float/40)) $sImportanceSQLGeom AS importance, ";
460         $sSQL .= "  (";
461         $sSQL .= "     SELECT max(p.importance*(p.rank_address+2))";
462         $sSQL .= "     FROM ";
463         $sSQL .= "       place_addressline s, ";
464         $sSQL .= "       placex p";
465         $sSQL .= "     WHERE s.place_id = lp.parent_place_id";
466         $sSQL .= "       AND p.place_id = s.address_place_id ";
467         $sSQL .= "       AND s.isaddress";
468         $sSQL .= "       AND p.importance is not null";
469         $sSQL .= "  ) AS addressimportance, ";
470         $sSQL .= "  null AS extra_place ";
471         $sSQL .= "FROM location_postcode lp";
472         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
473
474         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
475             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
476             // with start- and endnumber, the common osm housenumbers are usually saved as points
477             $sHousenumbers = "";
478             $i = 0;
479             $length = count($aPlaceIDs);
480             foreach ($aPlaceIDs as $placeID => $housenumber) {
481                 $i++;
482                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
483                 if ($i<$length) $sHousenumbers .= ", ";
484             }
485
486             if (CONST_Use_US_Tiger_Data) {
487                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
488                 $sSQL .= " union";
489                 $sSQL .= " SELECT ";
490                 $sSQL .= "     'T' AS osm_type, ";
491                 $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
492                 $sSQL .= "     'place' AS class, ";
493                 $sSQL .= "     'house' AS type, ";
494                 $sSQL .= "     null AS admin_level, ";
495                 $sSQL .= "     30 AS rank_search, ";
496                 $sSQL .= "     30 AS rank_address, ";
497                 $sSQL .= "     min(place_id) AS place_id, ";
498                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
499                 $sSQL .= "     'us' AS country_code, ";
500                 $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
501                 $sSQL .= "     null AS placename, ";
502                 $sSQL .= "     null AS ref, ";
503                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
504                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
505                 $sSQL .= "     avg(st_x(centroid)) AS lon, ";
506                 $sSQL .= "     avg(st_y(centroid)) AS lat,";
507                 $sSQL .= "     -1.15".$sImportanceSQL." AS importance, ";
508                 $sSQL .= "     (";
509                 $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
510                 $sSQL .= "        FROM ";
511                 $sSQL .= "          place_addressline s, ";
512                 $sSQL .= "          placex p";
513                 $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
514                 $sSQL .= "          AND p.place_id = s.address_place_id ";
515                 $sSQL .= "          AND s.isaddress";
516                 $sSQL .= "          AND p.importance is not null";
517                 $sSQL .= "     ) AS addressimportance, ";
518                 $sSQL .= "     null AS extra_place ";
519                 $sSQL .= " FROM (";
520                 $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
521                 $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
522                 $sSQL .= "         parent_place_id, ";
523                 $sSQL .= "         housenumber_for_place";
524                 $sSQL .= "     FROM (";
525                 $sSQL .= "            location_property_tiger ";
526                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
527                 $sSQL .= "     WHERE ";
528                 $sSQL .= "         housenumber_for_place>=0";
529                 $sSQL .= "         AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
530                 $sSQL .= " ) AS blub"; //postgres wants an alias here
531                 $sSQL .= " GROUP BY";
532                 $sSQL .= "      place_id, ";
533                 $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
534                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
535             }
536             // osmline
537             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
538             $sSQL .= " UNION ";
539             $sSQL .= "SELECT ";
540             $sSQL .= "  'W' AS osm_type, ";
541             $sSQL .= "  osm_id, ";
542             $sSQL .= "  'place' AS class, ";
543             $sSQL .= "  'house' AS type, ";
544             $sSQL .= "  null AS admin_level, ";
545             $sSQL .= "  30 AS rank_search, ";
546             $sSQL .= "  30 AS rank_address, ";
547             $sSQL .= "  min(place_id) as place_id, ";
548             $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
549             $sSQL .= "  country_code, ";
550             $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
551             $sSQL .= "  null AS placename, ";
552             $sSQL .= "  null AS ref, ";
553             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
554             if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
555             $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
556             $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
557             $sSQL .= "  -0.1".$sImportanceSQL." AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
558             $sSQL .= "  (";
559             $sSQL .= "     SELECT ";
560             $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
561             $sSQL .= "     FROM";
562             $sSQL .= "       place_addressline s, ";
563             $sSQL .= "       placex p";
564             $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
565             $sSQL .= "       AND p.place_id = s.address_place_id ";
566             $sSQL .= "       AND s.isaddress ";
567             $sSQL .= "       AND p.importance is not null";
568             $sSQL .= "  ) AS addressimportance,";
569             $sSQL .= "  null AS extra_place ";
570             $sSQL .= "  FROM (";
571             $sSQL .= "     SELECT ";
572             $sSQL .= "         osm_id, ";
573             $sSQL .= "         place_id, ";
574             $sSQL .= "         country_code, ";
575             $sSQL .= "         CASE ";             // interpolate the housenumbers here
576             $sSQL .= "           WHEN startnumber != endnumber ";
577             $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
578             $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
579             $sSQL .= "         END as centroid, ";
580             $sSQL .= "         parent_place_id, ";
581             $sSQL .= "         housenumber_for_place ";
582             $sSQL .= "     FROM (";
583             $sSQL .= "            location_property_osmline ";
584             $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
585             $sSQL .= "          ) ";
586             $sSQL .= "     WHERE housenumber_for_place>=0 ";
587             $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
588             $sSQL .= "  ) as blub"; //postgres wants an alias here
589             $sSQL .= "  GROUP BY ";
590             $sSQL .= "    osm_id, ";
591             $sSQL .= "    place_id, ";
592             $sSQL .= "    housenumber_for_place, ";
593             $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
594             if (!$this->bDeDupe) $sSQL .= ", place_id ";
595
596             if (CONST_Use_Aux_Location_data) {
597                 $sSQL .= " UNION ";
598                 $sSQL .= "  SELECT ";
599                 $sSQL .= "     'L' AS osm_type, ";
600                 $sSQL .= "     place_id AS osm_id, ";
601                 $sSQL .= "     'place' AS class,";
602                 $sSQL .= "     'house' AS type, ";
603                 $sSQL .= "     null AS admin_level, ";
604                 $sSQL .= "     0 AS rank_search,";
605                 $sSQL .= "     0 AS rank_address, ";
606                 $sSQL .= "     min(place_id) AS place_id,";
607                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
608                 $sSQL .= "     'us' AS country_code, ";
609                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
610                 $sSQL .= "     null AS placename, ";
611                 $sSQL .= "     null AS ref, ";
612                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
613                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
614                 $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
615                 $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
616                 $sSQL .= "     -1.10".$sImportanceSQL." AS importance, ";
617                 $sSQL .= "     ( ";
618                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
619                 $sSQL .= "       FROM ";
620                 $sSQL .= "          place_addressline s, ";
621                 $sSQL .= "          placex p";
622                 $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
623                 $sSQL .= "         AND p.place_id = s.address_place_id ";
624                 $sSQL .= "         AND s.isaddress";
625                 $sSQL .= "         AND p.importance is not null";
626                 $sSQL .= "     ) AS addressimportance, ";
627                 $sSQL .= "     null AS extra_place ";
628                 $sSQL .= "  FROM location_property_aux ";
629                 $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
630                 $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
631                 $sSQL .= "  GROUP BY ";
632                 $sSQL .= "     place_id, ";
633                 if (!$this->bDeDupe) $sSQL .= "place_id, ";
634                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
635             }
636         }
637
638         $sSQL .= " order by importance desc";
639         if (CONST_Debug) {
640             echo "<hr>";
641             var_dump($sSQL);
642         }
643         $aSearchResults = chksql(
644             $this->oDB->getAll($sSQL),
645             "Could not get details for place."
646         );
647
648         return $aSearchResults;
649     }
650
651     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
652     {
653         /*
654              Calculate all searches using aValidTokens i.e.
655              'Wodsworth Road, Sheffield' =>
656
657              Phrase Wordset
658              0      0       (wodsworth road)
659              0      1       (wodsworth)(road)
660              1      0       (sheffield)
661
662              Score how good the search is so they can be ordered
663          */
664         $iGlobalRank = 0;
665
666         foreach ($aPhrases as $iPhrase => $aPhrase) {
667             $aNewPhraseSearches = array();
668             if ($bStructuredPhrases) {
669                 $sPhraseType = $aPhraseTypes[$iPhrase];
670             } else {
671                 $sPhraseType = '';
672             }
673
674             foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
675                 // Too many permutations - too expensive
676                 if ($iWordSet > 120) break;
677
678                 $aWordsetSearches = $aSearches;
679
680                 // Add all words from this wordset
681                 foreach ($aWordset as $iToken => $sToken) {
682                     //echo "<br><b>$sToken</b>";
683                     $aNewWordsetSearches = array();
684
685                     foreach ($aWordsetSearches as $oCurrentSearch) {
686                         //echo "<i>";
687                         //var_dump($oCurrentSearch);
688                         //echo "</i>";
689
690                         // If the token is valid
691                         if (isset($aValidTokens[' '.$sToken])) {
692                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
693                                 // Recheck if the original word shows up in the query.
694                                 $bWordInQuery = false;
695                                 if (isset($aSearchTerm['word']) && $aSearchTerm['word']) {
696                                     $bWordInQuery = strpos(
697                                         $sNormQuery,
698                                         $this->normTerm($aSearchTerm['word'])
699                                     ) !== false;
700                                 }
701                                 $aNewSearches = $oCurrentSearch->extendWithFullTerm(
702                                     $aSearchTerm,
703                                     $bWordInQuery,
704                                     isset($aValidTokens[$sToken])
705                                       && strpos($sToken, ' ') === false,
706                                     $sPhraseType,
707                                     $iToken == 0 && $iPhrase == 0,
708                                     $iPhrase == 0,
709                                     $iToken + 1 == sizeof($aWordset)
710                                       && $iPhrase + 1 == sizeof($aPhrases),
711                                     $iGlobalRank
712                                 );
713
714                                 foreach ($aNewSearches as $oSearch) {
715                                     if ($oSearch->getRank() < $this->iMaxRank) {
716                                         $aNewWordsetSearches[] = $oSearch;
717                                     }
718                                 }
719                             }
720                         }
721                         // Look for partial matches.
722                         // Note that there is no point in adding country terms here
723                         // because country is omitted in the address.
724                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
725                             // Allow searching for a word - but at extra cost
726                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
727                                 $aNewSearches = $oCurrentSearch->extendWithPartialTerm(
728                                     $aSearchTerm,
729                                     $bStructuredPhrases,
730                                     $iPhrase,
731                                     $aWordFrequencyScores,
732                                     isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
733                                 );
734
735                                 foreach ($aNewSearches as $oSearch) {
736                                     if ($oSearch->getRank() < $this->iMaxRank) {
737                                         $aNewWordsetSearches[] = $oSearch;
738                                     }
739                                 }
740                             }
741                         }
742                     }
743                     // Sort and cut
744                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
745                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
746                 }
747                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
748
749                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
750                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
751
752                 $aSearchHash = array();
753                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
754                     $sHash = serialize($aSearch);
755                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
756                     else $aSearchHash[$sHash] = 1;
757                 }
758
759                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
760             }
761
762             // Re-group the searches by their score, junk anything over 20 as just not worth trying
763             $aGroupedSearches = array();
764             foreach ($aNewPhraseSearches as $aSearch) {
765                 $iRank = $aSearch->getRank();
766                 if ($iRank < $this->iMaxRank) {
767                     if (!isset($aGroupedSearches[$iRank])) {
768                         $aGroupedSearches[$iRank] = array();
769                     }
770                     $aGroupedSearches[$iRank][] = $aSearch;
771                 }
772             }
773             ksort($aGroupedSearches);
774
775             $iSearchCount = 0;
776             $aSearches = array();
777             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
778                 $iSearchCount += sizeof($aNewSearches);
779                 $aSearches = array_merge($aSearches, $aNewSearches);
780                 if ($iSearchCount > 50) break;
781             }
782
783             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
784         }
785
786         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
787         $aGroupedSearches = array();
788         foreach ($aSearches as $oSearch) {
789             if (!$oSearch->isValidSearch($this->aCountryCodes)) {
790                 continue;
791             }
792
793             $iRank = $oSearch->addToRank($iGlobalRank);
794             if (!isset($aGroupedSearches[$iRank])) {
795                 $aGroupedSearches[$iRank] = array();
796             }
797             $aGroupedSearches[$iRank][] = $oSearch;
798         }
799         ksort($aGroupedSearches);
800
801         return $aGroupedSearches;
802     }
803
804     /* Perform the actual query lookup.
805
806         Returns an ordered list of results, each with the following fields:
807             osm_type: type of corresponding OSM object
808                         N - node
809                         W - way
810                         R - relation
811                         P - postcode (internally computed)
812             osm_id: id of corresponding OSM object
813             class: general object class (corresponds to tag key of primary OSM tag)
814             type: subclass of object (corresponds to tag value of primary OSM tag)
815             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
816             rank_search: rank in search hierarchy
817                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
818             rank_address: rank in address hierarchy (determines orer in address)
819             place_id: internal key (may differ between different instances)
820             country_code: ISO country code
821             langaddress: localized full address
822             placename: localized name of object
823             ref: content of ref tag (if available)
824             lon: longitude
825             lat: latitude
826             importance: importance of place based on Wikipedia link count
827             addressimportance: cumulated importance of address elements
828             extra_place: type of place (for admin boundaries, if there is a place tag)
829             aBoundingBox: bounding Box
830             label: short description of the object class/type (English only)
831             name: full name (currently the same as langaddress)
832             foundorder: secondary ordering for places with same importance
833     */
834
835
836     public function lookup()
837     {
838         if (!$this->sQuery && !$this->aStructuredQuery) return array();
839
840         $oCtx = new SearchContext();
841
842         if ($this->aRoutePoints) {
843             $oCtx->setViewboxFromRoute(
844                 $this->oDB,
845                 $this->aRoutePoints,
846                 $this->aRouteWidth,
847                 $this->bBoundedSearch
848             );
849         } else if ($this->aViewBox) {
850             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
851         }
852
853         $sNormQuery = $this->normTerm($this->sQuery);
854         $sLanguagePrefArraySQL = getArraySQL(
855             array_map("getDBQuoted", $this->aLangPrefOrder)
856         );
857         $sCountryCodesSQL = false;
858         if ($this->aCountryCodes) {
859             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
860         }
861
862         $sQuery = $this->sQuery;
863         if (!preg_match('//u', $sQuery)) {
864             userError("Query string is not UTF-8 encoded.");
865         }
866
867         // Conflicts between US state abreviations and various words for 'the' in different languages
868         if (isset($this->aLangPrefOrder['name:en'])) {
869             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
870             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
871             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
872         }
873
874         // Do we have anything that looks like a lat/lon pair?
875         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
876
877         $aSearchResults = array();
878         if ($sQuery || $this->aStructuredQuery) {
879             // Start with a single blank search
880             $aSearches = array(new SearchDescription($oCtx));
881
882             if ($sQuery) {
883                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
884             }
885
886             $sSpecialTerm = '';
887             if ($sQuery) {
888                 preg_match_all(
889                     '/\\[([\\w ]*)\\]/u',
890                     $sQuery,
891                     $aSpecialTermsRaw,
892                     PREG_SET_ORDER
893                 );
894                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
895                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
896                     if (!$sSpecialTerm) {
897                         $sSpecialTerm = $aSpecialTerm[1];
898                     }
899                 }
900             }
901             if (!$sSpecialTerm && $this->aStructuredQuery
902                 && isset($this->aStructuredQuery['amenity'])) {
903                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
904                 unset($this->aStructuredQuery['amenity']);
905             }
906
907             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
908                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
909                 $sToken = chksql(
910                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
911                     "Cannot decode query. Wrong encoding?"
912                 );
913                 $sSQL = 'SELECT class, type FROM word ';
914                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
915                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
916                 if (CONST_Debug) var_Dump($sSQL);
917                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
918                 $aNewSearches = array();
919                 foreach ($aSearches as $oSearch) {
920                     foreach ($aSearchWords as $aSearchTerm) {
921                         $oNewSearch = clone $oSearch;
922                         $oNewSearch->setPoiSearch(
923                             Operator::TYPE,
924                             $aSearchTerm['class'],
925                             $aSearchTerm['type']
926                         );
927                         $aNewSearches[] = $oNewSearch;
928                     }
929                 }
930                 $aSearches = $aNewSearches;
931             }
932
933             // Split query into phrases
934             // Commas are used to reduce the search space by indicating where phrases split
935             if ($this->aStructuredQuery) {
936                 $aPhrases = $this->aStructuredQuery;
937                 $bStructuredPhrases = true;
938             } else {
939                 $aPhrases = explode(',', $sQuery);
940                 $bStructuredPhrases = false;
941             }
942
943             // Convert each phrase to standard form
944             // Create a list of standard words
945             // Get all 'sets' of words
946             // Generate a complete list of all
947             $aTokens = array();
948             foreach ($aPhrases as $iPhrase => $sPhrase) {
949                 $aPhrase = chksql(
950                     $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
951                     "Cannot normalize query string (is it a UTF-8 string?)"
952                 );
953                 if (trim($aPhrase['string'])) {
954                     $aPhrases[$iPhrase] = $aPhrase;
955                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
956                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
957                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
958                 } else {
959                     unset($aPhrases[$iPhrase]);
960                 }
961             }
962
963             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
964             $aPhraseTypes = array_keys($aPhrases);
965             $aPhrases = array_values($aPhrases);
966
967             if (sizeof($aTokens)) {
968                 // Check which tokens we have, get the ID numbers
969                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
970                 $sSQL .= ' FROM word ';
971                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
972
973                 if (CONST_Debug) var_Dump($sSQL);
974
975                 $aValidTokens = array();
976                 $aDatabaseWords = chksql(
977                     $this->oDB->getAll($sSQL),
978                     "Could not get word tokens."
979                 );
980                 $aPossibleMainWordIDs = array();
981                 $aWordFrequencyScores = array();
982                 foreach ($aDatabaseWords as $aToken) {
983                     // Very special case - require 2 letter country param to match the country code found
984                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
985                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
986                     ) {
987                         continue;
988                     }
989
990                     if (isset($aValidTokens[$aToken['word_token']])) {
991                         $aValidTokens[$aToken['word_token']][] = $aToken;
992                     } else {
993                         $aValidTokens[$aToken['word_token']] = array($aToken);
994                     }
995                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
996                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
997                 }
998                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
999
1000                 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1001                 foreach ($aTokens as $sToken) {
1002                     if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1003                         if (isset($aValidTokens[$aData[1]])) {
1004                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1005                                 if (!$aToken['class']) {
1006                                     if (isset($aValidTokens[$sToken])) {
1007                                         $aValidTokens[$sToken][] = $aToken;
1008                                     } else {
1009                                         $aValidTokens[$sToken] = array($aToken);
1010                                     }
1011                                 }
1012                             }
1013                         }
1014                     }
1015                 }
1016
1017                 foreach ($aTokens as $sToken) {
1018                     // Unknown single word token with a number - assume it is a house number
1019                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1020                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1021                     }
1022                 }
1023
1024                 // Any words that have failed completely?
1025                 // TODO: suggestions
1026
1027                 // Start the search process
1028                 // array with: placeid => -1 | tiger-housenumber
1029                 $aResultPlaceIDs = array();
1030
1031                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1032
1033                 if ($this->bReverseInPlan) {
1034                     // Reverse phrase array and also reverse the order of the wordsets in
1035                     // the first and final phrase. Don't bother about phrases in the middle
1036                     // because order in the address doesn't matter.
1037                     $aPhrases = array_reverse($aPhrases);
1038                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1039                     if (sizeof($aPhrases) > 1) {
1040                         $aFinalPhrase = end($aPhrases);
1041                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1042                     }
1043                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1044
1045                     foreach ($aGroupedSearches as $aSearches) {
1046                         foreach ($aSearches as $aSearch) {
1047                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1048                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1049                             }
1050                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1051                         }
1052                     }
1053
1054                     $aGroupedSearches = $aReverseGroupedSearches;
1055                     ksort($aGroupedSearches);
1056                 }
1057             } else {
1058                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1059                 $aGroupedSearches = array();
1060                 foreach ($aSearches as $aSearch) {
1061                     if ($aSearch->getRank() < $this->iMaxRank) {
1062                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1063                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1064                     }
1065                 }
1066                 ksort($aGroupedSearches);
1067             }
1068
1069             // Filter out duplicate searches
1070             $aSearchHash = array();
1071             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1072                 foreach ($aSearches as $iSearch => $aSearch) {
1073                     $sHash = serialize($aSearch);
1074                     if (isset($aSearchHash[$sHash])) {
1075                         unset($aGroupedSearches[$iGroup][$iSearch]);
1076                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1077                     } else {
1078                         $aSearchHash[$sHash] = 1;
1079                     }
1080                 }
1081             }
1082
1083             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1084
1085             $iGroupLoop = 0;
1086             $iQueryLoop = 0;
1087             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1088                 $iGroupLoop++;
1089                 foreach ($aSearches as $oSearch) {
1090                     $iQueryLoop++;
1091                     $searchedHousenumber = -1;
1092
1093                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1094                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1095
1096                     $aPlaceIDs = array();
1097                     if ($oSearch->isCountrySearch()) {
1098                         // Just looking for a country - look it up
1099                         if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1100                             $aPlaceIDs = $oSearch->queryCountry($this->oDB);
1101                         }
1102                     } elseif (!$oSearch->isNamedSearch()) {
1103                         // looking for a POI in a geographic area
1104                         if (!$oCtx->isBoundedSearch()) {
1105                             continue;
1106                         }
1107
1108                         $aPlaceIDs = $oSearch->queryNearbyPoi(
1109                             $this->oDB,
1110                             $sCountryCodesSQL,
1111                             $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1112                             $this->iLimit
1113                         );
1114                     } elseif ($oSearch->isOperator(Operator::POSTCODE)) {
1115                         $aPlaceIDs = $oSearch->queryPostcode(
1116                             $this->oDB,
1117                             $sCountryCodesSQL,
1118                             $this->iLimit
1119                         );
1120                     } else {
1121                         // Ordinary search:
1122                         // First search for places according to name and address.
1123                         $aNamedPlaceIDs = $oSearch->queryNamedPlace(
1124                             $this->oDB,
1125                             $aWordFrequencyScores,
1126                             $sCountryCodesSQL,
1127                             $this->iMinAddressRank,
1128                             $this->iMaxAddressRank,
1129                             $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1130                             $this->iLimit
1131                         );
1132
1133                         if (sizeof($aNamedPlaceIDs)) {
1134                             foreach ($aNamedPlaceIDs as $aRow) {
1135                                 $aPlaceIDs[] = $aRow['place_id'];
1136                                 $this->exactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
1137                             }
1138                         }
1139
1140                         //now search for housenumber, if housenumber provided
1141                         if ($oSearch->hasHouseNumber() && sizeof($aPlaceIDs)) {
1142                             $aResult = $oSearch->queryHouseNumber(
1143                                 $this->oDB,
1144                                 $aPlaceIDs,
1145                                 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1146                                 $this->iLimit
1147                             );
1148
1149                             if (sizeof($aResult)) {
1150                                 $searchedHousenumber = $aResult['iHouseNumber'];
1151                                 $aPlaceIDs = $aResult['aPlaceIDs'];
1152                             } elseif (!$oSearch->looksLikeFullAddress()) {
1153                                 $aPlaceIDs = array();
1154                             }
1155                         }
1156
1157                         // finally get POIs if requested
1158                         if ($oSearch->isPoiSearch() && sizeof($aPlaceIDs)) {
1159                             $aPlaceIDs = $oSearch->queryPoiByOperator(
1160                                 $this->oDB,
1161                                 $aPlaceIDs,
1162                                 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1163                                 $this->iLimit
1164                             );
1165                         }
1166                     }
1167
1168                     if (CONST_Debug) {
1169                         echo "<br><b>Place IDs:</b> ";
1170                         var_Dump($aPlaceIDs);
1171                     }
1172
1173                     if (sizeof($aPlaceIDs) && $oSearch->getPostcode()) {
1174                         $sSQL = 'SELECT place_id FROM placex';
1175                         $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1176                         $sSQL .= " AND postcode = '".$oSearch->getPostcode()."'";
1177                         if (CONST_Debug) var_dump($sSQL);
1178                         $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1179                         if ($aFilteredPlaceIDs) {
1180                             $aPlaceIDs = $aFilteredPlaceIDs;
1181                             if (CONST_Debug) {
1182                                 echo "<br><b>Place IDs after postcode filtering:</b> ";
1183                                 var_Dump($aPlaceIDs);
1184                             }
1185                         }
1186                     }
1187
1188                     foreach ($aPlaceIDs as $iPlaceID) {
1189                         // array for placeID => -1 | Tiger housenumber
1190                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1191                     }
1192                     if ($iQueryLoop > 20) break;
1193                 }
1194
1195                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1196                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1197                     // reduces the number of place ids, like a filter
1198                     // rank_address is 30 for interpolated housenumbers
1199                     $sWherePlaceId = 'WHERE place_id in (';
1200                     $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1201
1202                     $sSQL = "SELECT place_id ";
1203                     $sSQL .= "FROM placex ".$sWherePlaceId;
1204                     $sSQL .= "  AND (";
1205                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1206                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1207                         $sSQL .= "     OR (extratags->'place') = 'city'";
1208                     }
1209                     if ($this->aAddressRankList) {
1210                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1211                     }
1212                     $sSQL .= "  ) UNION ";
1213                     $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1214                     $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1215                     if ($this->aAddressRankList) {
1216                         $sSQL .= "     OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1217                     }
1218                     $sSQL .= ") ";
1219                     if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1220                         $sSQL .= "UNION ";
1221                         $sSQL .= "  SELECT place_id ";
1222                         $sSQL .= "  FROM location_property_tiger ".$sWherePlaceId;
1223                     }
1224                     if ($this->iMaxAddressRank == 30) {
1225                         $sSQL .= "UNION ";
1226                         $sSQL .= "  SELECT place_id ";
1227                         $sSQL .= "  FROM location_property_osmline ".$sWherePlaceId;
1228                     }
1229                     if (CONST_Debug) var_dump($sSQL);
1230                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1231                     $tempIDs = array();
1232                     foreach ($aFilteredPlaceIDs as $placeID) {
1233                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1234                     }
1235                     $aResultPlaceIDs = $tempIDs;
1236                 }
1237
1238                 //exit;
1239                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1240                 if ($iGroupLoop > 4) break;
1241                 if ($iQueryLoop > 30) break;
1242             }
1243
1244             // Did we find anything?
1245             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1246                 $aSearchResults = $this->getDetails($aResultPlaceIDs, $oCtx);
1247             }
1248         } else {
1249             // Just interpret as a reverse geocode
1250             $oReverse = new ReverseGeocode($this->oDB);
1251             $oReverse->setZoom(18);
1252
1253             $aLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1254
1255             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1256
1257             if ($aLookup['place_id']) {
1258                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1), $oCtx);
1259                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1260             } else {
1261                 $aSearchResults = array();
1262             }
1263         }
1264
1265         // No results? Done
1266         if (!sizeof($aSearchResults)) {
1267             if ($this->bFallback) {
1268                 if ($this->fallbackStructuredQuery()) {
1269                     return $this->lookup();
1270                 }
1271             }
1272
1273             return array();
1274         }
1275
1276         $aClassType = getClassTypesWithImportance();
1277         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1278         foreach ($aRecheckWords as $i => $sWord) {
1279             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1280         }
1281
1282         if (CONST_Debug) {
1283             echo '<i>Recheck words:<\i>';
1284             var_dump($aRecheckWords);
1285         }
1286
1287         $oPlaceLookup = new PlaceLookup($this->oDB);
1288         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1289         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1290         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1291         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1292         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1293         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1294
1295         foreach ($aSearchResults as $iResNum => $aResult) {
1296             // Default
1297             $fDiameter = getResultDiameter($aResult);
1298
1299             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1300             if ($aOutlineResult) {
1301                 $aResult = array_merge($aResult, $aOutlineResult);
1302             }
1303             
1304             if ($aResult['extra_place'] == 'city') {
1305                 $aResult['class'] = 'place';
1306                 $aResult['type'] = 'city';
1307                 $aResult['rank_search'] = 16;
1308             }
1309
1310             // Is there an icon set for this type of result?
1311             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1312                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1313             ) {
1314                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1315             }
1316
1317             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1318                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1319             ) {
1320                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1321             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1322                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1323             ) {
1324                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1325             }
1326             // if tag '&addressdetails=1' is set in query
1327             if ($this->bIncludeAddressDetails) {
1328                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1329                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1330                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1331                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1332                 }
1333             }
1334
1335             if ($this->bIncludeExtraTags) {
1336                 if ($aResult['extra']) {
1337                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1338                 } else {
1339                     $aResult['sExtraTags'] = (object) array();
1340                 }
1341             }
1342
1343             if ($this->bIncludeNameDetails) {
1344                 if ($aResult['names']) {
1345                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1346                 } else {
1347                     $aResult['sNameDetails'] = (object) array();
1348                 }
1349             }
1350
1351             // Adjust importance for the number of exact string matches in the result
1352             $aResult['importance'] = max(0.001, $aResult['importance']);
1353             $iCountWords = 0;
1354             $sAddress = $aResult['langaddress'];
1355             foreach ($aRecheckWords as $i => $sWord) {
1356                 if (stripos($sAddress, $sWord)!==false) {
1357                     $iCountWords++;
1358                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1359                 }
1360             }
1361
1362             $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
1363
1364             $aResult['name'] = $aResult['langaddress'];
1365             // secondary ordering (for results with same importance (the smaller the better):
1366             // - approximate importance of address parts
1367             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1368             // - number of exact matches from the query
1369             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1370                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1371             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1372                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1373             }
1374             // - importance of the class/type
1375             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1376                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1377             ) {
1378                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1379             } else {
1380                 $aResult['foundorder'] += 0.01;
1381             }
1382             if (CONST_Debug) var_dump($aResult);
1383             $aSearchResults[$iResNum] = $aResult;
1384         }
1385         uasort($aSearchResults, 'byImportance');
1386
1387         $aOSMIDDone = array();
1388         $aClassTypeNameDone = array();
1389         $aToFilter = $aSearchResults;
1390         $aSearchResults = array();
1391
1392         $bFirst = true;
1393         foreach ($aToFilter as $iResNum => $aResult) {
1394             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1395             if ($bFirst) {
1396                 $fLat = $aResult['lat'];
1397                 $fLon = $aResult['lon'];
1398                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1399                 $bFirst = false;
1400             }
1401             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1402                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1403             ) {
1404                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1405                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1406                 $aSearchResults[] = $aResult;
1407             }
1408
1409             // Absolute limit on number of results
1410             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1411         }
1412
1413         return $aSearchResults;
1414     } // end lookup()
1415 } // end class