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