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