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