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