]> git.openstreetmap.org Git - nominatim.git/blob - lib/Geocode.php
take postcode into account for other searches
[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                 // Try and calculate GB postcodes we might be missing
1138                 foreach ($aTokens as $sToken) {
1139                     // Source of gb postcodes is now definitive - always use
1140                     if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1141                         if (substr($aData[1], -2, 1) != ' ') {
1142                             $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1143                             $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1144                         }
1145                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1146                         if ($aGBPostcodeLocation) {
1147                             $aValidTokens[$sToken] = $aGBPostcodeLocation;
1148                         }
1149                     } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1150                         // US ZIP+4 codes - if there is no token,
1151                         // merge in the 5-digit ZIP code
1152                         if (isset($aValidTokens[$aData[1]])) {
1153                             foreach ($aValidTokens[$aData[1]] as $aToken) {
1154                                 if (!$aToken['class']) {
1155                                     if (isset($aValidTokens[$sToken])) {
1156                                         $aValidTokens[$sToken][] = $aToken;
1157                                     } else {
1158                                         $aValidTokens[$sToken] = array($aToken);
1159                                     }
1160                                 }
1161                             }
1162                         }
1163                     }
1164                 }
1165
1166                 foreach ($aTokens as $sToken) {
1167                     // Unknown single word token with a number - assume it is a house number
1168                     if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1169                         $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1170                     }
1171                 }
1172
1173                 // Any words that have failed completely?
1174                 // TODO: suggestions
1175
1176                 // Start the search process
1177                 // array with: placeid => -1 | tiger-housenumber
1178                 $aResultPlaceIDs = array();
1179
1180                 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1181
1182                 if ($this->bReverseInPlan) {
1183                     // Reverse phrase array and also reverse the order of the wordsets in
1184                     // the first and final phrase. Don't bother about phrases in the middle
1185                     // because order in the address doesn't matter.
1186                     $aPhrases = array_reverse($aPhrases);
1187                     $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1188                     if (sizeof($aPhrases) > 1) {
1189                         $aFinalPhrase = end($aPhrases);
1190                         $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1191                     }
1192                     $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1193
1194                     foreach ($aGroupedSearches as $aSearches) {
1195                         foreach ($aSearches as $aSearch) {
1196                             if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1197                                 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1198                                 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1199                             }
1200                         }
1201                     }
1202
1203                     $aGroupedSearches = $aReverseGroupedSearches;
1204                     ksort($aGroupedSearches);
1205                 }
1206             } else {
1207                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1208                 $aGroupedSearches = array();
1209                 foreach ($aSearches as $aSearch) {
1210                     if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1211                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1212                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1213                     }
1214                 }
1215                 ksort($aGroupedSearches);
1216             }
1217
1218             if (CONST_Debug) var_Dump($aGroupedSearches);
1219             if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1220                 $aCopyGroupedSearches = $aGroupedSearches;
1221                 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1222                     foreach ($aSearches as $iSearch => $aSearch) {
1223                         $aReductionsList = array($aSearch['aAddress']);
1224                         $iSearchRank = $aSearch['iSearchRank'];
1225                         while (sizeof($aReductionsList) > 0) {
1226                             $iSearchRank += 5;
1227                             if ($iSearchRank > iMaxRank) break 3;
1228                             $aNewReductionsList = array();
1229                             foreach ($aReductionsList as $aReductionsWordList) {
1230                                 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1231                                     $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1232                                     $aReverseSearch = $aSearch;
1233                                     $aSearch['aAddress'] = $aReductionsWordListResult;
1234                                     $aSearch['iSearchRank'] = $iSearchRank;
1235                                     $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1236                                     if (sizeof($aReductionsWordListResult) > 0) {
1237                                         $aNewReductionsList[] = $aReductionsWordListResult;
1238                                     }
1239                                 }
1240                             }
1241                             $aReductionsList = $aNewReductionsList;
1242                         }
1243                     }
1244                 }
1245                 ksort($aGroupedSearches);
1246             }
1247
1248             // Filter out duplicate searches
1249             $aSearchHash = array();
1250             foreach ($aGroupedSearches as $iGroup => $aSearches) {
1251                 foreach ($aSearches as $iSearch => $aSearch) {
1252                     $sHash = serialize($aSearch);
1253                     if (isset($aSearchHash[$sHash])) {
1254                         unset($aGroupedSearches[$iGroup][$iSearch]);
1255                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1256                     } else {
1257                         $aSearchHash[$sHash] = 1;
1258                     }
1259                 }
1260             }
1261
1262             if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1263
1264             $iGroupLoop = 0;
1265             $iQueryLoop = 0;
1266             foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1267                 $iGroupLoop++;
1268                 foreach ($aSearches as $aSearch) {
1269                     $iQueryLoop++;
1270                     $searchedHousenumber = -1;
1271
1272                     if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1273                     if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1274
1275                     if ($sCountryCodesSQL && $aSearch['sCountryCode'] && !in_array($aSearch['sCountryCode'], $this->aCountryCodes)) {
1276                         continue;
1277                     }
1278
1279                     // No location term?
1280                     if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1281                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1282                             // Just looking for a country by code - look it up
1283                             if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1284                                 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1285                                 if ($bBoundingBoxSearch)
1286                                     $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1287                                 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1288                                 if (CONST_Debug) var_dump($sSQL);
1289                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1290                             } else {
1291                                 $aPlaceIDs = array();
1292                             }
1293                         } else {
1294                             if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1295                             if (!$aSearch['sClass']) continue;
1296
1297                             $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1298                             if (chksql($this->oDB->getOne($sSQL))) {
1299                                 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1300                                 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1301                                 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1302                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1303                                 if (sizeof($this->aExcludePlaceIDs)) {
1304                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1305                                 }
1306                                 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1307                                 $sSQL .= " limit $this->iLimit";
1308                                 if (CONST_Debug) var_dump($sSQL);
1309                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1310
1311                                 // If excluded place IDs are given, it is fair to assume that
1312                                 // there have been results in the small box, so no further
1313                                 // expansion in that case.
1314                                 // Also don't expand if bounded results were requested.
1315                                 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1316                                     $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1317                                     if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1318                                     $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1319                                     if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1320                                     if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1321                                     $sSQL .= " LIMIT $this->iLimit";
1322                                     if (CONST_Debug) var_dump($sSQL);
1323                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1324                                 }
1325                             } else {
1326                                 $sSQL = "SELECT place_id ";
1327                                 $sSQL .= "FROM placex ";
1328                                 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1329                                 $sSQL .= "  AND type='".$aSearch['sType']."'";
1330                                 $sSQL .= "  AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1331                                 $sSQL .= "  AND linked_place_id is null";
1332                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1333                                 if ($this->sViewboxCentreSQL)   $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1334                                 $sSQL .= " LIMIT $this->iLimit";
1335                                 if (CONST_Debug) var_dump($sSQL);
1336                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1337                             }
1338                         }
1339                     } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1340                         // If a coordinate is given, the search must either
1341                         // be for a name or a special search. Ignore everythin else.
1342                         $aPlaceIDs = array();
1343                     } elseif ($aSearch['sOperator'] == 'postcode') {
1344                         $sSQL  = "SELECT p.place_id FROM location_postcode p ";
1345                         if (sizeof($aSearch['aAddress'])) {
1346                             $sSQL .= ", search_name s ";
1347                             $sSQL .= "WHERE s.place_id = p.parent_place_id ";
1348                             $sSQL .= "AND array_cat(s.nameaddress_vector, s.name_vector) @> ARRAY[".join($aSearch['aAddress'], ",")."] AND ";
1349                         } else {
1350                             $sSQL .= " WHERE ";
1351                         }
1352                         $sSQL .= "p.postcode = '".pg_escape_string(reset($aSearch['aName']))."'";
1353                         if ($aSearch['sCountryCode']) {
1354                             $sSQL .= " AND p.country_code = '".$aSearch['sCountryCode']."'";
1355                         } elseif ($sCountryCodesSQL) {
1356                             $sSQL .= " AND p.country_code in ($sCountryCodesSQL)";
1357                         }
1358                         $sSQL .= " LIMIT $this->iLimit";
1359                         if (CONST_Debug) var_dump($sSQL);
1360                         $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1361                     } else {
1362                         $aPlaceIDs = array();
1363
1364                         // First we need a position, either aName or fLat or both
1365                         $aTerms = array();
1366                         $aOrder = array();
1367
1368                         if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1369                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1370                             $aOrder[] = "";
1371                             $aOrder[0] = "  (";
1372                             $aOrder[0] .= "   EXISTS(";
1373                             $aOrder[0] .= "     SELECT place_id ";
1374                             $aOrder[0] .= "     FROM placex ";
1375                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1376                             $aOrder[0] .= "       AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1377                             $aOrder[0] .= "     LIMIT 1";
1378                             $aOrder[0] .= "   ) ";
1379                             // also housenumbers from interpolation lines table are needed
1380                             $aOrder[0] .= "   OR EXISTS(";
1381                             $aOrder[0] .= "     SELECT place_id ";
1382                             $aOrder[0] .= "     FROM location_property_osmline ";
1383                             $aOrder[0] .= "     WHERE parent_place_id = search_name.place_id";
1384                             $aOrder[0] .= "       AND startnumber is not NULL";
1385                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1386                             $aOrder[0] .= "       AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1387                             $aOrder[0] .= "     LIMIT 1";
1388                             $aOrder[0] .= "   )";
1389                             $aOrder[0] .= " )";
1390                             $aOrder[0] .= " DESC";
1391                         }
1392
1393                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1394                         // they might be right - but they are just too darned expensive to run
1395                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1396                         if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1397                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1398                             // For infrequent name terms disable index usage for address
1399                             if (CONST_Search_NameOnlySearchFrequencyThreshold
1400                                 && sizeof($aSearch['aName']) == 1
1401                                 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1402                             ) {
1403                                 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1404                             } else {
1405                                 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1406                                 if (sizeof($aSearch['aAddressNonSearch'])) {
1407                                     $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1408                                 }
1409                             }
1410                         }
1411                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1412                         if ($aSearch['sHouseNumber']) {
1413                             $aTerms[] = "address_rank between 16 and 27";
1414                         } else {
1415                             if ($this->iMinAddressRank > 0) {
1416                                 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1417                             }
1418                             if ($this->iMaxAddressRank < 30) {
1419                                 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1420                             }
1421                         }
1422                         if ($aSearch['oNear']) {
1423                             $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1424
1425                             $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1426                         } elseif ($aSearch['sPostcode']) {
1427                             $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$aSearch['sPostcode']."')";
1428                         }
1429                         if (sizeof($this->aExcludePlaceIDs)) {
1430                             $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1431                         }
1432                         if ($sCountryCodesSQL) {
1433                             $aTerms[] = "country_code in ($sCountryCodesSQL)";
1434                         }
1435
1436                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1437                         if ($oNearPoint) {
1438                             $aOrder[] = $oNearPoint->distanceSQL('centroid');
1439                         }
1440
1441                         if ($aSearch['sHouseNumber']) {
1442                             $sImportanceSQL = '- abs(26 - address_rank) + 3';
1443                         } else {
1444                             $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1445                         }
1446                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1447                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1448
1449                         $aOrder[] = "$sImportanceSQL DESC";
1450                         if (sizeof($aSearch['aFullNameAddress'])) {
1451                             $sExactMatchSQL = ' ( ';
1452                             $sExactMatchSQL .= '   SELECT count(*) FROM ( ';
1453                             $sExactMatchSQL .= '      SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1454                             $sExactMatchSQL .= '      INTERSECT ';
1455                             $sExactMatchSQL .= '      SELECT unnest(nameaddress_vector)';
1456                             $sExactMatchSQL .= '   ) s';
1457                             $sExactMatchSQL .= ') as exactmatch';
1458                             $aOrder[] = 'exactmatch DESC';
1459                         } else {
1460                             $sExactMatchSQL = '0::int as exactmatch';
1461                         }
1462
1463                         if (sizeof($aTerms)) {
1464                             $sSQL = "SELECT place_id, ";
1465                             $sSQL .= $sExactMatchSQL;
1466                             $sSQL .= " FROM search_name";
1467                             $sSQL .= " WHERE ".join(' and ', $aTerms);
1468                             $sSQL .= " ORDER BY ".join(', ', $aOrder);
1469                             if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1470                                 $sSQL .= " LIMIT 20";
1471                             } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1472                                 $sSQL .= " LIMIT 1";
1473                             } else {
1474                                 $sSQL .= " LIMIT ".$this->iLimit;
1475                             }
1476
1477                             if (CONST_Debug) var_dump($sSQL);
1478                             $aViewBoxPlaceIDs = chksql(
1479                                 $this->oDB->getAll($sSQL),
1480                                 "Could not get places for search terms."
1481                             );
1482                             //var_dump($aViewBoxPlaceIDs);
1483                             // Did we have an viewbox matches?
1484                             $aPlaceIDs = array();
1485                             $bViewBoxMatch = false;
1486                             foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1487                                 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1488                                 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1489                                 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1490                                 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1491                                 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1492                                 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1493                             }
1494                         }
1495                         //var_Dump($aPlaceIDs);
1496                         //exit;
1497
1498                         //now search for housenumber, if housenumber provided
1499                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1500                             $searchedHousenumber = intval($aSearch['sHouseNumber']);
1501                             $aRoadPlaceIDs = $aPlaceIDs;
1502                             $sPlaceIDs = join(',', $aPlaceIDs);
1503
1504                             // Now they are indexed, look for a house attached to a street we found
1505                             $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1506                             $sSQL = "SELECT place_id FROM placex ";
1507                             $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1508                             if (sizeof($this->aExcludePlaceIDs)) {
1509                                 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1510                             }
1511                             $sSQL .= " LIMIT $this->iLimit";
1512                             if (CONST_Debug) var_dump($sSQL);
1513                             $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1514
1515                             // if nothing found, search in the interpolation line table
1516                             if (!sizeof($aPlaceIDs)) {
1517                                 // do we need to use transliteration and the regex for housenumbers???
1518                                 //new query for lines, not housenumbers anymore
1519                                 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1520                                 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1521                                 if ($searchedHousenumber%2 == 0) {
1522                                     //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1523                                     $sSQL .= "interpolationtype='even'";
1524                                 } else {
1525                                     //look for housenumber in streets with interpolationtype odd or all
1526                                     $sSQL .= "interpolationtype='odd'";
1527                                 }
1528                                 $sSQL .= " or interpolationtype='all') and ";
1529                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1530                                 $sSQL .= $searchedHousenumber."<=endnumber";
1531
1532                                 if (sizeof($this->aExcludePlaceIDs)) {
1533                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1534                                 }
1535                                 //$sSQL .= " limit $this->iLimit";
1536                                 if (CONST_Debug) var_dump($sSQL);
1537                                 //get place IDs
1538                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1539                             }
1540
1541                             // If nothing found try the aux fallback table
1542                             if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1543                                 $sSQL = "SELECT place_id FROM location_property_aux ";
1544                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1545                                 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1546                                 if (sizeof($this->aExcludePlaceIDs)) {
1547                                     $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1548                                 }
1549                                 //$sSQL .= " limit $this->iLimit";
1550                                 if (CONST_Debug) var_dump($sSQL);
1551                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1552                             }
1553
1554                             //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1555                             if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1556                                 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1557                                 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1558                                 if ($searchedHousenumber%2 == 0) {
1559                                     $sSQL .= "interpolationtype='even'";
1560                                 } else {
1561                                     $sSQL .= "interpolationtype='odd'";
1562                                 }
1563                                 $sSQL .= " or interpolationtype='all') and ";
1564                                 $sSQL .= $searchedHousenumber.">=startnumber and ";
1565                                 $sSQL .= $searchedHousenumber."<=endnumber";
1566
1567                                 if (sizeof($this->aExcludePlaceIDs)) {
1568                                     $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1569                                 }
1570                                 //$sSQL .= " limit $this->iLimit";
1571                                 if (CONST_Debug) var_dump($sSQL);
1572                                 //get place IDs
1573                                 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1574                             }
1575
1576                             // Fallback to the road (if no housenumber was found)
1577                             if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1578                                 $aPlaceIDs = $aRoadPlaceIDs;
1579                                 //set to -1, if no housenumbers were found
1580                                 $searchedHousenumber = -1;
1581                             }
1582                             //else: housenumber was found, remains saved in searchedHousenumber
1583                         }
1584
1585
1586                         if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1587                             $sPlaceIDs = join(',', $aPlaceIDs);
1588                             $aClassPlaceIDs = array();
1589
1590                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1591                                 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1592                                 $sSQL = "SELECT place_id ";
1593                                 $sSQL .= " FROM placex ";
1594                                 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1595                                 $sSQL .= "   AND class='".$aSearch['sClass']."' ";
1596                                 $sSQL .= "   AND type='".$aSearch['sType']."'";
1597                                 $sSQL .= "   AND linked_place_id is null";
1598                                 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1599                                 $sSQL .= " ORDER BY rank_search ASC ";
1600                                 $sSQL .= " LIMIT $this->iLimit";
1601                                 if (CONST_Debug) var_dump($sSQL);
1602                                 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1603                             }
1604
1605                             if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1606                                 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
1607                                 $sSQL = "SELECT count(*) FROM pg_tables ";
1608                                 $sSQL .= "WHERE tablename = '$sClassTable'";
1609                                 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1610
1611                                 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1612
1613                                 if (CONST_Debug) var_dump($sSQL);
1614                                 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1615
1616                                 // For state / country level searches the normal radius search doesn't work very well
1617                                 $sPlaceGeom = false;
1618                                 if ($this->iMaxRank < 9 && $bCacheTable) {
1619                                     // Try and get a polygon to search in instead
1620                                     $sSQL = "SELECT geometry ";
1621                                     $sSQL .= " FROM placex";
1622                                     $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1623                                     $sSQL .= "   AND rank_search < $this->iMaxRank + 5";
1624                                     $sSQL .= "   AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1625                                     $sSQL .= " ORDER BY rank_search ASC ";
1626                                     $sSQL .= " LIMIT 1";
1627                                     if (CONST_Debug) var_dump($sSQL);
1628                                     $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1629                                 }
1630
1631                                 if ($sPlaceGeom) {
1632                                     $sPlaceIDs = false;
1633                                 } else {
1634                                     $this->iMaxRank += 5;
1635                                     $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1636                                     if (CONST_Debug) var_dump($sSQL);
1637                                     $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1638                                     $sPlaceIDs = join(',', $aPlaceIDs);
1639                                 }
1640
1641                                 if ($sPlaceIDs || $sPlaceGeom) {
1642                                     $fRange = 0.01;
1643                                     if ($bCacheTable) {
1644                                         // More efficient - can make the range bigger
1645                                         $fRange = 0.05;
1646
1647                                         $sOrderBySQL = '';
1648                                         if ($oNearPoint) {
1649                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1650                                         } elseif ($sPlaceIDs) {
1651                                             $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1652                                         } elseif ($sPlaceGeom) {
1653                                             $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1654                                         }
1655
1656                                         $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
1657                                         $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
1658                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1659                                         if ($sPlaceIDs) {
1660                                             $sSQL .= ",placex as f where ";
1661                                             $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1662                                         }
1663                                         if ($sPlaceGeom) {
1664                                             $sSQL .= " where ";
1665                                             $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1666                                         }
1667                                         if (sizeof($this->aExcludePlaceIDs)) {
1668                                             $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1669                                         }
1670                                         if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1671                                         $sSQL .= 'limit 300) i ';
1672                                         if ($sOrderBySQL) $sSQL .= "order by order_term asc";
1673                                         if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1674                                         $sSQL .= " limit $this->iLimit";
1675                                         if (CONST_Debug) var_dump($sSQL);
1676                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1677                                     } else {
1678                                         if ($aSearch['oNear']) {
1679                                             $fRange = $aSearch['oNear']->radius();
1680                                         }
1681
1682                                         $sOrderBySQL = '';
1683                                         if ($oNearPoint) {
1684                                             $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1685                                         } else {
1686                                             $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1687                                         }
1688
1689                                         $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1690                                         $sSQL .= " FROM placex as l, placex as f ";
1691                                         $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1692                                         $sSQL .= "  AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1693                                         $sSQL .= "  AND l.class='".$aSearch['sClass']."' ";
1694                                         $sSQL .= "  AND l.type='".$aSearch['sType']."' ";
1695                                         if (sizeof($this->aExcludePlaceIDs)) {
1696                                             $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1697                                         }
1698                                         if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1699                                         if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1700                                         if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1701                                         $sSQL .= " limit $this->iLimit";
1702                                         if (CONST_Debug) var_dump($sSQL);
1703                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1704                                     }
1705                                 }
1706                             }
1707                             $aPlaceIDs = $aClassPlaceIDs;
1708                         }
1709                     }
1710
1711                     if (CONST_Debug) {
1712                         echo "<br><b>Place IDs:</b> ";
1713                         var_Dump($aPlaceIDs);
1714                     }
1715
1716                     if ($aSearch['sPostcode']) {
1717                         $sSQL = 'SELECT place_id FROM placex';
1718                         $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1719                         $sSQL .= " AND postcode = '".pg_escape_string($aSearch['sPostcode'])."'";
1720                         if (CONST_Debug) var_dump($sSQL);
1721                         $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1722                         if ($aFilteredPlaceIDs) {
1723                             $aPlaceIDs = $aFilteredPlaceIDs;
1724                             if (CONST_Debug) {
1725                                 echo "<br><b>Place IDs after postcode filtering:</b> ";
1726                                 var_Dump($aPlaceIDs);
1727                             }
1728                         }
1729                     }
1730
1731                     foreach ($aPlaceIDs as $iPlaceID) {
1732                         // array for placeID => -1 | Tiger housenumber
1733                         $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1734                     }
1735                     if ($iQueryLoop > 20) break;
1736                 }
1737
1738                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1739                     // Need to verify passes rank limits before dropping out of the loop (yuk!)
1740                     // reduces the number of place ids, like a filter
1741                     // rank_address is 30 for interpolated housenumbers
1742                     $sSQL = "SELECT place_id ";
1743                     $sSQL .= "FROM placex ";
1744                     $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1745                     $sSQL .= "  AND (";
1746                     $sSQL .= "         placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1747                     if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1748                         $sSQL .= "     OR (extratags->'place') = 'city'";
1749                     }
1750                     if ($this->aAddressRankList) {
1751                         $sSQL .= "     OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1752                     }
1753                     if (CONST_Use_US_Tiger_Data) {
1754                         $sSQL .= "  ) ";
1755                         $sSQL .= "UNION ";
1756                         $sSQL .= "  SELECT place_id ";
1757                         $sSQL .= "  FROM location_property_tiger ";
1758                         $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1759                         $sSQL .= "    AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1760                         if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1761                     }
1762                     $sSQL .= ") UNION ";
1763                     $sSQL .= "  SELECT place_id ";
1764                     $sSQL .= "  FROM location_property_osmline ";
1765                     $sSQL .= "  WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1766                     $sSQL .= "    AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1767                     if (CONST_Debug) var_dump($sSQL);
1768                     $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1769                     $tempIDs = array();
1770                     foreach ($aFilteredPlaceIDs as $placeID) {
1771                         $tempIDs[$placeID] = $aResultPlaceIDs[$placeID];  //assign housenumber to placeID
1772                     }
1773                     $aResultPlaceIDs = $tempIDs;
1774                 }
1775
1776                 //exit;
1777                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1778                 if ($iGroupLoop > 4) break;
1779                 if ($iQueryLoop > 30) break;
1780             }
1781
1782             // Did we find anything?
1783             if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1784                 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1785             }
1786         } else {
1787             // Just interpret as a reverse geocode
1788             $oReverse = new ReverseGeocode($this->oDB);
1789             $oReverse->setZoom(18);
1790
1791             $aLookup = $oReverse->lookup(
1792                 $oNearPoint->lat(),
1793                 $oNearPoint->lon(),
1794                 false
1795             );
1796
1797             if (CONST_Debug) var_dump("Reverse search", $aLookup);
1798
1799             if ($aLookup['place_id']) {
1800                 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1801                 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1802             } else {
1803                 $aSearchResults = array();
1804             }
1805         }
1806
1807         // No results? Done
1808         if (!sizeof($aSearchResults)) {
1809             if ($this->bFallback) {
1810                 if ($this->fallbackStructuredQuery()) {
1811                     return $this->lookup();
1812                 }
1813             }
1814
1815             return array();
1816         }
1817
1818         $aClassType = getClassTypesWithImportance();
1819         $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1820         foreach ($aRecheckWords as $i => $sWord) {
1821             if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1822         }
1823
1824         if (CONST_Debug) {
1825             echo '<i>Recheck words:<\i>';
1826             var_dump($aRecheckWords);
1827         }
1828
1829         $oPlaceLookup = new PlaceLookup($this->oDB);
1830         $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1831         $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1832         $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1833         $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1834         $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1835         $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1836
1837         foreach ($aSearchResults as $iResNum => $aResult) {
1838             // Default
1839             $fDiameter = getResultDiameter($aResult);
1840
1841             $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1842             if ($aOutlineResult) {
1843                 $aResult = array_merge($aResult, $aOutlineResult);
1844             }
1845             
1846             if ($aResult['extra_place'] == 'city') {
1847                 $aResult['class'] = 'place';
1848                 $aResult['type'] = 'city';
1849                 $aResult['rank_search'] = 16;
1850             }
1851
1852             // Is there an icon set for this type of result?
1853             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1854                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1855             ) {
1856                 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1857             }
1858
1859             if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1860                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1861             ) {
1862                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1863             } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1864                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1865             ) {
1866                 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1867             }
1868             // if tag '&addressdetails=1' is set in query
1869             if ($this->bIncludeAddressDetails) {
1870                 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1871                 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1872                 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1873                     $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1874                 }
1875             }
1876
1877             if ($this->bIncludeExtraTags) {
1878                 if ($aResult['extra']) {
1879                     $aResult['sExtraTags'] = json_decode($aResult['extra']);
1880                 } else {
1881                     $aResult['sExtraTags'] = (object) array();
1882                 }
1883             }
1884
1885             if ($this->bIncludeNameDetails) {
1886                 if ($aResult['names']) {
1887                     $aResult['sNameDetails'] = json_decode($aResult['names']);
1888                 } else {
1889                     $aResult['sNameDetails'] = (object) array();
1890                 }
1891             }
1892
1893             // Adjust importance for the number of exact string matches in the result
1894             $aResult['importance'] = max(0.001, $aResult['importance']);
1895             $iCountWords = 0;
1896             $sAddress = $aResult['langaddress'];
1897             foreach ($aRecheckWords as $i => $sWord) {
1898                 if (stripos($sAddress, $sWord)!==false) {
1899                     $iCountWords++;
1900                     if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1901                 }
1902             }
1903
1904             $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
1905
1906             $aResult['name'] = $aResult['langaddress'];
1907             // secondary ordering (for results with same importance (the smaller the better):
1908             // - approximate importance of address parts
1909             $aResult['foundorder'] = -$aResult['addressimportance']/10;
1910             // - number of exact matches from the query
1911             if (isset($this->exactMatchCache[$aResult['place_id']])) {
1912                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1913             } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1914                 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1915             }
1916             // - importance of the class/type
1917             if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1918                 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1919             ) {
1920                 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1921             } else {
1922                 $aResult['foundorder'] += 0.01;
1923             }
1924             if (CONST_Debug) var_dump($aResult);
1925             $aSearchResults[$iResNum] = $aResult;
1926         }
1927         uasort($aSearchResults, 'byImportance');
1928
1929         $aOSMIDDone = array();
1930         $aClassTypeNameDone = array();
1931         $aToFilter = $aSearchResults;
1932         $aSearchResults = array();
1933
1934         $bFirst = true;
1935         foreach ($aToFilter as $iResNum => $aResult) {
1936             $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1937             if ($bFirst) {
1938                 $fLat = $aResult['lat'];
1939                 $fLon = $aResult['lon'];
1940                 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1941                 $bFirst = false;
1942             }
1943             if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1944                 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1945             ) {
1946                 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1947                 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1948                 $aSearchResults[] = $aResult;
1949             }
1950
1951             // Absolute limit on number of results
1952             if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1953         }
1954
1955         return $aSearchResults;
1956     } // end lookup()
1957 } // end class