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