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