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