]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
add search for postcode
[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
9 class Geocode
10 {
11     protected $oDB;
12
13     protected $aLangPrefOrder = array();
14
15     protected $bIncludeAddressDetails = false;
16     protected $bIncludeExtraTags = false;
17     protected $bIncludeNameDetails = false;
18
19     protected $bIncludePolygonAsPoints = false;
20     protected $bIncludePolygonAsText = false;
21     protected $bIncludePolygonAsGeoJSON = false;
22     protected $bIncludePolygonAsKML = false;
23     protected $bIncludePolygonAsSVG = false;
24     protected $fPolygonSimplificationThreshold = 0.0;
25
26     protected $aExcludePlaceIDs = array();
27     protected $bDeDupe = true;
28     protected $bReverseInPlan = false;
29
30     protected $iLimit = 20;
31     protected $iFinalLimit = 10;
32     protected $iOffset = 0;
33     protected $bFallback = false;
34
35     protected $aCountryCodes = false;
36
37     protected $bBoundedSearch = false;
38     protected $aViewBox = false;
39     protected $sViewboxCentreSQL = false;
40     protected $sViewboxSmallSQL = false;
41     protected $sViewboxLargeSQL = false;
42
43     protected $iMaxRank = 20;
44     protected $iMinAddressRank = 0;
45     protected $iMaxAddressRank = 30;
46     protected $aAddressRankList = array();
47     protected $exactMatchCache = array();
48
49     protected $sAllowedTypesSQLList = false;
50
51     protected $sQuery = false;
52     protected $aStructuredQuery = false;
53
54
55     public function __construct(&$oDB)
56     {
57         $this->oDB =& $oDB;
58     }
59
60     public function setReverseInPlan($bReverse)
61     {
62         $this->bReverseInPlan = $bReverse;
63     }
64
65     public function setLanguagePreference($aLangPref)
66     {
67         $this->aLangPrefOrder = $aLangPref;
68     }
69
70     public function getMoreUrlParams()
71     {
72         if ($this->aStructuredQuery) {
73             $aParams = $this->aStructuredQuery;
74         } else {
75             $aParams = array('q' => $this->sQuery);
76         }
77
78         if ($this->aExcludePlaceIDs) {
79             $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
80         }
81
82         if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
83         if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
84         if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
85
86         if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
87         if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
88         if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
89         if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
90         if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
91
92         if ($this->fPolygonSimplificationThreshold > 0.0) {
93             $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
94         }
95
96         if ($this->bBoundedSearch) $aParams['bounded'] = '1';
97         if (!$this->bDeDupe) $aParams['dedupe'] = '0';
98
99         if ($this->aCountryCodes) {
100             $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
101         }
102
103         if ($this->aViewBox) {
104             $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
105                                   .','.$this->aViewBox[2].','.$this->aViewBox[1];
106         }
107
108         return $aParams;
109     }
110
111     public function setIncludePolygonAsPoints($b = true)
112     {
113         $this->bIncludePolygonAsPoints = $b;
114     }
115
116     public function setIncludePolygonAsText($b = true)
117     {
118         $this->bIncludePolygonAsText = $b;
119     }
120
121     public function setIncludePolygonAsGeoJSON($b = true)
122     {
123         $this->bIncludePolygonAsGeoJSON = $b;
124     }
125
126     public function setIncludePolygonAsKML($b = true)
127     {
128         $this->bIncludePolygonAsKML = $b;
129     }
130
131     public function setIncludePolygonAsSVG($b = true)
132     {
133         $this->bIncludePolygonAsSVG = $b;
134     }
135
136     public function setPolygonSimplificationThreshold($f)
137     {
138         $this->fPolygonSimplificationThreshold = $f;
139     }
140
141     public function setLimit($iLimit = 10)
142     {
143         if ($iLimit > 50) $iLimit = 50;
144         if ($iLimit < 1) $iLimit = 1;
145
146         $this->iFinalLimit = $iLimit;
147         $this->iLimit = $iLimit + min($iLimit, 10);
148     }
149
150     public function setFeatureType($sFeatureType)
151     {
152         switch ($sFeatureType) {
153             case 'country':
154                 $this->setRankRange(4, 4);
155                 break;
156             case 'state':
157                 $this->setRankRange(8, 8);
158                 break;
159             case 'city':
160                 $this->setRankRange(14, 16);
161                 break;
162             case 'settlement':
163                 $this->setRankRange(8, 20);
164                 break;
165         }
166     }
167
168     public function setRankRange($iMin, $iMax)
169     {
170         $this->iMinAddressRank = $iMin;
171         $this->iMaxAddressRank = $iMax;
172     }
173
174     public function setRoute($aRoutePoints, $fRouteWidth)
175     {
176         $this->aViewBox = false;
177
178         $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
179         $sSep = '';
180         foreach ($aRoutePoints as $aPoint) {
181             $fPoint = (float)$aPoint;
182             $this->sViewboxCentreSQL .= $sSep.$fPoint;
183             $sSep = ($sSep == ' ') ? ',' : ' ';
184         }
185         $this->sViewboxCentreSQL .= ")'::geometry,4326)";
186
187         $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
188         $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
189
190         $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
191         $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
192     }
193
194     public function setViewbox($aViewbox)
195     {
196         $this->aViewBox = array_map('floatval', $aViewbox);
197
198         $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
199         $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
200         $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
201         $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
202
203         if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
204             || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
205         ) {
206             userError("Bad parameter 'viewbox'. Not a box.");
207         }
208
209         $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
210         $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
211         $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
212         $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
213         $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
214         $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
215
216         $this->sViewboxCentreSQL = false;
217         $this->sViewboxSmallSQL = sprintf(
218             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
219             $this->aViewBox[0],
220             $this->aViewBox[1],
221             $this->aViewBox[2],
222             $this->aViewBox[3]
223         );
224         $this->sViewboxLargeSQL = sprintf(
225             'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
226             $aBigViewBox[0],
227             $aBigViewBox[1],
228             $aBigViewBox[2],
229             $aBigViewBox[3]
230         );
231     }
232
233     public function setQuery($sQueryString)
234     {
235         $this->sQuery = $sQueryString;
236         $this->aStructuredQuery = false;
237     }
238
239     public function getQueryString()
240     {
241         return $this->sQuery;
242     }
243
244
245     public function loadParamArray($oParams)
246     {
247         $this->bIncludeAddressDetails
248          = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
249         $this->bIncludeExtraTags
250          = $oParams->getBool('extratags', $this->bIncludeExtraTags);
251         $this->bIncludeNameDetails
252          = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
253
254         $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
255         $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
256
257         $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
258         $this->iOffset = $oParams->getInt('offset', $this->iOffset);
259
260         $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
261
262         // List of excluded Place IDs - used for more acurate pageing
263         $sExcluded = $oParams->getStringList('exclude_place_ids');
264         if ($sExcluded) {
265             foreach ($sExcluded as $iExcludedPlaceID) {
266                 $iExcludedPlaceID = (int)$iExcludedPlaceID;
267                 if ($iExcludedPlaceID)
268                     $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
269             }
270
271             if (isset($aExcludePlaceIDs))
272                 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
273         }
274
275         // Only certain ranks of feature
276         $sFeatureType = $oParams->getString('featureType');
277         if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
278         if ($sFeatureType) $this->setFeatureType($sFeatureType);
279
280         // Country code list
281         $sCountries = $oParams->getStringList('countrycodes');
282         if ($sCountries) {
283             foreach ($sCountries as $sCountryCode) {
284                 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
285                     $aCountries[] = strtolower($sCountryCode);
286                 }
287             }
288             if (isset($aCountries))
289                 $this->aCountryCodes = $aCountries;
290         }
291
292         $aViewbox = $oParams->getStringList('viewboxlbrt');
293         if ($aViewbox) {
294             if (count($aViewbox) != 4) {
295                 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
296             }
297             $this->setViewbox($aViewbox);
298         } else {
299             $aViewbox = $oParams->getStringList('viewbox');
300             if ($aViewbox) {
301                 if (count($aViewbox) != 4) {
302                     userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
303                 }
304                 $this->setViewBox(array(
305                                    $aViewbox[0],
306                                    $aViewbox[3],
307                                    $aViewbox[2],
308                                    $aViewbox[1]
309                                   ));
310             } else {
311                 $aRoute = $oParams->getStringList('route');
312                 $fRouteWidth = $oParams->getFloat('routewidth');
313                 if ($aRoute && $fRouteWidth) {
314                     $this->setRoute($aRoute, $fRouteWidth);
315                 }
316             }
317         }
318     }
319
320     public function setQueryFromParams($oParams)
321     {
322         // Search query
323         $sQuery = $oParams->getString('q');
324         if (!$sQuery) {
325             $this->setStructuredQuery(
326                 $oParams->getString('amenity'),
327                 $oParams->getString('street'),
328                 $oParams->getString('city'),
329                 $oParams->getString('county'),
330                 $oParams->getString('state'),
331                 $oParams->getString('country'),
332                 $oParams->getString('postalcode')
333             );
334             $this->setReverseInPlan(false);
335         } else {
336             $this->setQuery($sQuery);
337         }
338     }
339
340     public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
341     {
342         $sValue = trim($sValue);
343         if (!$sValue) return false;
344         $this->aStructuredQuery[$sKey] = $sValue;
345         if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
346             $this->iMinAddressRank = $iNewMinAddressRank;
347             $this->iMaxAddressRank = $iNewMaxAddressRank;
348         }
349         if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
350         return true;
351     }
352
353     public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
354     {
355         $this->sQuery = false;
356
357         // Reset
358         $this->iMinAddressRank = 0;
359         $this->iMaxAddressRank = 30;
360         $this->aAddressRankList = array();
361
362         $this->aStructuredQuery = array();
363         $this->sAllowedTypesSQLList = '';
364
365         $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
366         $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
367         $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
368         $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
369         $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
370         $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
371         $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
372
373         if (sizeof($this->aStructuredQuery) > 0) {
374             $this->sQuery = join(', ', $this->aStructuredQuery);
375             if ($this->iMaxAddressRank < 30) {
376                 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
377             }
378         }
379     }
380
381     public function fallbackStructuredQuery()
382     {
383         if (!$this->aStructuredQuery) return false;
384
385         $aParams = $this->aStructuredQuery;
386
387         if (sizeof($aParams) == 1) return false;
388
389         $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
390
391         foreach ($aOrderToFallback as $sType) {
392             if (isset($aParams[$sType])) {
393                 unset($aParams[$sType]);
394                 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
395                 return true;
396             }
397         }
398
399         return false;
400     }
401
402     public function getDetails($aPlaceIDs)
403     {
404         //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
405         if (sizeof($aPlaceIDs) == 0) return array();
406
407         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
408
409         // Get the details for display (is this a redundant extra step?)
410         $sPlaceIDs = join(',', array_keys($aPlaceIDs));
411
412         $sImportanceSQL = '';
413         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
414         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
415
416         $sSQL  = "SELECT ";
417         $sSQL .= "    osm_type,";
418         $sSQL .= "    osm_id,";
419         $sSQL .= "    class,";
420         $sSQL .= "    type,";
421         $sSQL .= "    admin_level,";
422         $sSQL .= "    rank_search,";
423         $sSQL .= "    rank_address,";
424         $sSQL .= "    min(place_id) AS place_id, ";
425         $sSQL .= "    min(parent_place_id) AS parent_place_id, ";
426         $sSQL .= "    country_code, ";
427         $sSQL .= "    get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
428         $sSQL .= "    get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
429         $sSQL .= "    get_name_by_language(name, ARRAY['ref']) AS ref,";
430         if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
431         if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
432         $sSQL .= "    avg(ST_X(centroid)) AS lon, ";
433         $sSQL .= "    avg(ST_Y(centroid)) AS lat, ";
434         $sSQL .= "    ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
435         $sSQL .= "    ( ";
436         $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
437         $sSQL .= "       FROM ";
438         $sSQL .= "         place_addressline s, ";
439         $sSQL .= "         placex p";
440         $sSQL .= "       WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
441         $sSQL .= "         AND p.place_id = s.address_place_id ";
442         $sSQL .= "         AND s.isaddress ";
443         $sSQL .= "         AND p.importance is not null ";
444         $sSQL .= "    ) AS addressimportance, ";
445         $sSQL .= "    (extratags->'place') AS extra_place ";
446         $sSQL .= " FROM placex";
447         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
448         $sSQL .= "   AND (";
449         $sSQL .= "            placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
450         if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
451             $sSQL .= "        OR (extratags->'place') = 'city'";
452         }
453         if ($this->aAddressRankList) {
454             $sSQL .= "        OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
455         }
456         $sSQL .= "       ) ";
457         if ($this->sAllowedTypesSQLList) {
458             $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
459         }
460         $sSQL .= "    AND linked_place_id is null ";
461         $sSQL .= " GROUP BY ";
462         $sSQL .= "     osm_type, ";
463         $sSQL .= "     osm_id, ";
464         $sSQL .= "     class, ";
465         $sSQL .= "     type, ";
466         $sSQL .= "     admin_level, ";
467         $sSQL .= "     rank_search, ";
468         $sSQL .= "     rank_address, ";
469         $sSQL .= "     country_code, ";
470         $sSQL .= "     importance, ";
471         if (!$this->bDeDupe) $sSQL .= "place_id,";
472         $sSQL .= "     langaddress, ";
473         $sSQL .= "     placename, ";
474         $sSQL .= "     ref, ";
475         if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
476         if ($this->bIncludeNameDetails) $sSQL .= "name, ";
477         $sSQL .= "     extratags->'place' ";
478
479         // postcode table
480         $sSQL .= "UNION ";
481         $sSQL .= "SELECT";
482         $sSQL .= "  'P' as osm_type,";
483         $sSQL .= "  (SELECT osm_id from placex p WHERE p.place_id = parent_place_id) as osm_id,";
484         $sSQL .= "  'place' as class, 'postcode' as type,";
485         $sSQL .= "  null as admin_level, rank_search, rank_address,";
486         $sSQL .= "  place_id, parent_place_id, country_code,";
487         $sSQL .= "  get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
488         $sSQL .= "  postcode as placename,";
489         $sSQL .= "  postcode as ref,";
490         if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
491         if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
492         $sSQL .= "  ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
493         $sSQL .=    $sImportanceSQL."(0.75-(rank_search::float/40)) AS importance, ";
494         $sSQL .= "  (";
495         $sSQL .= "     SELECT max(p.importance*(p.rank_address+2))";
496         $sSQL .= "     FROM ";
497         $sSQL .= "       place_addressline s, ";
498         $sSQL .= "       placex p";
499         $sSQL .= "     WHERE s.place_id = parent_place_id";
500         $sSQL .= "       AND p.place_id = s.address_place_id ";
501         $sSQL .= "       AND s.isaddress";
502         $sSQL .= "       AND p.importance is not null";
503         $sSQL .= "  ) AS addressimportance, ";
504         $sSQL .= "  null AS extra_place ";
505         $sSQL .= "FROM location_postcode";
506         $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
507
508         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
509             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
510             // with start- and endnumber, the common osm housenumbers are usually saved as points
511             $sHousenumbers = "";
512             $i = 0;
513             $length = count($aPlaceIDs);
514             foreach ($aPlaceIDs as $placeID => $housenumber) {
515                 $i++;
516                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
517                 if ($i<$length) $sHousenumbers .= ", ";
518             }
519
520             if (CONST_Use_US_Tiger_Data) {
521                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
522                 $sSQL .= " union";
523                 $sSQL .= " SELECT ";
524                 $sSQL .= "     'T' AS osm_type, ";
525                 $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
526                 $sSQL .= "     'place' AS class, ";
527                 $sSQL .= "     'house' AS type, ";
528                 $sSQL .= "     null AS admin_level, ";
529                 $sSQL .= "     30 AS rank_search, ";
530                 $sSQL .= "     30 AS rank_address, ";
531                 $sSQL .= "     min(place_id) AS place_id, ";
532                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
533                 $sSQL .= "     'us' AS country_code, ";
534                 $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
535                 $sSQL .= "     null AS placename, ";
536                 $sSQL .= "     null AS ref, ";
537                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
538                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
539                 $sSQL .= "     avg(st_x(centroid)) AS lon, ";
540                 $sSQL .= "     avg(st_y(centroid)) AS lat,";
541                 $sSQL .= "     ".$sImportanceSQL."-1.15 AS importance, ";
542                 $sSQL .= "     (";
543                 $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
544                 $sSQL .= "        FROM ";
545                 $sSQL .= "          place_addressline s, ";
546                 $sSQL .= "          placex p";
547                 $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
548                 $sSQL .= "          AND p.place_id = s.address_place_id ";
549                 $sSQL .= "          AND s.isaddress";
550                 $sSQL .= "          AND p.importance is not null";
551                 $sSQL .= "     ) AS addressimportance, ";
552                 $sSQL .= "     null AS extra_place ";
553                 $sSQL .= " FROM (";
554                 $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
555                 $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
556                 $sSQL .= "         parent_place_id, ";
557                 $sSQL .= "         housenumber_for_place";
558                 $sSQL .= "     FROM (";
559                 $sSQL .= "            location_property_tiger ";
560                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
561                 $sSQL .= "     WHERE ";
562                 $sSQL .= "         housenumber_for_place>=0";
563                 $sSQL .= "         AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
564                 $sSQL .= " ) AS blub"; //postgres wants an alias here
565                 $sSQL .= " GROUP BY";
566                 $sSQL .= "      place_id, ";
567                 $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
568                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
569             }
570             // osmline
571             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
572             $sSQL .= " UNION ";
573             $sSQL .= "SELECT ";
574             $sSQL .= "  'W' AS osm_type, ";
575             $sSQL .= "  osm_id, ";
576             $sSQL .= "  'place' AS class, ";
577             $sSQL .= "  'house' AS type, ";
578             $sSQL .= "  null AS admin_level, ";
579             $sSQL .= "  30 AS rank_search, ";
580             $sSQL .= "  30 AS rank_address, ";
581             $sSQL .= "  min(place_id) as place_id, ";
582             $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
583             $sSQL .= "  country_code, ";
584             $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
585             $sSQL .= "  null AS placename, ";
586             $sSQL .= "  null AS ref, ";
587             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
588             if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
589             $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
590             $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
591             $sSQL .= "  ".$sImportanceSQL."-0.1 AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
592             $sSQL .= "  (";
593             $sSQL .= "     SELECT ";
594             $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
595             $sSQL .= "     FROM";
596             $sSQL .= "       place_addressline s, ";
597             $sSQL .= "       placex p";
598             $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
599             $sSQL .= "       AND p.place_id = s.address_place_id ";
600             $sSQL .= "       AND s.isaddress ";
601             $sSQL .= "       AND p.importance is not null";
602             $sSQL .= "  ) AS addressimportance,";
603             $sSQL .= "  null AS extra_place ";
604             $sSQL .= "  FROM (";
605             $sSQL .= "     SELECT ";
606             $sSQL .= "         osm_id, ";
607             $sSQL .= "         place_id, ";
608             $sSQL .= "         country_code, ";
609             $sSQL .= "         CASE ";             // interpolate the housenumbers here
610             $sSQL .= "           WHEN startnumber != endnumber ";
611             $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
612             $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
613             $sSQL .= "         END as centroid, ";
614             $sSQL .= "         parent_place_id, ";
615             $sSQL .= "         housenumber_for_place ";
616             $sSQL .= "     FROM (";
617             $sSQL .= "            location_property_osmline ";
618             $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
619             $sSQL .= "          ) ";
620             $sSQL .= "     WHERE housenumber_for_place>=0 ";
621             $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
622             $sSQL .= "  ) as blub"; //postgres wants an alias here
623             $sSQL .= "  GROUP BY ";
624             $sSQL .= "    osm_id, ";
625             $sSQL .= "    place_id, ";
626             $sSQL .= "    housenumber_for_place, ";
627             $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
628             if (!$this->bDeDupe) $sSQL .= ", place_id ";
629
630             if (CONST_Use_Aux_Location_data) {
631                 $sSQL .= " UNION ";
632                 $sSQL .= "  SELECT ";
633                 $sSQL .= "     'L' AS osm_type, ";
634                 $sSQL .= "     place_id AS osm_id, ";
635                 $sSQL .= "     'place' AS class,";
636                 $sSQL .= "     'house' AS type, ";
637                 $sSQL .= "     null AS admin_level, ";
638                 $sSQL .= "     0 AS rank_search,";
639                 $sSQL .= "     0 AS rank_address, ";
640                 $sSQL .= "     min(place_id) AS place_id,";
641                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
642                 $sSQL .= "     'us' AS country_code, ";
643                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
644                 $sSQL .= "     null AS placename, ";
645                 $sSQL .= "     null AS ref, ";
646                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
647                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
648                 $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
649                 $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
650                 $sSQL .= "     ".$sImportanceSQL."-1.10 AS importance, ";
651                 $sSQL .= "     ( ";
652                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
653                 $sSQL .= "       FROM ";
654                 $sSQL .= "          place_addressline s, ";
655                 $sSQL .= "          placex p";
656                 $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
657                 $sSQL .= "         AND p.place_id = s.address_place_id ";
658                 $sSQL .= "         AND s.isaddress";
659                 $sSQL .= "         AND p.importance is not null";
660                 $sSQL .= "     ) AS addressimportance, ";
661                 $sSQL .= "     null AS extra_place ";
662                 $sSQL .= "  FROM location_property_aux ";
663                 $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
664                 $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
665                 $sSQL .= "  GROUP BY ";
666                 $sSQL .= "     place_id, ";
667                 if (!$this->bDeDupe) $sSQL .= "place_id, ";
668                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
669             }
670         }
671
672         $sSQL .= " order by importance desc";
673         if (CONST_Debug) {
674             echo "<hr>";
675             var_dump($sSQL);
676         }
677         $aSearchResults = chksql(
678             $this->oDB->getAll($sSQL),
679             "Could not get details for place."
680         );
681
682         return $aSearchResults;
683     }
684
685     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
686     {
687         /*
688              Calculate all searches using aValidTokens i.e.
689              'Wodsworth Road, Sheffield' =>
690
691              Phrase Wordset
692              0      0       (wodsworth road)
693              0      1       (wodsworth)(road)
694              1      0       (sheffield)
695
696              Score how good the search is so they can be ordered
697          */
698         foreach ($aPhrases as $iPhrase => $aPhrase) {
699             $aNewPhraseSearches = array();
700             if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
701             else $sPhraseType = '';
702
703             foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
704                 // Too many permutations - too expensive
705                 if ($iWordSet > 120) break;
706
707                 $aWordsetSearches = $aSearches;
708
709                 // Add all words from this wordset
710                 foreach ($aWordset as $iToken => $sToken) {
711                     //echo "<br><b>$sToken</b>";
712                     $aNewWordsetSearches = array();
713
714                     foreach ($aWordsetSearches as $aCurrentSearch) {
715                         //echo "<i>";
716                         //var_dump($aCurrentSearch);
717                         //echo "</i>";
718
719                         // If the token is valid
720                         if (isset($aValidTokens[' '.$sToken])) {
721                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
722                                 $aSearch = $aCurrentSearch;
723                                 $aSearch['iSearchRank']++;
724                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
725                                     if ($aSearch['sCountryCode'] === false) {
726                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
727                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
728                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
729                                             $aSearch['iSearchRank'] += 5;
730                                         }
731                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
732                                     }
733                                 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
734                                     if ($aSearch['oNear'] === false) {
735                                         $aSearch['oNear'] = new NearPoint(
736                                             $aSearchTerm['lat'],
737                                             $aSearchTerm['lon'],
738                                             $aSearchTerm['radius']
739                                         );
740                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
741                                     }
742                                 } elseif ($sPhraseType == 'postalcode' || ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode')) {
743                                     // We need to try the case where the postal code is the primary element (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode) so try both
744                                     if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
745                                         // If we have structured search or this is the first term,
746                                         // make the postcode the primary search element.
747                                         if ($sPhraseType == 'postalcode' || sizeof($aSearch['aName']) == 0) {
748                                             $aNewSearch = $aSearch;
749                                             $aNewSearch['sOperator'] = 'postcode';
750                                             $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
751                                             $aNewSearch['aName'][$aSearchTerm['word_id']] = substr($aSearchTerm['word_token'], 1);
752                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
753                                         }
754
755                                         // If we have a structured search or this is not the first term,
756                                         // add the postcode as an addendum.
757                                         if ($sPhraseType == 'postalcode' || sizeof($aSearch['aName'])) {
758                                             $aSearch['sPostcode'] = $aSearchTerm['word_token'];
759                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
760                                         }
761                                     }
762                                 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
763                                     if ($aSearch['sHouseNumber'] === '') {
764                                         $aSearch['sHouseNumber'] = $sToken;
765                                         // sanity check: if the housenumber is not mainly made
766                                         // up of numbers, add a penalty
767                                         if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
768                                         // also housenumbers should appear in the first or second phrase
769                                         if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
770                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
771                                         /*
772                                         // Fall back to not searching for this item (better than nothing)
773                                         $aSearch = $aCurrentSearch;
774                                         $aSearch['iSearchRank'] += 1;
775                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
776                                          */
777                                     }
778                                 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
779                                     // require a normalized exact match of the term
780                                     // if we have the normalizer version of the query
781                                     // available
782                                     if ($aSearch['sClass'] === ''
783                                         && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
784                                         $aSearch['sClass'] = $aSearchTerm['class'];
785                                         $aSearch['sType'] = $aSearchTerm['type'];
786                                         if ($aSearchTerm['operator'] == '') {
787                                             $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' :  'near';
788                                             $aSearch['iSearchRank'] += 2;
789                                         } else {
790                                             $aSearch['sOperator'] = 'near'; // near = in for the moment
791                                         }
792
793                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
794                                     }
795                                 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
796                                     if (sizeof($aSearch['aName'])) {
797                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
798                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
799                                         } else {
800                                             $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
801                                             $aSearch['iSearchRank'] += 1000; // skip;
802                                         }
803                                     } else {
804                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
805                                         //$aSearch['iNamePhrase'] = $iPhrase;
806                                     }
807                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
808                                 }
809                             }
810                         }
811                         // Look for partial matches.
812                         // Note that there is no point in adding country terms here
813                         // because country are omitted in the address.
814                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
815                             // Allow searching for a word - but at extra cost
816                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
817                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
818                                     if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
819                                         $aSearch = $aCurrentSearch;
820                                         $aSearch['iSearchRank'] += 1;
821                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
822                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
823                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
824                                         } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
825                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
826                                             $aSearch['iSearchRank'] += 1;
827                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
828                                             foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
829                                                 if (empty($aSearchTermToken['country_code'])
830                                                     && empty($aSearchTermToken['lat'])
831                                                     && empty($aSearchTermToken['class'])
832                                                 ) {
833                                                     $aSearch = $aCurrentSearch;
834                                                     $aSearch['iSearchRank'] += 1;
835                                                     $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
836                                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
837                                                 }
838                                             }
839                                         } else {
840                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
841                                             if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
842                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
843                                         }
844                                     }
845
846                                     if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
847                                         $aSearch = $aCurrentSearch;
848                                         $aSearch['iSearchRank'] += 1;
849                                         if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
850                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
851                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
852                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
853                                         } else {
854                                             $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
855                                         }
856                                         $aSearch['iNamePhrase'] = $iPhrase;
857                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
858                                     }
859                                 }
860                             }
861                         } else {
862                             // Allow skipping a word - but at EXTREAM cost
863                             //$aSearch = $aCurrentSearch;
864                             //$aSearch['iSearchRank']+=100;
865                             //$aNewWordsetSearches[] = $aSearch;
866                         }
867                     }
868                     // Sort and cut
869                     usort($aNewWordsetSearches, 'bySearchRank');
870                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
871                 }
872                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
873
874                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
875                 usort($aNewPhraseSearches, 'bySearchRank');
876
877                 $aSearchHash = array();
878                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
879                     $sHash = serialize($aSearch);
880                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
881                     else $aSearchHash[$sHash] = 1;
882                 }
883
884                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
885             }
886
887             // Re-group the searches by their score, junk anything over 20 as just not worth trying
888             $aGroupedSearches = array();
889             foreach ($aNewPhraseSearches as $aSearch) {
890                 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
891                     if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
892                     $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
893                 }
894             }
895             ksort($aGroupedSearches);
896
897             $iSearchCount = 0;
898             $aSearches = array();
899             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
900                 $iSearchCount += sizeof($aNewSearches);
901                 $aSearches = array_merge($aSearches, $aNewSearches);
902                 if ($iSearchCount > 50) break;
903             }
904
905             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
906         }
907         return $aGroupedSearches;
908     }
909
910     /* Perform the actual query lookup.
911
912         Returns an ordered list of results, each with the following fields:
913             osm_type: type of corresponding OSM object
914                         N - node
915                         W - way
916                         R - relation
917                         P - postcode (internally computed)
918             osm_id: id of corresponding OSM object
919             class: general object class (corresponds to tag key of primary OSM tag)
920             type: subclass of object (corresponds to tag value of primary OSM tag)
921             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
922             rank_search: rank in search hierarchy
923                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
924             rank_address: rank in address hierarchy (determines orer in address)
925             place_id: internal key (may differ between different instances)
926             country_code: ISO country code
927             langaddress: localized full address
928             placename: localized name of object
929             ref: content of ref tag (if available)
930             lon: longitude
931             lat: latitude
932             importance: importance of place based on Wikipedia link count
933             addressimportance: cumulated importance of address elements
934             extra_place: type of place (for admin boundaries, if there is a place tag)
935             aBoundingBox: bounding Box
936             label: short description of the object class/type (English only)
937             name: full name (currently the same as langaddress)
938             foundorder: secondary ordering for places with same importance
939     */
940
941
942     public function lookup()
943     {
944         if (!$this->sQuery && !$this->aStructuredQuery) return array();
945
946         $oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
947         if ($oNormalizer !== null) {
948             $sNormQuery = $oNormalizer->transliterate($this->sQuery);
949         } else {
950             $sNormQuery = null;
951         }
952
953         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
954         $sCountryCodesSQL = false;
955         if ($this->aCountryCodes) {
956             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
957         }
958
959         $sQuery = $this->sQuery;
960         if (!preg_match('//u', $sQuery)) {
961             userError("Query string is not UTF-8 encoded.");
962         }
963
964         // Conflicts between US state abreviations and various words for 'the' in different languages
965         if (isset($this->aLangPrefOrder['name:en'])) {
966             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
967             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
968             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
969         }
970
971         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
972         if ($this->sViewboxCentreSQL) {
973             // For complex viewboxes (routes) precompute the bounding geometry
974             $sGeom = chksql(
975                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
976                 "Could not get small viewbox"
977             );
978             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
979
980             $sGeom = chksql(
981                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
982                 "Could not get large viewbox"
983             );
984             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
985         }
986
987         // Do we have anything that looks like a lat/lon pair?
988         $oNearPoint = false;
989         if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
990             $oNearPoint = $aLooksLike['pt'];
991             $sQuery = $aLooksLike['query'];
992         }
993
994         $aSearchResults = array();
995         if ($sQuery || $this->aStructuredQuery) {
996             // Start with a blank search
997             $aSearches = array(
998                           array(
999                            'iSearchRank' => 0,
1000                            'iNamePhrase' => -1,
1001                            'sCountryCode' => false,
1002                            'aName' => array(),
1003                            'aAddress' => array(),
1004                            'aFullNameAddress' => array(),
1005                            'aNameNonSearch' => array(),
1006                            'aAddressNonSearch' => array(),
1007                            'sOperator' => '',
1008                            'aFeatureName' => array(),
1009                            'sClass' => '',
1010                            'sType' => '',
1011                            'sHouseNumber' => '',
1012                            'sPostcode' => '',
1013                            'oNear' => $oNearPoint
1014                           )
1015                          );
1016
1017             // Any 'special' terms in the search?
1018             $bSpecialTerms = false;
1019             preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1020             $aSpecialTerms = array();
1021             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1022                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1023                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
1024             }
1025
1026             preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1027             $aSpecialTerms = array();
1028             if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
1029                 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
1030                 unset($this->aStructuredQuery['amenity']);
1031             }
1032
1033             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1034                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1035                 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
1036                 $sSQL = 'SELECT * ';
1037                 $sSQL .= 'FROM ( ';
1038                 $sSQL .= '   SELECT word_id, word_token, word, class, type, country_code, operator';
1039                 $sSQL .= '   FROM word ';
1040                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
1041                 $sSQL .= ') AS x ';
1042                 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1043                 $sSQL .= ' OR country_code is not null';
1044                 if (CONST_Debug) var_Dump($sSQL);
1045                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1046                 $aNewSearches = array();
1047                 foreach ($aSearches as $aSearch) {
1048                     foreach ($aSearchWords as $aSearchTerm) {
1049                         $aNewSearch = $aSearch;
1050                         if ($aSearchTerm['country_code']) {
1051                             $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1052                             $aNewSearches[] = $aNewSearch;
1053                             $bSpecialTerms = true;
1054                         }
1055                         if ($aSearchTerm['class']) {
1056                             $aNewSearch['sClass'] = $aSearchTerm['class'];
1057                             $aNewSearch['sType'] = $aSearchTerm['type'];
1058                             $aNewSearches[] = $aNewSearch;
1059                             $bSpecialTerms = true;
1060                         }
1061                     }
1062                 }
1063                 $aSearches = $aNewSearches;
1064             }
1065
1066             // Split query into phrases
1067             // Commas are used to reduce the search space by indicating where phrases split
1068             if ($this->aStructuredQuery) {
1069                 $aPhrases = $this->aStructuredQuery;
1070                 $bStructuredPhrases = true;
1071             } else {
1072                 $aPhrases = explode(',', $sQuery);
1073                 $bStructuredPhrases = false;
1074             }
1075
1076             // Convert each phrase to standard form
1077             // Create a list of standard words
1078             // Get all 'sets' of words
1079             // Generate a complete list of all
1080             $aTokens = array();
1081             foreach ($aPhrases as $iPhrase => $sPhrase) {
1082                 $aPhrase = chksql(
1083                     $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1084                     "Cannot normalize query string (is it a UTF-8 string?)"
1085                 );
1086                 if (trim($aPhrase['string'])) {
1087                     $aPhrases[$iPhrase] = $aPhrase;
1088                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1089                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1090                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1091                 } else {
1092                     unset($aPhrases[$iPhrase]);
1093                 }
1094             }
1095
1096             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1097             $aPhraseTypes = array_keys($aPhrases);
1098             $aPhrases = array_values($aPhrases);
1099
1100             if (sizeof($aTokens)) {
1101                 // Check which tokens we have, get the ID numbers
1102                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1103                 $sSQL .= ' FROM word ';
1104                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1105
1106                 if (CONST_Debug) var_Dump($sSQL);
1107
1108                 $aValidTokens = array();
1109                 if (sizeof($aTokens)) {
1110                     $aDatabaseWords = chksql(
1111                         $this->oDB->getAll($sSQL),
1112                         "Could not get word tokens."
1113                     );
1114                 } else {
1115                     $aDatabaseWords = array();
1116                 }
1117                 $aPossibleMainWordIDs = array();
1118                 $aWordFrequencyScores = array();
1119                 foreach ($aDatabaseWords as $aToken) {
1120                     // Very special case - require 2 letter country param to match the country code found
1121                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1122                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1123                     ) {
1124                         continue;
1125                     }
1126
1127                     if (isset($aValidTokens[$aToken['word_token']])) {
1128                         $aValidTokens[$aToken['word_token']][] = $aToken;
1129                     } else {
1130                         $aValidTokens[$aToken['word_token']] = array($aToken);
1131                     }
1132                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1133                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1134                 }
1135                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1136
1137                 // Try and calculate GB postcodes we might be missing
1138                 foreach ($aTokens as $sToken) {
1139                     // Source of gb postcodes is now definitive - always use
1140                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1141                         if (substr($aData[1], -2, 1) != ' ') {
1142                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1143                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1144                         }
1145                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1146                         if ($aGBPostcodeLocation) {
1147                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
1148                         }
1149                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1150                         // US ZIP+4 codes - if there is no token,
1151                         // merge in the 5-digit ZIP code
1152                         if (isset($aValidTokens[$aData[1]])) {
1153                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1154                                 if (!$aToken['class']) {
1155                                     if (isset($aValidTokens[$sToken])) {
1156                                         $aValidTokens[$sToken][] = $aToken;
1157                                     } else {
1158                                         $aValidTokens[$sToken] = array($aToken);
1159                                     }
1160                                 }
1161                             }
1162                         }
1163                     }
1164                 }
1165
1166                 foreach ($aTokens as $sToken) {
1167                     // Unknown single word token with a number - assume it is a house number
1168                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1169                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1170                     }
1171                 }
1172
1173                 // Any words that have failed completely?
1174                 // TODO: suggestions
1175
1176                 // Start the search process
1177                 // array with: placeid => -1 | tiger-housenumber
1178                 $aResultPlaceIDs = array();
1179
1180                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1181
1182                 if ($this->bReverseInPlan) {
1183                     // Reverse phrase array and also reverse the order of the wordsets in
1184                     // the first and final phrase. Don't bother about phrases in the middle
1185                     // because order in the address doesn't matter.
1186                     $aPhrases = array_reverse($aPhrases);
1187                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1188                     if (sizeof($aPhrases) > 1) {
1189                         $aFinalPhrase = end($aPhrases);
1190                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1191                     }
1192                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1193
1194                     foreach ($aGroupedSearches as $aSearches) {
1195                         foreach ($aSearches as $aSearch) {
1196                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1197                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1198                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1199                             }
1200                         }
1201                     }
1202
1203                     $aGroupedSearches = $aReverseGroupedSearches;
1204                     ksort($aGroupedSearches);
1205                 }
1206             } else {
1207                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1208                 $aGroupedSearches = array();
1209                 foreach ($aSearches as $aSearch) {
1210                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1211                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1212                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1213                     }
1214                 }
1215                 ksort($aGroupedSearches);
1216             }
1217
1218             if (CONST_Debug) var_Dump($aGroupedSearches);
1219             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1220                 $aCopyGroupedSearches = $aGroupedSearches;
1221                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1222                     foreach ($aSearches as $iSearch => $aSearch) {
1223                         $aReductionsList = array($aSearch['aAddress']);
1224                         $iSearchRank = $aSearch['iSearchRank'];
1225                         while (sizeof($aReductionsList) > 0) {
1226                             $iSearchRank += 5;
1227                             if ($iSearchRank > iMaxRank) break 3;
1228                             $aNewReductionsList = array();
1229                             foreach ($aReductionsList as $aReductionsWordList) {
1230                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1231                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1232                                     $aReverseSearch = $aSearch;
1233                                     $aSearch['aAddress'] = $aReductionsWordListResult;
1234                                     $aSearch['iSearchRank'] = $iSearchRank;
1235                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1236                                     if (sizeof($aReductionsWordListResult) > 0) {
1237                                         $aNewReductionsList[] = $aReductionsWordListResult;
1238                                     }
1239                                 }
1240                             }
1241                             $aReductionsList = $aNewReductionsList;
1242                         }
1243                     }
1244                 }
1245                 ksort($aGroupedSearches);
1246             }
1247
1248             // Filter out duplicate searches
1249             $aSearchHash = array();
1250             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1251                 foreach ($aSearches as $iSearch => $aSearch) {
1252                     $sHash = serialize($aSearch);
1253                     if (isset($aSearchHash[$sHash])) {
1254                         unset($aGroupedSearches[$iGroup][$iSearch]);
1255                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1256                     } else {
1257                         $aSearchHash[$sHash] = 1;
1258                     }
1259                 }
1260             }
1261
1262             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1263
1264             $iGroupLoop = 0;
1265             $iQueryLoop = 0;
1266             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1267                 $iGroupLoop++;
1268                 foreach ($aSearches as $aSearch) {
1269                     $iQueryLoop++;
1270                     $searchedHousenumber = -1;
1271
1272                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1273                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1274
1275                     // No location term?
1276                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1277                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1278                             // Just looking for a country by code - look it up
1279                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1280                                 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1281                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1282                                 if ($bBoundingBoxSearch)
1283                                     $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1284                                 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1285                                 if (CONST_Debug) var_dump($sSQL);
1286                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1287                             } else {
1288                                 $aPlaceIDs = array();
1289                             }
1290                         } else {
1291                             if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1292                             if (!$aSearch['sClass']) continue;
1293
1294                             $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1295                             if (chksql($this->oDB->getOne($sSQL))) {
1296                                 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1297                                 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1298                                 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1299                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1300                                 if (sizeof($this->aExcludePlaceIDs)) {
1301                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1302                                 }
1303                                 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1304                                 $sSQL .= " limit $this->iLimit";
1305                                 if (CONST_Debug) var_dump($sSQL);
1306                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1307
1308                                 // If excluded place IDs are given, it is fair to assume that
1309                                 // there have been results in the small box, so no further
1310                                 // expansion in that case.
1311                                 // Also don't expand if bounded results were requested.
1312                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1313                                     $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1314                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1315                                     $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1316                                     if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1317                                     if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1318                                     $sSQL .= " LIMIT $this->iLimit";
1319                                     if (CONST_Debug) var_dump($sSQL);
1320                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1321                                 }
1322                             } else {
1323                                 $sSQL = "SELECT place_id ";
1324                                 $sSQL .= "FROM placex ";
1325                                 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1326                                 $sSQL .= "  AND type='".$aSearch['sType']."'";
1327                                 $sSQL .= "  AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1328                                 $sSQL .= "  AND linked_place_id is null";
1329                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1330                                 if ($this->sViewboxCentreSQL)   $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1331                                 $sSQL .= " LIMIT $this->iLimit";
1332                                 if (CONST_Debug) var_dump($sSQL);
1333                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1334                             }
1335                         }
1336                     } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1337                         // If a coordinate is given, the search must either
1338                         // be for a name or a special search. Ignore everythin else.
1339                         $aPlaceIDs = array();
1340                     } elseif ($aSearch['sOperator'] == 'postcode') {
1341                         $sSQL  = "SELECT place_id FROM location_postcode ";
1342                         $sSQL .= "WHERE postcode = '".pg_escape_string(reset($aSearch['aName']))."'";
1343                         if ($aSearch['sCountryCode']) {
1344                             $sSQL .= " AND country_code = '".$aSearch['sCountryCode']."'";
1345                         }
1346                         if ($sCountryCodesSQL) {
1347                             $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1348                         }
1349                         $sSQL .= " LIMIT $this->iLimit";
1350                         if (CONST_Debug) var_dump($sSQL);
1351                         $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1352                     } else {
1353                         $aPlaceIDs = array();
1354
1355                         // First we need a position, either aName or fLat or both
1356                         $aTerms = array();
1357                         $aOrder = array();
1358
1359                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1360                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1361                             $aOrder[] = "";
1362                             $aOrder[0] = "  (";
1363                             $aOrder[0] .= "   EXISTS(";
1364                             $aOrder[0] .= "     SELECT place_id ";
1365                             $aOrder[0] .= "     FROM placex ";
1366                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1367                             $aOrder[0] .= "       AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1368                             $aOrder[0] .= "     LIMIT 1";
1369                             $aOrder[0] .= "   ) ";
1370                             // also housenumbers from interpolation lines table are needed
1371                             $aOrder[0] .= "   OR EXISTS(";
1372                             $aOrder[0] .= "     SELECT place_id ";
1373                             $aOrder[0] .= "     FROM location_property_osmline ";
1374                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1375                             $aOrder[0] .= "       AND startnumber is not NULL";
1376                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1377                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1378                             $aOrder[0] .= "     LIMIT 1";
1379                             $aOrder[0] .= "   )";
1380                             $aOrder[0] .= " )";
1381                             $aOrder[0] .= " DESC";
1382                         }
1383
1384                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1385                         // they might be right - but they are just too darned expensive to run
1386                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1387                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1388                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1389                             // For infrequent name terms disable index usage for address
1390                             if (CONST_Search_NameOnlySearchFrequencyThreshold
1391                                 && sizeof($aSearch['aName']) == 1
1392                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1393                             ) {
1394                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1395                             } else {
1396                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1397                                 if (sizeof($aSearch['aAddressNonSearch'])) {
1398                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1399                                 }
1400                             }
1401                         }
1402                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1403                         if ($aSearch['sHouseNumber']) {
1404                             $aTerms[] = "address_rank between 16 and 27";
1405                         } else {
1406                             if ($this->iMinAddressRank > 0) {
1407                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1408                             }
1409                             if ($this->iMaxAddressRank < 30) {
1410                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1411                             }
1412                         }
1413                         if ($aSearch['oNear']) {
1414                             $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1415
1416                             $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1417                         }
1418                         if (sizeof($this->aExcludePlaceIDs)) {
1419                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1420                         }
1421                         if ($sCountryCodesSQL) {
1422                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
1423                         }
1424
1425                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1426                         if ($oNearPoint) {
1427                             $aOrder[] = $oNearPoint->distanceSQL('centroid');
1428                         }
1429
1430                         if ($aSearch['sHouseNumber']) {
1431                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
1432                         } else {
1433                             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1434                         }
1435                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1436                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1437
1438                         $aOrder[] = "$sImportanceSQL DESC";
1439                         if (sizeof($aSearch['aFullNameAddress'])) {
1440                             $sExactMatchSQL = ' ( ';
1441                             $sExactMatchSQL .= '   SELECT count(*) FROM ( ';
1442                             $sExactMatchSQL .= '      SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1443                             $sExactMatchSQL .= '      INTERSECT ';
1444                             $sExactMatchSQL .= '      SELECT unnest(nameaddress_vector)';
1445                             $sExactMatchSQL .= '   ) s';
1446                             $sExactMatchSQL .= ') as exactmatch';
1447                             $aOrder[] = 'exactmatch DESC';
1448                         } else {
1449                             $sExactMatchSQL = '0::int as exactmatch';
1450                         }
1451
1452                         if (sizeof($aTerms)) {
1453                             $sSQL = "SELECT place_id, ";
1454                             $sSQL .= $sExactMatchSQL;
1455                             $sSQL .= " FROM search_name";
1456                             $sSQL .= " WHERE ".join(' and ', $aTerms);
1457                             $sSQL .= " ORDER BY ".join(', ', $aOrder);
1458                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1459                                 $sSQL .= " LIMIT 20";
1460                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1461                                 $sSQL .= " LIMIT 1";
1462                             } else {
1463                                 $sSQL .= " LIMIT ".$this->iLimit;
1464                             }
1465
1466                             if (CONST_Debug) var_dump($sSQL);
1467                             $aViewBoxPlaceIDs = chksql(
1468                                 $this->oDB->getAll($sSQL),
1469                                 "Could not get places for search terms."
1470                             );
1471                             //var_dump($aViewBoxPlaceIDs);
1472                             // Did we have an viewbox matches?
1473                             $aPlaceIDs = array();
1474                             $bViewBoxMatch = false;
1475                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1476                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1477                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1478                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1479                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1480                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1481                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1482                             }
1483                         }
1484                         //var_Dump($aPlaceIDs);
1485                         //exit;
1486
1487                         //now search for housenumber, if housenumber provided
1488                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1489                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
1490                             $aRoadPlaceIDs = $aPlaceIDs;
1491                             $sPlaceIDs = join(',', $aPlaceIDs);
1492
1493                             // Now they are indexed, look for a house attached to a street we found
1494                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1495                             $sSQL = "SELECT place_id FROM placex ";
1496                             $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1497                             if (sizeof($this->aExcludePlaceIDs)) {
1498                                 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1499                             }
1500                             $sSQL .= " LIMIT $this->iLimit";
1501                             if (CONST_Debug) var_dump($sSQL);
1502                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1503
1504                             // if nothing found, search in the interpolation line table
1505                             if (!sizeof($aPlaceIDs)) {
1506                                 // do we need to use transliteration and the regex for housenumbers???
1507                                 //new query for lines, not housenumbers anymore
1508                                 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1509                                 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1510                                 if ($searchedHousenumber%2 == 0) {
1511                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1512                                     $sSQL .= "interpolationtype='even'";
1513                                 } else {
1514                                     //look for housenumber in streets with interpolationtype odd or all
1515                                     $sSQL .= "interpolationtype='odd'";
1516                                 }
1517                                 $sSQL .= " or interpolationtype='all') and ";
1518                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1519                                 $sSQL .= $searchedHousenumber."<=endnumber";
1520
1521                                 if (sizeof($this->aExcludePlaceIDs)) {
1522                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1523                                 }
1524                                 //$sSQL .= " limit $this->iLimit";
1525                                 if (CONST_Debug) var_dump($sSQL);
1526                                 //get place IDs
1527                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1528                             }
1529
1530                             // If nothing found try the aux fallback table
1531                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1532                                 $sSQL = "SELECT place_id FROM location_property_aux ";
1533                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1534                                 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1535                                 if (sizeof($this->aExcludePlaceIDs)) {
1536                                     $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1537                                 }
1538                                 //$sSQL .= " limit $this->iLimit";
1539                                 if (CONST_Debug) var_dump($sSQL);
1540                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1541                             }
1542
1543                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1544                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1545                                 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1546                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1547                                 if ($searchedHousenumber%2 == 0) {
1548                                     $sSQL .= "interpolationtype='even'";
1549                                 } else {
1550                                     $sSQL .= "interpolationtype='odd'";
1551                                 }
1552                                 $sSQL .= " or interpolationtype='all') and ";
1553                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1554                                 $sSQL .= $searchedHousenumber."<=endnumber";
1555
1556                                 if (sizeof($this->aExcludePlaceIDs)) {
1557                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1558                                 }
1559                                 //$sSQL .= " limit $this->iLimit";
1560                                 if (CONST_Debug) var_dump($sSQL);
1561                                 //get place IDs
1562                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1563                             }
1564
1565                             // Fallback to the road (if no housenumber was found)
1566                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1567                                 $aPlaceIDs = $aRoadPlaceIDs;
1568                                 //set to -1, if no housenumbers were found
1569                                 $searchedHousenumber = -1;
1570                             }
1571                             //else: housenumber was found, remains saved in searchedHousenumber
1572                         }
1573
1574
1575                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1576                             $sPlaceIDs = join(',', $aPlaceIDs);
1577                             $aClassPlaceIDs = array();
1578
1579                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1580                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1581                                 $sSQL = "SELECT place_id ";
1582                                 $sSQL .= " FROM placex ";
1583                                 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1584                                 $sSQL .= "   AND class='".$aSearch['sClass']."' ";
1585                                 $sSQL .= "   AND type='".$aSearch['sType']."'";
1586                                 $sSQL .= "   AND linked_place_id is null";
1587                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1588                                 $sSQL .= " ORDER BY rank_search ASC ";
1589                                 $sSQL .= " LIMIT $this->iLimit";
1590                                 if (CONST_Debug) var_dump($sSQL);
1591                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1592                             }
1593
1594                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1595                                 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
1596                                 $sSQL = "SELECT count(*) FROM pg_tables ";
1597                                 $sSQL .= "WHERE tablename = '$sClassTable'";
1598                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1599
1600                                 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1601
1602                                 if (CONST_Debug) var_dump($sSQL);
1603                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1604
1605                                 // For state / country level searches the normal radius search doesn't work very well
1606                                 $sPlaceGeom = false;
1607                                 if ($this->iMaxRank < 9 && $bCacheTable) {
1608                                     // Try and get a polygon to search in instead
1609                                     $sSQL = "SELECT geometry ";
1610                                     $sSQL .= " FROM placex";
1611                                     $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1612                                     $sSQL .= "   AND rank_search < $this->iMaxRank + 5";
1613                                     $sSQL .= "   AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1614                                     $sSQL .= " ORDER BY rank_search ASC ";
1615                                     $sSQL .= " LIMIT 1";
1616                                     if (CONST_Debug) var_dump($sSQL);
1617                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1618                                 }
1619
1620                                 if ($sPlaceGeom) {
1621                                     $sPlaceIDs = false;
1622                                 } else {
1623                                     $this->iMaxRank += 5;
1624                                     $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1625                                     if (CONST_Debug) var_dump($sSQL);
1626                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1627                                     $sPlaceIDs = join(',', $aPlaceIDs);
1628                                 }
1629
1630                                 if ($sPlaceIDs || $sPlaceGeom) {
1631                                     $fRange = 0.01;
1632                                     if ($bCacheTable) {
1633                                         // More efficient - can make the range bigger
1634                                         $fRange = 0.05;
1635
1636                                         $sOrderBySQL = '';
1637                                         if ($oNearPoint) {
1638                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1639                                         } elseif ($sPlaceIDs) {
1640                                             $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1641                                         } elseif ($sPlaceGeom) {
1642                                             $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1643                                         }
1644
1645                                         $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
1646                                         $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
1647                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1648                                         if ($sPlaceIDs) {
1649                                             $sSQL .= ",placex as f where ";
1650                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1651                                         }
1652                                         if ($sPlaceGeom) {
1653                                             $sSQL .= " where ";
1654                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1655                                         }
1656                                         if (sizeof($this->aExcludePlaceIDs)) {
1657                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1658                                         }
1659                                         if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1660                                         $sSQL .= 'limit 300) i ';
1661                                         if ($sOrderBySQL) $sSQL .= "order by order_term asc";
1662                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1663                                         $sSQL .= " limit $this->iLimit";
1664                                         if (CONST_Debug) var_dump($sSQL);
1665                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1666                                     } else {
1667                                         if ($aSearch['oNear']) {
1668                                             $fRange = $aSearch['oNear']->radius();
1669                                         }
1670
1671                                         $sOrderBySQL = '';
1672                                         if ($oNearPoint) {
1673                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1674                                         } else {
1675                                             $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1676                                         }
1677
1678                                         $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1679                                         $sSQL .= " FROM placex as l, placex as f ";
1680                                         $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1681                                         $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1682                                         $sSQL .= "  AND l.class='".$aSearch['sClass']."' ";
1683                                         $sSQL .= "  AND l.type='".$aSearch['sType']."' ";
1684                                         if (sizeof($this->aExcludePlaceIDs)) {
1685                                             $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1686                                         }
1687                                         if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1688                                         if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1689                                         if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1690                                         $sSQL .= " limit $this->iLimit";
1691                                         if (CONST_Debug) var_dump($sSQL);
1692                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1693                                     }
1694                                 }
1695                             }
1696                             $aPlaceIDs = $aClassPlaceIDs;
1697                         }
1698                     }
1699
1700                     if (CONST_Debug) {
1701                         echo "<br><b>Place IDs:</b> ";
1702                         var_Dump($aPlaceIDs);
1703                     }
1704
1705                     foreach ($aPlaceIDs as $iPlaceID) {
1706                         // array for placeID => -1 | Tiger housenumber
1707                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1708                     }
1709                     if ($iQueryLoop > 20) break;
1710                 }
1711
1712                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1713                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1714                     // reduces the number of place ids, like a filter
1715                     // rank_address is 30 for interpolated housenumbers
1716                     $sSQL = "SELECT place_id ";
1717                     $sSQL .= "FROM placex ";
1718                     $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1719                     $sSQL .= "  AND (";
1720                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1721                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1722                         $sSQL .= "     OR (extratags->'place') = 'city'";
1723                     }
1724                     if ($this->aAddressRankList) {
1725                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1726                     }
1727                     if (CONST_Use_US_Tiger_Data) {
1728                         $sSQL .= "  ) ";
1729                         $sSQL .= "UNION ";
1730                         $sSQL .= "  SELECT place_id ";
1731                         $sSQL .= "  FROM location_property_tiger ";
1732                         $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1733                         $sSQL .= "    AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1734                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1735                     }
1736                     $sSQL .= ") UNION ";
1737                     $sSQL .= "  SELECT place_id ";
1738                     $sSQL .= "  FROM location_property_osmline ";
1739                     $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1740                     $sSQL .= "    AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1741                     if (CONST_Debug) var_dump($sSQL);
1742                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1743                     $tempIDs = array();
1744                     foreach ($aFilteredPlaceIDs as $placeID) {
1745                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1746                     }
1747                     $aResultPlaceIDs = $tempIDs;
1748                 }
1749
1750                 //exit;
1751                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1752                 if ($iGroupLoop > 4) break;
1753                 if ($iQueryLoop > 30) break;
1754             }
1755
1756             // Did we find anything?
1757             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1758                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1759             }
1760         } else {
1761             // Just interpret as a reverse geocode
1762             $oReverse = new ReverseGeocode($this->oDB);
1763             $oReverse->setZoom(18);
1764
1765             $aLookup = $oReverse->lookup(
1766                 $oNearPoint->lat(),
1767                 $oNearPoint->lon(),
1768                 false
1769             );
1770
1771             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1772
1773             if ($aLookup['place_id']) {
1774                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1775                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1776             } else {
1777                 $aSearchResults = array();
1778             }
1779         }
1780
1781         // No results? Done
1782         if (!sizeof($aSearchResults)) {
1783             if ($this->bFallback) {
1784                 if ($this->fallbackStructuredQuery()) {
1785                     return $this->lookup();
1786                 }
1787             }
1788
1789             return array();
1790         }
1791
1792         $aClassType = getClassTypesWithImportance();
1793         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1794         foreach ($aRecheckWords as $i => $sWord) {
1795             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1796         }
1797
1798         if (CONST_Debug) {
1799             echo '<i>Recheck words:<\i>';
1800             var_dump($aRecheckWords);
1801         }
1802
1803         $oPlaceLookup = new PlaceLookup($this->oDB);
1804         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1805         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1806         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1807         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1808         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1809         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1810
1811         foreach ($aSearchResults as $iResNum => $aResult) {
1812             // Default
1813             $fDiameter = getResultDiameter($aResult);
1814
1815             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1816             if ($aOutlineResult) {
1817                 $aResult = array_merge($aResult, $aOutlineResult);
1818             }
1819             
1820             if ($aResult['extra_place'] == 'city') {
1821                 $aResult['class'] = 'place';
1822                 $aResult['type'] = 'city';
1823                 $aResult['rank_search'] = 16;
1824             }
1825
1826             // Is there an icon set for this type of result?
1827             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1828                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1829             ) {
1830                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1831             }
1832
1833             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1834                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1835             ) {
1836                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1837             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1838                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1839             ) {
1840                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1841             }
1842             // if tag '&addressdetails=1' is set in query
1843             if ($this->bIncludeAddressDetails) {
1844                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1845                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1846                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1847                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1848                 }
1849             }
1850
1851             if ($this->bIncludeExtraTags) {
1852                 if ($aResult['extra']) {
1853                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1854                 } else {
1855                     $aResult['sExtraTags'] = (object) array();
1856                 }
1857             }
1858
1859             if ($this->bIncludeNameDetails) {
1860                 if ($aResult['names']) {
1861                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1862                 } else {
1863                     $aResult['sNameDetails'] = (object) array();
1864                 }
1865             }
1866
1867             // Adjust importance for the number of exact string matches in the result
1868             $aResult['importance'] = max(0.001, $aResult['importance']);
1869             $iCountWords = 0;
1870             $sAddress = $aResult['langaddress'];
1871             foreach ($aRecheckWords as $i => $sWord) {
1872                 if (stripos($sAddress, $sWord)!==false) {
1873                     $iCountWords++;
1874                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1875                 }
1876             }
1877
1878             $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
1879
1880             $aResult['name'] = $aResult['langaddress'];
1881             // secondary ordering (for results with same importance (the smaller the better):
1882             // - approximate importance of address parts
1883             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1884             // - number of exact matches from the query
1885             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1886                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1887             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1888                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1889             }
1890             // - importance of the class/type
1891             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1892                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1893             ) {
1894                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1895             } else {
1896                 $aResult['foundorder'] += 0.01;
1897             }
1898             if (CONST_Debug) var_dump($aResult);
1899             $aSearchResults[$iResNum] = $aResult;
1900         }
1901         uasort($aSearchResults, 'byImportance');
1902
1903         $aOSMIDDone = array();
1904         $aClassTypeNameDone = array();
1905         $aToFilter = $aSearchResults;
1906         $aSearchResults = array();
1907
1908         $bFirst = true;
1909         foreach ($aToFilter as $iResNum => $aResult) {
1910             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1911             if ($bFirst) {
1912                 $fLat = $aResult['lat'];
1913                 $fLon = $aResult['lon'];
1914                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1915                 $bFirst = false;
1916             }
1917             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1918                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1919             ) {
1920                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1921                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1922                 $aSearchResults[] = $aResult;
1923             }
1924
1925             // Absolute limit on number of results
1926             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1927         }
1928
1929         return $aSearchResults;
1930     } // end lookup()
1931 } // end class