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