]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
convert phrase array to class
[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, $aWordFrequencyScores, $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                                     $aWordFrequencyScores,
749                                     isset($aValidTokens[' '.$sToken]) ? $aValidTokens[' '.$sToken] : array()
750                                 );
751
752                                 foreach ($aNewSearches as $oSearch) {
753                                     if ($oSearch->getRank() < $this->iMaxRank) {
754                                         $aNewWordsetSearches[] = $oSearch;
755                                     }
756                                 }
757                             }
758                         }
759                     }
760                     // Sort and cut
761                     usort($aNewWordsetSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
762                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
763                 }
764                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
765
766                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
767                 usort($aNewPhraseSearches, array('Nominatim\SearchDescription', 'bySearchRank'));
768
769                 $aSearchHash = array();
770                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
771                     $sHash = serialize($aSearch);
772                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
773                     else $aSearchHash[$sHash] = 1;
774                 }
775
776                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
777             }
778
779             // Re-group the searches by their score, junk anything over 20 as just not worth trying
780             $aGroupedSearches = array();
781             foreach ($aNewPhraseSearches as $aSearch) {
782                 $iRank = $aSearch->getRank();
783                 if ($iRank < $this->iMaxRank) {
784                     if (!isset($aGroupedSearches[$iRank])) {
785                         $aGroupedSearches[$iRank] = array();
786                     }
787                     $aGroupedSearches[$iRank][] = $aSearch;
788                 }
789             }
790             ksort($aGroupedSearches);
791
792             $iSearchCount = 0;
793             $aSearches = array();
794             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
795                 $iSearchCount += sizeof($aNewSearches);
796                 $aSearches = array_merge($aSearches, $aNewSearches);
797                 if ($iSearchCount > 50) break;
798             }
799
800             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
801         }
802
803         // Revisit searches, drop bad searches and give penalty to unlikely combinations.
804         $aGroupedSearches = array();
805         foreach ($aSearches as $oSearch) {
806             if (!$oSearch->isValidSearch($this->aCountryCodes)) {
807                 continue;
808             }
809
810             $iRank = $oSearch->addToRank($iGlobalRank);
811             if (!isset($aGroupedSearches[$iRank])) {
812                 $aGroupedSearches[$iRank] = array();
813             }
814             $aGroupedSearches[$iRank][] = $oSearch;
815         }
816         ksort($aGroupedSearches);
817
818         return $aGroupedSearches;
819     }
820
821     /* Perform the actual query lookup.
822
823         Returns an ordered list of results, each with the following fields:
824             osm_type: type of corresponding OSM object
825                         N - node
826                         W - way
827                         R - relation
828                         P - postcode (internally computed)
829             osm_id: id of corresponding OSM object
830             class: general object class (corresponds to tag key of primary OSM tag)
831             type: subclass of object (corresponds to tag value of primary OSM tag)
832             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
833             rank_search: rank in search hierarchy
834                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
835             rank_address: rank in address hierarchy (determines orer in address)
836             place_id: internal key (may differ between different instances)
837             country_code: ISO country code
838             langaddress: localized full address
839             placename: localized name of object
840             ref: content of ref tag (if available)
841             lon: longitude
842             lat: latitude
843             importance: importance of place based on Wikipedia link count
844             addressimportance: cumulated importance of address elements
845             extra_place: type of place (for admin boundaries, if there is a place tag)
846             aBoundingBox: bounding Box
847             label: short description of the object class/type (English only)
848             name: full name (currently the same as langaddress)
849             foundorder: secondary ordering for places with same importance
850     */
851
852
853     public function lookup()
854     {
855         if (!$this->sQuery && !$this->aStructuredQuery) return array();
856
857         $oCtx = new SearchContext();
858
859         if ($this->aRoutePoints) {
860             $oCtx->setViewboxFromRoute(
861                 $this->oDB,
862                 $this->aRoutePoints,
863                 $this->aRouteWidth,
864                 $this->bBoundedSearch
865             );
866         } elseif ($this->aViewBox) {
867             $oCtx->setViewboxFromBox($this->aViewBox, $this->bBoundedSearch);
868         }
869         if ($this->aExcludePlaceIDs) {
870             $oCtx->setExcludeList($this->aExcludePlaceIDs);
871         }
872         if ($this->aCountryCodes) {
873             $oCtx->setCountryList($this->aCountryCodes);
874         }
875
876         $sNormQuery = $this->normTerm($this->sQuery);
877         $sLanguagePrefArraySQL = getArraySQL(
878             array_map("getDBQuoted", $this->aLangPrefOrder)
879         );
880
881         $sQuery = $this->sQuery;
882         if (!preg_match('//u', $sQuery)) {
883             userError("Query string is not UTF-8 encoded.");
884         }
885
886         // Conflicts between US state abreviations and various words for 'the' in different languages
887         if (isset($this->aLangPrefOrder['name:en'])) {
888             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
889             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
890             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
891         }
892
893         // Do we have anything that looks like a lat/lon pair?
894         $sQuery = $oCtx->setNearPointFromQuery($sQuery);
895
896         $aSearchResults = array();
897         if ($sQuery || $this->aStructuredQuery) {
898             // Start with a single blank search
899             $aSearches = array(new SearchDescription($oCtx));
900
901             if ($sQuery) {
902                 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
903             }
904
905             $sSpecialTerm = '';
906             if ($sQuery) {
907                 preg_match_all(
908                     '/\\[([\\w ]*)\\]/u',
909                     $sQuery,
910                     $aSpecialTermsRaw,
911                     PREG_SET_ORDER
912                 );
913                 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
914                     $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
915                     if (!$sSpecialTerm) {
916                         $sSpecialTerm = $aSpecialTerm[1];
917                     }
918                 }
919             }
920             if (!$sSpecialTerm && $this->aStructuredQuery
921                 && isset($this->aStructuredQuery['amenity'])) {
922                 $sSpecialTerm = $this->aStructuredQuery['amenity'];
923                 unset($this->aStructuredQuery['amenity']);
924             }
925
926             if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
927                 $sSpecialTerm = pg_escape_string($sSpecialTerm);
928                 $sToken = chksql(
929                     $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
930                     "Cannot decode query. Wrong encoding?"
931                 );
932                 $sSQL = 'SELECT class, type FROM word ';
933                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
934                 $sSQL .= '   AND class is not null AND class not in (\'place\')';
935                 if (CONST_Debug) var_Dump($sSQL);
936                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
937                 $aNewSearches = array();
938                 foreach ($aSearches as $oSearch) {
939                     foreach ($aSearchWords as $aSearchTerm) {
940                         $oNewSearch = clone $oSearch;
941                         $oNewSearch->setPoiSearch(
942                             Operator::TYPE,
943                             $aSearchTerm['class'],
944                             $aSearchTerm['type']
945                         );
946                         $aNewSearches[] = $oNewSearch;
947                     }
948                 }
949                 $aSearches = $aNewSearches;
950             }
951
952             // Split query into phrases
953             // Commas are used to reduce the search space by indicating where phrases split
954             if ($this->aStructuredQuery) {
955                 $aInPhrases = $this->aStructuredQuery;
956                 $bStructuredPhrases = true;
957             } else {
958                 $aInPhrases = explode(',', $sQuery);
959                 $bStructuredPhrases = false;
960             }
961
962             // Convert each phrase to standard form
963             // Create a list of standard words
964             // Get all 'sets' of words
965             // Generate a complete list of all
966             $aTokens = array();
967             $aPhrases = array();
968             foreach ($aInPhrases as $iPhrase => $sPhrase) {
969                 $sPhrase = chksql(
970                     $this->oDB->getOne('SELECT make_standard_name('.getDBQuoted($sPhrase).')'),
971                     "Cannot normalize query string (is it a UTF-8 string?)"
972                 );
973                 if (trim($sPhrase)) {
974                     $oPhrase = new Phrase($sPhrase, is_string($iPhrase) ? $iPhrase : '');
975                     $oPhrase->addTokens($aTokens);
976                     $aPhrases[] = $oPhrase;
977                 }
978             }
979
980             if (sizeof($aTokens)) {
981                 // Check which tokens we have, get the ID numbers
982                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
983                 $sSQL .= ' FROM word ';
984                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
985
986                 if (CONST_Debug) var_Dump($sSQL);
987
988                 $aValidTokens = array();
989                 $aDatabaseWords = chksql(
990                     $this->oDB->getAll($sSQL),
991                     "Could not get word tokens."
992                 );
993                 $aPossibleMainWordIDs = array();
994                 $aWordFrequencyScores = array();
995                 foreach ($aDatabaseWords as $aToken) {
996                     // Very special case - require 2 letter country param to match the country code found
997                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
998                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
999                     ) {
1000                         continue;
1001                     }
1002
1003                     if (isset($aValidTokens[$aToken['word_token']])) {
1004                         $aValidTokens[$aToken['word_token']][] = $aToken;
1005                     } else {
1006                         $aValidTokens[$aToken['word_token']] = array($aToken);
1007                     }
1008                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1009                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1010                 }
1011                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1012
1013                 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1014                 foreach ($aTokens as $sToken) {
1015                     if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1016                         if (isset($aValidTokens[$aData[1]])) {
1017                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1018                                 if (!$aToken['class']) {
1019                                     if (isset($aValidTokens[$sToken])) {
1020                                         $aValidTokens[$sToken][] = $aToken;
1021                                     } else {
1022                                         $aValidTokens[$sToken] = array($aToken);
1023                                     }
1024                                 }
1025                             }
1026                         }
1027                     }
1028                 }
1029
1030                 foreach ($aTokens as $sToken) {
1031                     // Unknown single word token with a number - assume it is a house number
1032                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/^[0-9]+$/', $sToken)) {
1033                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house', 'word_token' => ' '.$sToken));
1034                     }
1035                 }
1036
1037                 // Any words that have failed completely?
1038                 // TODO: suggestions
1039
1040                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1041
1042                 if ($this->bReverseInPlan) {
1043                     // Reverse phrase array and also reverse the order of the wordsets in
1044                     // the first and final phrase. Don't bother about phrases in the middle
1045                     // because order in the address doesn't matter.
1046                     $aPhrases = array_reverse($aPhrases);
1047                     $aPhrases[0]->invertWordSets();
1048                     if (sizeof($aPhrases) > 1) {
1049                         $aPhrases[sizeof($aPhrases)-1]->invertWordSets();
1050                     }
1051                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1052
1053                     foreach ($aGroupedSearches as $aSearches) {
1054                         foreach ($aSearches as $aSearch) {
1055                             if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1056                                 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1057                             }
1058                             $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1059                         }
1060                     }
1061
1062                     $aGroupedSearches = $aReverseGroupedSearches;
1063                     ksort($aGroupedSearches);
1064                 }
1065             } else {
1066                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1067                 $aGroupedSearches = array();
1068                 foreach ($aSearches as $aSearch) {
1069                     if ($aSearch->getRank() < $this->iMaxRank) {
1070                         if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1071                         $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1072                     }
1073                 }
1074                 ksort($aGroupedSearches);
1075             }
1076
1077             // Filter out duplicate searches
1078             $aSearchHash = array();
1079             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1080                 foreach ($aSearches as $iSearch => $aSearch) {
1081                     $sHash = serialize($aSearch);
1082                     if (isset($aSearchHash[$sHash])) {
1083                         unset($aGroupedSearches[$iGroup][$iSearch]);
1084                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1085                     } else {
1086                         $aSearchHash[$sHash] = 1;
1087                     }
1088                 }
1089             }
1090
1091             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1092
1093             // Start the search process
1094             // array with: placeid => -1 | tiger-housenumber
1095             $aResultPlaceIDs = array();
1096             $iGroupLoop = 0;
1097             $iQueryLoop = 0;
1098             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1099                 $iGroupLoop++;
1100                 foreach ($aSearches as $oSearch) {
1101                     $iQueryLoop++;
1102
1103                     if (CONST_Debug) {
1104                         echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1105                         _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1106                     }
1107
1108                     $aRes = $oSearch->query(
1109                         $this->oDB,
1110                         $aWordFrequencyScores,
1111                         $this->exactMatchCache,
1112                         $this->iMinAddressRank,
1113                         $this->iMaxAddressRank,
1114                         $this->iLimit
1115                     );
1116
1117                     foreach ($aRes['IDs'] as $iPlaceID) {
1118                         // array for placeID => -1 | Tiger housenumber
1119                         $aResultPlaceIDs[$iPlaceID] = $aRes['houseNumber'];
1120                     }
1121                     if ($iQueryLoop > 20) break;
1122                 }
1123
1124                 if (sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1125                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1126                     // reduces the number of place ids, like a filter
1127                     // rank_address is 30 for interpolated housenumbers
1128                     $sWherePlaceId = 'WHERE place_id in (';
1129                     $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1130
1131                     $sSQL = "SELECT place_id ";
1132                     $sSQL .= "FROM placex ".$sWherePlaceId;
1133                     $sSQL .= "  AND (";
1134                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1135                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1136                         $sSQL .= "     OR (extratags->'place') = 'city'";
1137                     }
1138                     if ($this->aAddressRankList) {
1139                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1140                     }
1141                     $sSQL .= "  ) UNION ";
1142                     $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1143                     $sSQL .= "  AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1144                     if ($this->aAddressRankList) {
1145                         $sSQL .= "     OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1146                     }
1147                     $sSQL .= ") ";
1148                     if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1149                         $sSQL .= "UNION ";
1150                         $sSQL .= "  SELECT place_id ";
1151                         $sSQL .= "  FROM location_property_tiger ".$sWherePlaceId;
1152                     }
1153                     if ($this->iMaxAddressRank == 30) {
1154                         $sSQL .= "UNION ";
1155                         $sSQL .= "  SELECT place_id ";
1156                         $sSQL .= "  FROM location_property_osmline ".$sWherePlaceId;
1157                     }
1158                     if (CONST_Debug) var_dump($sSQL);
1159                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1160                     $tempIDs = array();
1161                     foreach ($aFilteredPlaceIDs as $placeID) {
1162                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1163                     }
1164                     $aResultPlaceIDs = $tempIDs;
1165                 }
1166
1167                 if (sizeof($aResultPlaceIDs)) break;
1168                 if ($iGroupLoop > 4) break;
1169                 if ($iQueryLoop > 30) break;
1170             }
1171
1172             // Did we find anything?
1173             if (sizeof($aResultPlaceIDs)) {
1174                 $aSearchResults = $this->getDetails($aResultPlaceIDs, $oCtx);
1175             }
1176         } else {
1177             // Just interpret as a reverse geocode
1178             $oReverse = new ReverseGeocode($this->oDB);
1179             $oReverse->setZoom(18);
1180
1181             $aLookup = $oReverse->lookupPoint($oCtx->sqlNear, false);
1182
1183             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1184
1185             if ($aLookup['place_id']) {
1186                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1), $oCtx);
1187                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1188             } else {
1189                 $aSearchResults = array();
1190             }
1191         }
1192
1193         // No results? Done
1194         if (!sizeof($aSearchResults)) {
1195             if ($this->bFallback) {
1196                 if ($this->fallbackStructuredQuery()) {
1197                     return $this->lookup();
1198                 }
1199             }
1200
1201             return array();
1202         }
1203
1204         $aClassType = getClassTypesWithImportance();
1205         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1206         foreach ($aRecheckWords as $i => $sWord) {
1207             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1208         }
1209
1210         if (CONST_Debug) {
1211             echo '<i>Recheck words:<\i>';
1212             var_dump($aRecheckWords);
1213         }
1214
1215         $oPlaceLookup = new PlaceLookup($this->oDB);
1216         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1217         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1218         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1219         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1220         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1221         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1222
1223         foreach ($aSearchResults as $iResNum => $aResult) {
1224             // Default
1225             $fDiameter = getResultDiameter($aResult);
1226
1227             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1228             if ($aOutlineResult) {
1229                 $aResult = array_merge($aResult, $aOutlineResult);
1230             }
1231             
1232             if ($aResult['extra_place'] == 'city') {
1233                 $aResult['class'] = 'place';
1234                 $aResult['type'] = 'city';
1235                 $aResult['rank_search'] = 16;
1236             }
1237
1238             // Is there an icon set for this type of result?
1239             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1240                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1241             ) {
1242                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1243             }
1244
1245             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1246                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1247             ) {
1248                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1249             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1250                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1251             ) {
1252                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1253             }
1254             // if tag '&addressdetails=1' is set in query
1255             if ($this->bIncludeAddressDetails) {
1256                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1257                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1258                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1259                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1260                 }
1261             }
1262
1263             if ($this->bIncludeExtraTags) {
1264                 if ($aResult['extra']) {
1265                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1266                 } else {
1267                     $aResult['sExtraTags'] = (object) array();
1268                 }
1269             }
1270
1271             if ($this->bIncludeNameDetails) {
1272                 if ($aResult['names']) {
1273                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1274                 } else {
1275                     $aResult['sNameDetails'] = (object) array();
1276                 }
1277             }
1278
1279             $aResult['name'] = $aResult['langaddress'];
1280
1281             if ($oCtx->hasNearPoint())
1282             {
1283                 $aResult['importance'] = 0.001;
1284                 $aResult['foundorder'] = $aResult['addressimportance'];
1285             } else {
1286                 // Adjust importance for the number of exact string matches in the result
1287                 $aResult['importance'] = max(0.001, $aResult['importance']);
1288                 $iCountWords = 0;
1289                 $sAddress = $aResult['langaddress'];
1290                 foreach ($aRecheckWords as $i => $sWord) {
1291                     if (stripos($sAddress, $sWord)!==false) {
1292                         $iCountWords++;
1293                         if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1294                     }
1295                 }
1296
1297                 $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
1298
1299                 // secondary ordering (for results with same importance (the smaller the better):
1300                 // - approximate importance of address parts
1301                 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1302                 // - number of exact matches from the query
1303                 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1304                     $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1305                 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1306                     $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1307                 }
1308                 // - importance of the class/type
1309                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1310                     && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1311                 ) {
1312                     $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1313                 } else {
1314                     $aResult['foundorder'] += 0.01;
1315                 }
1316             }
1317             if (CONST_Debug) var_dump($aResult);
1318             $aSearchResults[$iResNum] = $aResult;
1319         }
1320         uasort($aSearchResults, 'byImportance');
1321
1322         $aOSMIDDone = array();
1323         $aClassTypeNameDone = array();
1324         $aToFilter = $aSearchResults;
1325         $aSearchResults = array();
1326
1327         $bFirst = true;
1328         foreach ($aToFilter as $iResNum => $aResult) {
1329             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1330             if ($bFirst) {
1331                 $fLat = $aResult['lat'];
1332                 $fLon = $aResult['lon'];
1333                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1334                 $bFirst = false;
1335             }
1336             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1337                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1338             ) {
1339                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1340                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1341                 $aSearchResults[] = $aResult;
1342             }
1343
1344             // Absolute limit on number of results
1345             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1346         }
1347
1348         return $aSearchResults;
1349     } // end lookup()
1350 } // end class