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