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