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