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