]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
Merge pull request #700 from lonvia/structured-address-info
[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         if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
480             // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
481             // with start- and endnumber, the common osm housenumbers are usually saved as points
482             $sHousenumbers = "";
483             $i = 0;
484             $length = count($aPlaceIDs);
485             foreach ($aPlaceIDs as $placeID => $housenumber) {
486                 $i++;
487                 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
488                 if ($i<$length) $sHousenumbers .= ", ";
489             }
490
491             if (CONST_Use_US_Tiger_Data) {
492                 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
493                 $sSQL .= " union";
494                 $sSQL .= " SELECT ";
495                 $sSQL .= "     'T' AS osm_type, ";
496                 $sSQL .= "     (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
497                 $sSQL .= "     'place' AS class, ";
498                 $sSQL .= "     'house' AS type, ";
499                 $sSQL .= "     null AS admin_level, ";
500                 $sSQL .= "     30 AS rank_search, ";
501                 $sSQL .= "     30 AS rank_address, ";
502                 $sSQL .= "     min(place_id) AS place_id, ";
503                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
504                 $sSQL .= "     'us' AS country_code, ";
505                 $sSQL .= "     get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
506                 $sSQL .= "     null AS placename, ";
507                 $sSQL .= "     null AS ref, ";
508                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
509                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
510                 $sSQL .= "     avg(st_x(centroid)) AS lon, ";
511                 $sSQL .= "     avg(st_y(centroid)) AS lat,";
512                 $sSQL .= "     ".$sImportanceSQL."-1.15 AS importance, ";
513                 $sSQL .= "     (";
514                 $sSQL .= "        SELECT max(p.importance*(p.rank_address+2))";
515                 $sSQL .= "        FROM ";
516                 $sSQL .= "          place_addressline s, ";
517                 $sSQL .= "          placex p";
518                 $sSQL .= "        WHERE s.place_id = min(blub.parent_place_id)";
519                 $sSQL .= "          AND p.place_id = s.address_place_id ";
520                 $sSQL .= "          AND s.isaddress";
521                 $sSQL .= "          AND p.importance is not null";
522                 $sSQL .= "     ) AS addressimportance, ";
523                 $sSQL .= "     null AS extra_place ";
524                 $sSQL .= " FROM (";
525                 $sSQL .= "     SELECT place_id, ";    // interpolate the Tiger housenumbers here
526                 $sSQL .= "         ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
527                 $sSQL .= "         parent_place_id, ";
528                 $sSQL .= "         housenumber_for_place";
529                 $sSQL .= "     FROM (";
530                 $sSQL .= "            location_property_tiger ";
531                 $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
532                 $sSQL .= "     WHERE ";
533                 $sSQL .= "         housenumber_for_place>=0";
534                 $sSQL .= "         AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
535                 $sSQL .= " ) AS blub"; //postgres wants an alias here
536                 $sSQL .= " GROUP BY";
537                 $sSQL .= "      place_id, ";
538                 $sSQL .= "      housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
539                 if (!$this->bDeDupe) $sSQL .= ", place_id ";
540             }
541             // osmline
542             // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
543             $sSQL .= " UNION ";
544             $sSQL .= "SELECT ";
545             $sSQL .= "  'W' AS osm_type, ";
546             $sSQL .= "  osm_id, ";
547             $sSQL .= "  'place' AS class, ";
548             $sSQL .= "  'house' AS type, ";
549             $sSQL .= "  null AS admin_level, ";
550             $sSQL .= "  30 AS rank_search, ";
551             $sSQL .= "  30 AS rank_address, ";
552             $sSQL .= "  min(place_id) as place_id, ";
553             $sSQL .= "  min(parent_place_id) AS parent_place_id, ";
554             $sSQL .= "  country_code, ";
555             $sSQL .= "  get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
556             $sSQL .= "  null AS placename, ";
557             $sSQL .= "  null AS ref, ";
558             if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
559             if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
560             $sSQL .= "  AVG(st_x(centroid)) AS lon, ";
561             $sSQL .= "  AVG(st_y(centroid)) AS lat, ";
562             $sSQL .= "  ".$sImportanceSQL."-0.1 AS importance, ";  // slightly smaller than the importance for normal houses with rank 30, which is 0
563             $sSQL .= "  (";
564             $sSQL .= "     SELECT ";
565             $sSQL .= "       MAX(p.importance*(p.rank_address+2)) ";
566             $sSQL .= "     FROM";
567             $sSQL .= "       place_addressline s, ";
568             $sSQL .= "       placex p";
569             $sSQL .= "     WHERE s.place_id = min(blub.parent_place_id) ";
570             $sSQL .= "       AND p.place_id = s.address_place_id ";
571             $sSQL .= "       AND s.isaddress ";
572             $sSQL .= "       AND p.importance is not null";
573             $sSQL .= "  ) AS addressimportance,";
574             $sSQL .= "  null AS extra_place ";
575             $sSQL .= "  FROM (";
576             $sSQL .= "     SELECT ";
577             $sSQL .= "         osm_id, ";
578             $sSQL .= "         place_id, ";
579             $sSQL .= "         country_code, ";
580             $sSQL .= "         CASE ";             // interpolate the housenumbers here
581             $sSQL .= "           WHEN startnumber != endnumber ";
582             $sSQL .= "           THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
583             $sSQL .= "           ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
584             $sSQL .= "         END as centroid, ";
585             $sSQL .= "         parent_place_id, ";
586             $sSQL .= "         housenumber_for_place ";
587             $sSQL .= "     FROM (";
588             $sSQL .= "            location_property_osmline ";
589             $sSQL .= "            JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
590             $sSQL .= "          ) ";
591             $sSQL .= "     WHERE housenumber_for_place>=0 ";
592             $sSQL .= "       AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
593             $sSQL .= "  ) as blub"; //postgres wants an alias here
594             $sSQL .= "  GROUP BY ";
595             $sSQL .= "    osm_id, ";
596             $sSQL .= "    place_id, ";
597             $sSQL .= "    housenumber_for_place, ";
598             $sSQL .= "    country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
599             if (!$this->bDeDupe) $sSQL .= ", place_id ";
600
601             if (CONST_Use_Aux_Location_data) {
602                 $sSQL .= " UNION ";
603                 $sSQL .= "  SELECT ";
604                 $sSQL .= "     'L' AS osm_type, ";
605                 $sSQL .= "     place_id AS osm_id, ";
606                 $sSQL .= "     'place' AS class,";
607                 $sSQL .= "     'house' AS type, ";
608                 $sSQL .= "     null AS admin_level, ";
609                 $sSQL .= "     0 AS rank_search,";
610                 $sSQL .= "     0 AS rank_address, ";
611                 $sSQL .= "     min(place_id) AS place_id,";
612                 $sSQL .= "     min(parent_place_id) AS parent_place_id, ";
613                 $sSQL .= "     'us' AS country_code, ";
614                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
615                 $sSQL .= "     null AS placename, ";
616                 $sSQL .= "     null AS ref, ";
617                 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
618                 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
619                 $sSQL .= "     avg(ST_X(centroid)) AS lon, ";
620                 $sSQL .= "     avg(ST_Y(centroid)) AS lat, ";
621                 $sSQL .= "     ".$sImportanceSQL."-1.10 AS importance, ";
622                 $sSQL .= "     ( ";
623                 $sSQL .= "       SELECT max(p.importance*(p.rank_address+2))";
624                 $sSQL .= "       FROM ";
625                 $sSQL .= "          place_addressline s, ";
626                 $sSQL .= "          placex p";
627                 $sSQL .= "       WHERE s.place_id = min(location_property_aux.parent_place_id)";
628                 $sSQL .= "         AND p.place_id = s.address_place_id ";
629                 $sSQL .= "         AND s.isaddress";
630                 $sSQL .= "         AND p.importance is not null";
631                 $sSQL .= "     ) AS addressimportance, ";
632                 $sSQL .= "     null AS extra_place ";
633                 $sSQL .= "  FROM location_property_aux ";
634                 $sSQL .= "  WHERE place_id in ($sPlaceIDs) ";
635                 $sSQL .= "    AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
636                 $sSQL .= "  GROUP BY ";
637                 $sSQL .= "     place_id, ";
638                 if (!$this->bDeDupe) $sSQL .= "place_id, ";
639                 $sSQL .= "     get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
640             }
641         }
642
643         $sSQL .= " order by importance desc";
644         if (CONST_Debug) {
645             echo "<hr>";
646             var_dump($sSQL);
647         }
648         $aSearchResults = chksql(
649             $this->oDB->getAll($sSQL),
650             "Could not get details for place."
651         );
652
653         return $aSearchResults;
654     }
655
656     public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
657     {
658         /*
659              Calculate all searches using aValidTokens i.e.
660              'Wodsworth Road, Sheffield' =>
661
662              Phrase Wordset
663              0      0       (wodsworth road)
664              0      1       (wodsworth)(road)
665              1      0       (sheffield)
666
667              Score how good the search is so they can be ordered
668          */
669         foreach ($aPhrases as $iPhrase => $sPhrase) {
670             $aNewPhraseSearches = array();
671             if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
672             else $sPhraseType = '';
673
674             foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
675                 // Too many permutations - too expensive
676                 if ($iWordSet > 120) break;
677
678                 $aWordsetSearches = $aSearches;
679
680                 // Add all words from this wordset
681                 foreach ($aWordset as $iToken => $sToken) {
682                     //echo "<br><b>$sToken</b>";
683                     $aNewWordsetSearches = array();
684
685                     foreach ($aWordsetSearches as $aCurrentSearch) {
686                         //echo "<i>";
687                         //var_dump($aCurrentSearch);
688                         //echo "</i>";
689
690                         // If the token is valid
691                         if (isset($aValidTokens[' '.$sToken])) {
692                             foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
693                                 $aSearch = $aCurrentSearch;
694                                 $aSearch['iSearchRank']++;
695                                 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
696                                     if ($aSearch['sCountryCode'] === false) {
697                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
698                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
699                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
700                                             $aSearch['iSearchRank'] += 5;
701                                         }
702                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
703                                     }
704                                 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
705                                     if ($aSearch['oNear'] === false) {
706                                         $aSearch['oNear'] = new NearPoint(
707                                             $aSearchTerm['lat'],
708                                             $aSearchTerm['lon'],
709                                             $aSearchTerm['radius']
710                                         );
711                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
712                                     }
713                                 } elseif ($sPhraseType == 'postalcode') {
714                                     // 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
715                                     if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
716                                         // If we already have a name try putting the postcode first
717                                         if (sizeof($aSearch['aName'])) {
718                                             $aNewSearch = $aSearch;
719                                             $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
720                                             $aNewSearch['aName'] = array();
721                                             $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
722                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
723                                         }
724
725                                         if (sizeof($aSearch['aName'])) {
726                                             if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
727                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
728                                             } else {
729                                                 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
730                                                 $aSearch['iSearchRank'] += 1000; // skip;
731                                             }
732                                         } else {
733                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
734                                             //$aSearch['iNamePhrase'] = $iPhrase;
735                                         }
736                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
737                                     }
738                                 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
739                                     if ($aSearch['sHouseNumber'] === '') {
740                                         $aSearch['sHouseNumber'] = $sToken;
741                                         // sanity check: if the housenumber is not mainly made
742                                         // up of numbers, add a penalty
743                                         if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
744                                         // also housenumbers should appear in the first or second phrase
745                                         if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
746                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
747                                         /*
748                                         // Fall back to not searching for this item (better than nothing)
749                                         $aSearch = $aCurrentSearch;
750                                         $aSearch['iSearchRank'] += 1;
751                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
752                                          */
753                                     }
754                                 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
755                                     if ($aSearch['sClass'] === '') {
756                                         $aSearch['sOperator'] = $aSearchTerm['operator'];
757                                         $aSearch['sClass'] = $aSearchTerm['class'];
758                                         $aSearch['sType'] = $aSearchTerm['type'];
759                                         if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
760                                         else $aSearch['sOperator'] = 'near'; // near = in for the moment
761                                         if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
762
763                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
764                                     }
765                                 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
766                                     if (sizeof($aSearch['aName'])) {
767                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
768                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
769                                         } else {
770                                             $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
771                                             $aSearch['iSearchRank'] += 1000; // skip;
772                                         }
773                                     } else {
774                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
775                                         //$aSearch['iNamePhrase'] = $iPhrase;
776                                     }
777                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
778                                 }
779                             }
780                         }
781                         // Look for partial matches.
782                         // Note that there is no point in adding country terms here
783                         // because country are omitted in the address.
784                         if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
785                             // Allow searching for a word - but at extra cost
786                             foreach ($aValidTokens[$sToken] as $aSearchTerm) {
787                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
788                                     if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
789                                         $aSearch = $aCurrentSearch;
790                                         $aSearch['iSearchRank'] += 1;
791                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
792                                             $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
793                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
794                                         } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
795                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
796                                             $aSearch['iSearchRank'] += 1;
797                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
798                                             foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
799                                                 if (empty($aSearchTermToken['country_code'])
800                                                     && empty($aSearchTermToken['lat'])
801                                                     && empty($aSearchTermToken['class'])
802                                                 ) {
803                                                     $aSearch = $aCurrentSearch;
804                                                     $aSearch['iSearchRank'] += 1;
805                                                     $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
806                                                     if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
807                                                 }
808                                             }
809                                         } else {
810                                             $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
811                                             if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
812                                             if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
813                                         }
814                                     }
815
816                                     if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
817                                         $aSearch = $aCurrentSearch;
818                                         $aSearch['iSearchRank'] += 1;
819                                         if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
820                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
821                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
822                                             $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
823                                         } else {
824                                             $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
825                                         }
826                                         $aSearch['iNamePhrase'] = $iPhrase;
827                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
828                                     }
829                                 }
830                             }
831                         } else {
832                             // Allow skipping a word - but at EXTREAM cost
833                             //$aSearch = $aCurrentSearch;
834                             //$aSearch['iSearchRank']+=100;
835                             //$aNewWordsetSearches[] = $aSearch;
836                         }
837                     }
838                     // Sort and cut
839                     usort($aNewWordsetSearches, 'bySearchRank');
840                     $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
841                 }
842                 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
843
844                 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
845                 usort($aNewPhraseSearches, 'bySearchRank');
846
847                 $aSearchHash = array();
848                 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
849                     $sHash = serialize($aSearch);
850                     if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
851                     else $aSearchHash[$sHash] = 1;
852                 }
853
854                 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
855             }
856
857             // Re-group the searches by their score, junk anything over 20 as just not worth trying
858             $aGroupedSearches = array();
859             foreach ($aNewPhraseSearches as $aSearch) {
860                 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
861                     if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
862                     $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
863                 }
864             }
865             ksort($aGroupedSearches);
866
867             $iSearchCount = 0;
868             $aSearches = array();
869             foreach ($aGroupedSearches as $iScore => $aNewSearches) {
870                 $iSearchCount += sizeof($aNewSearches);
871                 $aSearches = array_merge($aSearches, $aNewSearches);
872                 if ($iSearchCount > 50) break;
873             }
874
875             //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
876         }
877         return $aGroupedSearches;
878     }
879
880     /* Perform the actual query lookup.
881
882         Returns an ordered list of results, each with the following fields:
883             osm_type: type of corresponding OSM object
884                         N - node
885                         W - way
886                         R - relation
887                         P - postcode (internally computed)
888             osm_id: id of corresponding OSM object
889             class: general object class (corresponds to tag key of primary OSM tag)
890             type: subclass of object (corresponds to tag value of primary OSM tag)
891             admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
892             rank_search: rank in search hierarchy
893                         (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
894             rank_address: rank in address hierarchy (determines orer in address)
895             place_id: internal key (may differ between different instances)
896             country_code: ISO country code
897             langaddress: localized full address
898             placename: localized name of object
899             ref: content of ref tag (if available)
900             lon: longitude
901             lat: latitude
902             importance: importance of place based on Wikipedia link count
903             addressimportance: cumulated importance of address elements
904             extra_place: type of place (for admin boundaries, if there is a place tag)
905             aBoundingBox: bounding Box
906             label: short description of the object class/type (English only)
907             name: full name (currently the same as langaddress)
908             foundorder: secondary ordering for places with same importance
909     */
910
911
912     public function lookup()
913     {
914         if (!$this->sQuery && !$this->aStructuredQuery) return array();
915
916         $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
917         $sCountryCodesSQL = false;
918         if ($this->aCountryCodes) {
919             $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
920         }
921
922         $sQuery = $this->sQuery;
923         if (!preg_match('//u', $sQuery)) {
924             userError("Query string is not UTF-8 encoded.");
925         }
926
927         // Conflicts between US state abreviations and various words for 'the' in different languages
928         if (isset($this->aLangPrefOrder['name:en'])) {
929             $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
930             $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
931             $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
932         }
933
934         $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
935         if ($this->sViewboxCentreSQL) {
936             // For complex viewboxes (routes) precompute the bounding geometry
937             $sGeom = chksql(
938                 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
939                 "Could not get small viewbox"
940             );
941             $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
942
943             $sGeom = chksql(
944                 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
945                 "Could not get large viewbox"
946             );
947             $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
948         }
949
950         // Do we have anything that looks like a lat/lon pair?
951         $oNearPoint = false;
952         if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
953             $oNearPoint = $aLooksLike['pt'];
954             $sQuery = $aLooksLike['query'];
955         }
956
957         $aSearchResults = array();
958         if ($sQuery || $this->aStructuredQuery) {
959             // Start with a blank search
960             $aSearches = array(
961                           array(
962                            'iSearchRank' => 0,
963                            'iNamePhrase' => -1,
964                            'sCountryCode' => false,
965                            'aName' => array(),
966                            'aAddress' => array(),
967                            'aFullNameAddress' => array(),
968                            'aNameNonSearch' => array(),
969                            'aAddressNonSearch' => array(),
970                            'sOperator' => '',
971                            'aFeatureName' => array(),
972                            'sClass' => '',
973                            'sType' => '',
974                            'sHouseNumber' => '',
975                            'oNear' => $oNearPoint
976                           )
977                          );
978
979             // Any 'special' terms in the search?
980             $bSpecialTerms = false;
981             preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
982             $aSpecialTerms = array();
983             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
984                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
985                 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
986             }
987
988             preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
989             $aSpecialTerms = array();
990             if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
991                 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
992                 unset($this->aStructuredQuery['amenity']);
993             }
994
995             foreach ($aSpecialTermsRaw as $aSpecialTerm) {
996                 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
997                 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
998                 $sSQL = 'SELECT * ';
999                 $sSQL .= 'FROM ( ';
1000                 $sSQL .= '   SELECT word_id, word_token, word, class, type, country_code, operator';
1001                 $sSQL .= '   FROM word ';
1002                 $sSQL .= '   WHERE word_token in (\' '.$sToken.'\')';
1003                 $sSQL .= ') AS x ';
1004                 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1005                 $sSQL .= ' OR country_code is not null';
1006                 if (CONST_Debug) var_Dump($sSQL);
1007                 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1008                 $aNewSearches = array();
1009                 foreach ($aSearches as $aSearch) {
1010                     foreach ($aSearchWords as $aSearchTerm) {
1011                         $aNewSearch = $aSearch;
1012                         if ($aSearchTerm['country_code']) {
1013                             $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1014                             $aNewSearches[] = $aNewSearch;
1015                             $bSpecialTerms = true;
1016                         }
1017                         if ($aSearchTerm['class']) {
1018                             $aNewSearch['sClass'] = $aSearchTerm['class'];
1019                             $aNewSearch['sType'] = $aSearchTerm['type'];
1020                             $aNewSearches[] = $aNewSearch;
1021                             $bSpecialTerms = true;
1022                         }
1023                     }
1024                 }
1025                 $aSearches = $aNewSearches;
1026             }
1027
1028             // Split query into phrases
1029             // Commas are used to reduce the search space by indicating where phrases split
1030             if ($this->aStructuredQuery) {
1031                 $aPhrases = $this->aStructuredQuery;
1032                 $bStructuredPhrases = true;
1033             } else {
1034                 $aPhrases = explode(',', $sQuery);
1035                 $bStructuredPhrases = false;
1036             }
1037
1038             // Convert each phrase to standard form
1039             // Create a list of standard words
1040             // Get all 'sets' of words
1041             // Generate a complete list of all
1042             $aTokens = array();
1043             foreach ($aPhrases as $iPhrase => $sPhrase) {
1044                 $aPhrase = chksql(
1045                     $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1046                     "Cannot normalize query string (is it a UTF-8 string?)"
1047                 );
1048                 if (trim($aPhrase['string'])) {
1049                     $aPhrases[$iPhrase] = $aPhrase;
1050                     $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1051                     $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1052                     $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1053                 } else {
1054                     unset($aPhrases[$iPhrase]);
1055                 }
1056             }
1057
1058             // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1059             $aPhraseTypes = array_keys($aPhrases);
1060             $aPhrases = array_values($aPhrases);
1061
1062             if (sizeof($aTokens)) {
1063                 // Check which tokens we have, get the ID numbers
1064                 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1065                 $sSQL .= ' FROM word ';
1066                 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1067
1068                 if (CONST_Debug) var_Dump($sSQL);
1069
1070                 $aValidTokens = array();
1071                 if (sizeof($aTokens)) {
1072                     $aDatabaseWords = chksql(
1073                         $this->oDB->getAll($sSQL),
1074                         "Could not get word tokens."
1075                     );
1076                 } else {
1077                     $aDatabaseWords = array();
1078                 }
1079                 $aPossibleMainWordIDs = array();
1080                 $aWordFrequencyScores = array();
1081                 foreach ($aDatabaseWords as $aToken) {
1082                     // Very special case - require 2 letter country param to match the country code found
1083                     if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1084                         && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1085                     ) {
1086                         continue;
1087                     }
1088
1089                     if (isset($aValidTokens[$aToken['word_token']])) {
1090                         $aValidTokens[$aToken['word_token']][] = $aToken;
1091                     } else {
1092                         $aValidTokens[$aToken['word_token']] = array($aToken);
1093                     }
1094                     if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1095                     $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1096                 }
1097                 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1098
1099                 // Try and calculate GB postcodes we might be missing
1100                 foreach ($aTokens as $sToken) {
1101                     // Source of gb postcodes is now definitive - always use
1102                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1103                         if (substr($aData[1], -2, 1) != ' ') {
1104                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1105                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1106                         }
1107                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1108                         if ($aGBPostcodeLocation) {
1109                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
1110                         }
1111                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1112                         // US ZIP+4 codes - if there is no token,
1113                         // merge in the 5-digit ZIP code
1114                         if (isset($aValidTokens[$aData[1]])) {
1115                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1116                                 if (!$aToken['class']) {
1117                                     if (isset($aValidTokens[$sToken])) {
1118                                         $aValidTokens[$sToken][] = $aToken;
1119                                     } else {
1120                                         $aValidTokens[$sToken] = array($aToken);
1121                                     }
1122                                 }
1123                             }
1124                         }
1125                     }
1126                 }
1127
1128                 foreach ($aTokens as $sToken) {
1129                     // Unknown single word token with a number - assume it is a house number
1130                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1131                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1132                     }
1133                 }
1134
1135                 // Any words that have failed completely?
1136                 // TODO: suggestions
1137
1138                 // Start the search process
1139                 // array with: placeid => -1 | tiger-housenumber
1140                 $aResultPlaceIDs = array();
1141
1142                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1143
1144                 if ($this->bReverseInPlan) {
1145                     // Reverse phrase array and also reverse the order of the wordsets in
1146                     // the first and final phrase. Don't bother about phrases in the middle
1147                     // because order in the address doesn't matter.
1148                     $aPhrases = array_reverse($aPhrases);
1149                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1150                     if (sizeof($aPhrases) > 1) {
1151                         $aFinalPhrase = end($aPhrases);
1152                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1153                     }
1154                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1155
1156                     foreach ($aGroupedSearches as $aSearches) {
1157                         foreach ($aSearches as $aSearch) {
1158                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1159                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1160                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1161                             }
1162                         }
1163                     }
1164
1165                     $aGroupedSearches = $aReverseGroupedSearches;
1166                     ksort($aGroupedSearches);
1167                 }
1168             } else {
1169                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1170                 $aGroupedSearches = array();
1171                 foreach ($aSearches as $aSearch) {
1172                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1173                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1174                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1175                     }
1176                 }
1177                 ksort($aGroupedSearches);
1178             }
1179
1180             if (CONST_Debug) var_Dump($aGroupedSearches);
1181             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1182                 $aCopyGroupedSearches = $aGroupedSearches;
1183                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1184                     foreach ($aSearches as $iSearch => $aSearch) {
1185                         $aReductionsList = array($aSearch['aAddress']);
1186                         $iSearchRank = $aSearch['iSearchRank'];
1187                         while (sizeof($aReductionsList) > 0) {
1188                             $iSearchRank += 5;
1189                             if ($iSearchRank > iMaxRank) break 3;
1190                             $aNewReductionsList = array();
1191                             foreach ($aReductionsList as $aReductionsWordList) {
1192                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1193                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1194                                     $aReverseSearch = $aSearch;
1195                                     $aSearch['aAddress'] = $aReductionsWordListResult;
1196                                     $aSearch['iSearchRank'] = $iSearchRank;
1197                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1198                                     if (sizeof($aReductionsWordListResult) > 0) {
1199                                         $aNewReductionsList[] = $aReductionsWordListResult;
1200                                     }
1201                                 }
1202                             }
1203                             $aReductionsList = $aNewReductionsList;
1204                         }
1205                     }
1206                 }
1207                 ksort($aGroupedSearches);
1208             }
1209
1210             // Filter out duplicate searches
1211             $aSearchHash = array();
1212             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1213                 foreach ($aSearches as $iSearch => $aSearch) {
1214                     $sHash = serialize($aSearch);
1215                     if (isset($aSearchHash[$sHash])) {
1216                         unset($aGroupedSearches[$iGroup][$iSearch]);
1217                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1218                     } else {
1219                         $aSearchHash[$sHash] = 1;
1220                     }
1221                 }
1222             }
1223
1224             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1225
1226             $iGroupLoop = 0;
1227             $iQueryLoop = 0;
1228             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1229                 $iGroupLoop++;
1230                 foreach ($aSearches as $aSearch) {
1231                     $iQueryLoop++;
1232                     $searchedHousenumber = -1;
1233
1234                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1235                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1236
1237                     // No location term?
1238                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1239                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1240                             // Just looking for a country by code - look it up
1241                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1242                                 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1243                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1244                                 if ($bBoundingBoxSearch)
1245                                     $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1246                                 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1247                                 if (CONST_Debug) var_dump($sSQL);
1248                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1249                             } else {
1250                                 $aPlaceIDs = array();
1251                             }
1252                         } else {
1253                             if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1254                             if (!$aSearch['sClass']) continue;
1255
1256                             $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1257                             if (chksql($this->oDB->getOne($sSQL))) {
1258                                 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1259                                 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1260                                 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1261                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1262                                 if (sizeof($this->aExcludePlaceIDs)) {
1263                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1264                                 }
1265                                 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1266                                 $sSQL .= " limit $this->iLimit";
1267                                 if (CONST_Debug) var_dump($sSQL);
1268                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1269
1270                                 // If excluded place IDs are given, it is fair to assume that
1271                                 // there have been results in the small box, so no further
1272                                 // expansion in that case.
1273                                 // Also don't expand if bounded results were requested.
1274                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1275                                     $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1276                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1277                                     $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1278                                     if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1279                                     if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1280                                     $sSQL .= " LIMIT $this->iLimit";
1281                                     if (CONST_Debug) var_dump($sSQL);
1282                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1283                                 }
1284                             } else {
1285                                 $sSQL = "SELECT place_id ";
1286                                 $sSQL .= "FROM placex ";
1287                                 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1288                                 $sSQL .= "  AND type='".$aSearch['sType']."'";
1289                                 $sSQL .= "  AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1290                                 $sSQL .= "  AND linked_place_id is null";
1291                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1292                                 if ($this->sViewboxCentreSQL)   $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1293                                 $sSQL .= " LIMIT $this->iLimit";
1294                                 if (CONST_Debug) var_dump($sSQL);
1295                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1296                             }
1297                         }
1298                     } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1299                         // If a coordinate is given, the search must either
1300                         // be for a name or a special search. Ignore everythin else.
1301                         $aPlaceIDs = array();
1302                     } else {
1303                         $aPlaceIDs = array();
1304
1305                         // First we need a position, either aName or fLat or both
1306                         $aTerms = array();
1307                         $aOrder = array();
1308
1309                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1310                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1311                             $aOrder[] = "";
1312                             $aOrder[0] = "  (";
1313                             $aOrder[0] .= "   EXISTS(";
1314                             $aOrder[0] .= "     SELECT place_id ";
1315                             $aOrder[0] .= "     FROM placex ";
1316                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1317                             $aOrder[0] .= "       AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1318                             $aOrder[0] .= "     LIMIT 1";
1319                             $aOrder[0] .= "   ) ";
1320                             // also housenumbers from interpolation lines table are needed
1321                             $aOrder[0] .= "   OR EXISTS(";
1322                             $aOrder[0] .= "     SELECT place_id ";
1323                             $aOrder[0] .= "     FROM location_property_osmline ";
1324                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1325                             $aOrder[0] .= "       AND startnumber is not NULL";
1326                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1327                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1328                             $aOrder[0] .= "     LIMIT 1";
1329                             $aOrder[0] .= "   )";
1330                             $aOrder[0] .= " )";
1331                             $aOrder[0] .= " DESC";
1332                         }
1333
1334                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1335                         // they might be right - but they are just too darned expensive to run
1336                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1337                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1338                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1339                             // For infrequent name terms disable index usage for address
1340                             if (CONST_Search_NameOnlySearchFrequencyThreshold
1341                                 && sizeof($aSearch['aName']) == 1
1342                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1343                             ) {
1344                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1345                             } else {
1346                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1347                                 if (sizeof($aSearch['aAddressNonSearch'])) {
1348                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1349                                 }
1350                             }
1351                         }
1352                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1353                         if ($aSearch['sHouseNumber']) {
1354                             $aTerms[] = "address_rank between 16 and 27";
1355                         } else {
1356                             if ($this->iMinAddressRank > 0) {
1357                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1358                             }
1359                             if ($this->iMaxAddressRank < 30) {
1360                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1361                             }
1362                         }
1363                         if ($aSearch['oNear']) {
1364                             $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1365
1366                             $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1367                         }
1368                         if (sizeof($this->aExcludePlaceIDs)) {
1369                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1370                         }
1371                         if ($sCountryCodesSQL) {
1372                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
1373                         }
1374
1375                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1376                         if ($oNearPoint) {
1377                             $aOrder[] = $oNearPoint->distanceSQL('centroid');
1378                         }
1379
1380                         if ($aSearch['sHouseNumber']) {
1381                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
1382                         } else {
1383                             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1384                         }
1385                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1386                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1387
1388                         $aOrder[] = "$sImportanceSQL DESC";
1389                         if (sizeof($aSearch['aFullNameAddress'])) {
1390                             $sExactMatchSQL = ' ( ';
1391                             $sExactMatchSQL .= '   SELECT count(*) FROM ( ';
1392                             $sExactMatchSQL .= '      SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1393                             $sExactMatchSQL .= '      INTERSECT ';
1394                             $sExactMatchSQL .= '      SELECT unnest(nameaddress_vector)';
1395                             $sExactMatchSQL .= '   ) s';
1396                             $sExactMatchSQL .= ') as exactmatch';
1397                             $aOrder[] = 'exactmatch DESC';
1398                         } else {
1399                             $sExactMatchSQL = '0::int as exactmatch';
1400                         }
1401
1402                         if (sizeof($aTerms)) {
1403                             $sSQL = "SELECT place_id, ";
1404                             $sSQL .= $sExactMatchSQL;
1405                             $sSQL .= " FROM search_name";
1406                             $sSQL .= " WHERE ".join(' and ', $aTerms);
1407                             $sSQL .= " ORDER BY ".join(', ', $aOrder);
1408                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1409                                 $sSQL .= " LIMIT 20";
1410                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1411                                 $sSQL .= " LIMIT 1";
1412                             } else {
1413                                 $sSQL .= " LIMIT ".$this->iLimit;
1414                             }
1415
1416                             if (CONST_Debug) var_dump($sSQL);
1417                             $aViewBoxPlaceIDs = chksql(
1418                                 $this->oDB->getAll($sSQL),
1419                                 "Could not get places for search terms."
1420                             );
1421                             //var_dump($aViewBoxPlaceIDs);
1422                             // Did we have an viewbox matches?
1423                             $aPlaceIDs = array();
1424                             $bViewBoxMatch = false;
1425                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1426                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1427                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1428                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1429                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1430                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1431                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1432                             }
1433                         }
1434                         //var_Dump($aPlaceIDs);
1435                         //exit;
1436
1437                         //now search for housenumber, if housenumber provided
1438                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1439                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
1440                             $aRoadPlaceIDs = $aPlaceIDs;
1441                             $sPlaceIDs = join(',', $aPlaceIDs);
1442
1443                             // Now they are indexed, look for a house attached to a street we found
1444                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1445                             $sSQL = "SELECT place_id FROM placex ";
1446                             $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1447                             if (sizeof($this->aExcludePlaceIDs)) {
1448                                 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1449                             }
1450                             $sSQL .= " LIMIT $this->iLimit";
1451                             if (CONST_Debug) var_dump($sSQL);
1452                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1453
1454                             // if nothing found, search in the interpolation line table
1455                             if (!sizeof($aPlaceIDs)) {
1456                                 // do we need to use transliteration and the regex for housenumbers???
1457                                 //new query for lines, not housenumbers anymore
1458                                 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1459                                 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1460                                 if ($searchedHousenumber%2 == 0) {
1461                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1462                                     $sSQL .= "interpolationtype='even'";
1463                                 } else {
1464                                     //look for housenumber in streets with interpolationtype odd or all
1465                                     $sSQL .= "interpolationtype='odd'";
1466                                 }
1467                                 $sSQL .= " or interpolationtype='all') and ";
1468                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1469                                 $sSQL .= $searchedHousenumber."<=endnumber";
1470
1471                                 if (sizeof($this->aExcludePlaceIDs)) {
1472                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1473                                 }
1474                                 //$sSQL .= " limit $this->iLimit";
1475                                 if (CONST_Debug) var_dump($sSQL);
1476                                 //get place IDs
1477                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1478                             }
1479
1480                             // If nothing found try the aux fallback table
1481                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1482                                 $sSQL = "SELECT place_id FROM location_property_aux ";
1483                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1484                                 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1485                                 if (sizeof($this->aExcludePlaceIDs)) {
1486                                     $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1487                                 }
1488                                 //$sSQL .= " limit $this->iLimit";
1489                                 if (CONST_Debug) var_dump($sSQL);
1490                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1491                             }
1492
1493                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1494                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1495                                 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1496                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1497                                 if ($searchedHousenumber%2 == 0) {
1498                                     $sSQL .= "interpolationtype='even'";
1499                                 } else {
1500                                     $sSQL .= "interpolationtype='odd'";
1501                                 }
1502                                 $sSQL .= " or interpolationtype='all') and ";
1503                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1504                                 $sSQL .= $searchedHousenumber."<=endnumber";
1505
1506                                 if (sizeof($this->aExcludePlaceIDs)) {
1507                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1508                                 }
1509                                 //$sSQL .= " limit $this->iLimit";
1510                                 if (CONST_Debug) var_dump($sSQL);
1511                                 //get place IDs
1512                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1513                             }
1514
1515                             // Fallback to the road (if no housenumber was found)
1516                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1517                                 $aPlaceIDs = $aRoadPlaceIDs;
1518                                 //set to -1, if no housenumbers were found
1519                                 $searchedHousenumber = -1;
1520                             }
1521                             //else: housenumber was found, remains saved in searchedHousenumber
1522                         }
1523
1524
1525                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1526                             $sPlaceIDs = join(',', $aPlaceIDs);
1527                             $aClassPlaceIDs = array();
1528
1529                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1530                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1531                                 $sSQL = "SELECT place_id ";
1532                                 $sSQL .= " FROM placex ";
1533                                 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1534                                 $sSQL .= "   AND class='".$aSearch['sClass']."' ";
1535                                 $sSQL .= "   AND type='".$aSearch['sType']."'";
1536                                 $sSQL .= "   AND linked_place_id is null";
1537                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1538                                 $sSQL .= " ORDER BY rank_search ASC ";
1539                                 $sSQL .= " LIMIT $this->iLimit";
1540                                 if (CONST_Debug) var_dump($sSQL);
1541                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1542                             }
1543
1544                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1545                                 $sSQL = "SELECT count(*) FROM pg_tables ";
1546                                 $sSQL .= "WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1547                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1548
1549                                 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1550
1551                                 if (CONST_Debug) var_dump($sSQL);
1552                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1553
1554                                 // For state / country level searches the normal radius search doesn't work very well
1555                                 $sPlaceGeom = false;
1556                                 if ($this->iMaxRank < 9 && $bCacheTable) {
1557                                     // Try and get a polygon to search in instead
1558                                     $sSQL = "SELECT geometry ";
1559                                     $sSQL .= " FROM placex";
1560                                     $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1561                                     $sSQL .= "   AND rank_search < $this->iMaxRank + 5";
1562                                     $sSQL .= "   AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1563                                     $sSQL .= " ORDER BY rank_search ASC ";
1564                                     $sSQL .= " LIMIT 1";
1565                                     if (CONST_Debug) var_dump($sSQL);
1566                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1567                                 }
1568
1569                                 if ($sPlaceGeom) {
1570                                     $sPlaceIDs = false;
1571                                 } else {
1572                                     $this->iMaxRank += 5;
1573                                     $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1574                                     if (CONST_Debug) var_dump($sSQL);
1575                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1576                                     $sPlaceIDs = join(',', $aPlaceIDs);
1577                                 }
1578
1579                                 if ($sPlaceIDs || $sPlaceGeom) {
1580                                     $fRange = 0.01;
1581                                     if ($bCacheTable) {
1582                                         // More efficient - can make the range bigger
1583                                         $fRange = 0.05;
1584
1585                                         $sOrderBySQL = '';
1586                                         if ($oNearPoint) {
1587                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1588                                         } elseif ($sPlaceIDs) {
1589                                             $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1590                                         } elseif ($sPlaceGeom) {
1591                                             $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1592                                         }
1593
1594                                         $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1595                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1596                                         if ($sPlaceIDs) {
1597                                             $sSQL .= ",placex as f where ";
1598                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1599                                         }
1600                                         if ($sPlaceGeom) {
1601                                             $sSQL .= " where ";
1602                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1603                                         }
1604                                         if (sizeof($this->aExcludePlaceIDs)) {
1605                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1606                                         }
1607                                         if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1608                                         if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1609                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1610                                         $sSQL .= " limit $this->iLimit";
1611                                         if (CONST_Debug) var_dump($sSQL);
1612                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1613                                     } else {
1614                                         if ($aSearch['oNear']) {
1615                                             $fRange = $aSearch['oNear']->radius();
1616                                         }
1617
1618                                         $sOrderBySQL = '';
1619                                         if ($oNearPoint) {
1620                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1621                                         } else {
1622                                             $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1623                                         }
1624
1625                                         $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1626                                         $sSQL .= " FROM placex as l, placex as f ";
1627                                         $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1628                                         $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1629                                         $sSQL .= "  AND l.class='".$aSearch['sClass']."' ";
1630                                         $sSQL .= "  AND l.type='".$aSearch['sType']."' ";
1631                                         if (sizeof($this->aExcludePlaceIDs)) {
1632                                             $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1633                                         }
1634                                         if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1635                                         if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1636                                         if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1637                                         $sSQL .= " limit $this->iLimit";
1638                                         if (CONST_Debug) var_dump($sSQL);
1639                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1640                                     }
1641                                 }
1642                             }
1643                             $aPlaceIDs = $aClassPlaceIDs;
1644                         }
1645                     }
1646
1647                     if (CONST_Debug) {
1648                         echo "<br><b>Place IDs:</b> ";
1649                         var_Dump($aPlaceIDs);
1650                     }
1651
1652                     foreach ($aPlaceIDs as $iPlaceID) {
1653                         // array for placeID => -1 | Tiger housenumber
1654                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1655                     }
1656                     if ($iQueryLoop > 20) break;
1657                 }
1658
1659                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1660                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1661                     // reduces the number of place ids, like a filter
1662                     // rank_address is 30 for interpolated housenumbers
1663                     $sSQL = "SELECT place_id ";
1664                     $sSQL .= "FROM placex ";
1665                     $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1666                     $sSQL .= "  AND (";
1667                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1668                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1669                         $sSQL .= "     OR (extratags->'place') = 'city'";
1670                     }
1671                     if ($this->aAddressRankList) {
1672                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1673                     }
1674                     if (CONST_Use_US_Tiger_Data) {
1675                         $sSQL .= "  ) ";
1676                         $sSQL .= "UNION ";
1677                         $sSQL .= "  SELECT place_id ";
1678                         $sSQL .= "  FROM location_property_tiger ";
1679                         $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1680                         $sSQL .= "    AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1681                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1682                     }
1683                     $sSQL .= ") UNION ";
1684                     $sSQL .= "  SELECT place_id ";
1685                     $sSQL .= "  FROM location_property_osmline ";
1686                     $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1687                     $sSQL .= "    AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1688                     if (CONST_Debug) var_dump($sSQL);
1689                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1690                     $tempIDs = array();
1691                     foreach ($aFilteredPlaceIDs as $placeID) {
1692                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1693                     }
1694                     $aResultPlaceIDs = $tempIDs;
1695                 }
1696
1697                 //exit;
1698                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1699                 if ($iGroupLoop > 4) break;
1700                 if ($iQueryLoop > 30) break;
1701             }
1702
1703             // Did we find anything?
1704             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1705                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1706             }
1707         } else {
1708             // Just interpret as a reverse geocode
1709             $oReverse = new ReverseGeocode($this->oDB);
1710             $oReverse->setZoom(18);
1711
1712             $aLookup = $oReverse->lookup(
1713                 $oNearPoint->lat(),
1714                 $oNearPoint->lon(),
1715                 false
1716             );
1717
1718             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1719
1720             if ($aLookup['place_id']) {
1721                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1722                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1723             } else {
1724                 $aSearchResults = array();
1725             }
1726         }
1727
1728         // No results? Done
1729         if (!sizeof($aSearchResults)) {
1730             if ($this->bFallback) {
1731                 if ($this->fallbackStructuredQuery()) {
1732                     return $this->lookup();
1733                 }
1734             }
1735
1736             return array();
1737         }
1738
1739         $aClassType = getClassTypesWithImportance();
1740         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1741         foreach ($aRecheckWords as $i => $sWord) {
1742             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1743         }
1744
1745         if (CONST_Debug) {
1746             echo '<i>Recheck words:<\i>';
1747             var_dump($aRecheckWords);
1748         }
1749
1750         $oPlaceLookup = new PlaceLookup($this->oDB);
1751         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1752         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1753         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1754         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1755         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1756         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1757
1758         foreach ($aSearchResults as $iResNum => $aResult) {
1759             // Default
1760             $fDiameter = getResultDiameter($aResult);
1761
1762             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1763             if ($aOutlineResult) {
1764                 $aResult = array_merge($aResult, $aOutlineResult);
1765             }
1766             
1767             if ($aResult['extra_place'] == 'city') {
1768                 $aResult['class'] = 'place';
1769                 $aResult['type'] = 'city';
1770                 $aResult['rank_search'] = 16;
1771             }
1772
1773             // Is there an icon set for this type of result?
1774             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1775                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1776             ) {
1777                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1778             }
1779
1780             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1781                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1782             ) {
1783                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1784             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1785                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1786             ) {
1787                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1788             }
1789             // if tag '&addressdetails=1' is set in query
1790             if ($this->bIncludeAddressDetails) {
1791                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1792                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1793                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1794                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1795                 }
1796             }
1797
1798             if ($this->bIncludeExtraTags) {
1799                 if ($aResult['extra']) {
1800                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1801                 } else {
1802                     $aResult['sExtraTags'] = (object) array();
1803                 }
1804             }
1805
1806             if ($this->bIncludeNameDetails) {
1807                 if ($aResult['names']) {
1808                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1809                 } else {
1810                     $aResult['sNameDetails'] = (object) array();
1811                 }
1812             }
1813
1814             // Adjust importance for the number of exact string matches in the result
1815             $aResult['importance'] = max(0.001, $aResult['importance']);
1816             $iCountWords = 0;
1817             $sAddress = $aResult['langaddress'];
1818             foreach ($aRecheckWords as $i => $sWord) {
1819                 if (stripos($sAddress, $sWord)!==false) {
1820                     $iCountWords++;
1821                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1822                 }
1823             }
1824
1825             $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
1826
1827             $aResult['name'] = $aResult['langaddress'];
1828             // secondary ordering (for results with same importance (the smaller the better):
1829             // - approximate importance of address parts
1830             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1831             // - number of exact matches from the query
1832             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1833                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1834             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1835                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1836             }
1837             // - importance of the class/type
1838             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1839                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1840             ) {
1841                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1842             } else {
1843                 $aResult['foundorder'] += 0.01;
1844             }
1845             if (CONST_Debug) var_dump($aResult);
1846             $aSearchResults[$iResNum] = $aResult;
1847         }
1848         uasort($aSearchResults, 'byImportance');
1849
1850         $aOSMIDDone = array();
1851         $aClassTypeNameDone = array();
1852         $aToFilter = $aSearchResults;
1853         $aSearchResults = array();
1854
1855         $bFirst = true;
1856         foreach ($aToFilter as $iResNum => $aResult) {
1857             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1858             if ($bFirst) {
1859                 $fLat = $aResult['lat'];
1860                 $fLon = $aResult['lon'];
1861                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1862                 $bFirst = false;
1863             }
1864             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1865                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1866             ) {
1867                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1868                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1869                 $aSearchResults[] = $aResult;
1870             }
1871
1872             // Absolute limit on number of results
1873             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1874         }
1875
1876         return $aSearchResults;
1877     } // end lookup()
1878 } // end class