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