]> 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                         // Hack to make it handle "new york, ny" (and variants) correctly
489                         //$sQuery = str_ireplace(array('New York, ny','new york, new york', 'New York ny','new york new york'), 'new york city, ny', $this->sQuery);
490                         $sQuery = $this->sQuery;
491
492                         // Conflicts between US state abreviations and various words for 'the' in different languages
493                         if (isset($this->aLangPrefOrder['name:en']))
494                         {
495                                 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/','\1illinois\2', $sQuery);
496                                 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/','\1alabama\2', $sQuery);
497                                 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/','\1louisiana\2', $sQuery);
498                         }
499
500                         // View Box SQL
501                         $sViewboxCentreSQL;
502                         $bBoundingBoxSearch = false;
503                         if ($this->aViewBox)
504                         {
505                                 $fHeight = $this->aViewBox[0]-$this->aViewBox[2];
506                                 $fWidth = $this->aViewBox[1]-$this->aViewBox[3];
507                                 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
508                                 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
509                                 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
510                                 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
511
512                                 $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)";
513                                 $this->sViewboxLargeSQL = "ST_SetSRID(ST_MakeBox2D(ST_Point(".(float)$aBigViewBox[0].",".(float)$aBigViewBox[1]."),ST_Point(".(float)$aBigViewBox[2].",".(float)$aBigViewBox[3].")),4326)";
514                                 $bBoundingBoxSearch = $this->bBoundedSearch;
515                         }
516
517                         // Route SQL
518                         if ($this->aRoutePoints)
519                         {
520                                 $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
521                                 $bFirst = true;
522                                 foreach($this->aRoutePoints as $aPoint)
523                                 {
524                                         if (!$bFirst) $sViewboxCentreSQL .= ",";
525                                         $sViewboxCentreSQL .= $aPoint[1].' '.$aPoint[0];
526                                         $bFirst = false;
527                                 }
528                                 $sViewboxCentreSQL .= ")'::geometry,4326)";
529
530                                 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/69).")";
531                                 $this->sViewboxSmallSQL = $this->oDB->getOne($sSQL);
532                                 if (PEAR::isError($this->sViewboxSmallSQL))
533                                 {
534                                         failInternalError("Could not get small viewbox.", $sSQL, $this->sViewboxSmallSQL);
535                                 }
536                                 $this->sViewboxSmallSQL = "'".$this->sViewboxSmallSQL."'::geometry";
537
538                                 $sSQL = "select st_buffer(".$sViewboxCentreSQL.",".(float)($_GET['routewidth']/30).")";
539                                 $this->sViewboxLargeSQL = $this->oDB->getOne($sSQL);
540                                 if (PEAR::isError($this->sViewboxLargeSQL))
541                                 {
542                                         failInternalError("Could not get large viewbox.", $sSQL, $this->sViewboxLargeSQL);
543                                 }
544                                 $this->sViewboxLargeSQL = "'".$this->sViewboxLargeSQL."'::geometry";
545                                 $bBoundingBoxSearch = $this->bBoundedSearch;
546                         }
547
548                         // Do we have anything that looks like a lat/lon pair?
549                         if (preg_match('/\\b([NS])[ ]+([0-9]+[0-9.]*)[ ]+([0-9.]+)?[, ]+([EW])[ ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?\\b/', $sQuery, $aData))
550                         {
551                                 $fQueryLat = ($aData[1]=='N'?1:-1) * ($aData[2] + $aData[3]/60);
552                                 $fQueryLon = ($aData[4]=='E'?1:-1) * ($aData[5] + $aData[6]/60);
553                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
554                                 {
555                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
556                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
557                                 }
558                         }
559                         elseif (preg_match('/\\b([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([NS])[, ]+([0-9]+)[ ]+([0-9]+[0-9.]*)?[ ]+([EW])\\b/', $sQuery, $aData))
560                         {
561                                 $fQueryLat = ($aData[3]=='N'?1:-1) * ($aData[1] + $aData[2]/60);
562                                 $fQueryLon = ($aData[6]=='E'?1:-1) * ($aData[4] + $aData[5]/60);
563                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
564                                 {
565                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
566                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
567                                 }
568                         }
569                         elseif (preg_match('/(\\[|^|\\b)(-?[0-9]+[0-9]*\\.[0-9]+)[, ]+(-?[0-9]+[0-9]*\\.[0-9]+)(\\]|$|\\b)/', $sQuery, $aData))
570                         {
571                                 $fQueryLat = $aData[2];
572                                 $fQueryLon = $aData[3];
573                                 if ($fQueryLat <= 90.1 && $fQueryLat >= -90.1 && $fQueryLon <= 180.1 && $fQueryLon >= -180.1)
574                                 {
575                                         $this->setNearPoint(array($fQueryLat, $fQueryLon));
576                                         $sQuery = trim(str_replace($aData[0], ' ', $sQuery));
577                                 }
578                         }
579
580                         $aSearchResults = array();
581                         if ($sQuery || $this->aStructuredQuery)
582                         {
583                                 // Start with a blank search
584                                 $aSearches = array(
585                                         array('iSearchRank' => 0, 'iNamePhrase' => -1, 'sCountryCode' => false, 'aName'=>array(), 'aAddress'=>array(), 'aFullNameAddress'=>array(),
586                                               'aNameNonSearch'=>array(), 'aAddressNonSearch'=>array(),
587                                               'sOperator'=>'', 'aFeatureName' => array(), 'sClass'=>'', 'sType'=>'', 'sHouseNumber'=>'', 'fLat'=>'', 'fLon'=>'', 'fRadius'=>'')
588                                 );
589
590                                 // Do we have a radius search?
591                                 $sNearPointSQL = false;
592                                 if ($this->aNearPoint)
593                                 {
594                                         $sNearPointSQL = "ST_SetSRID(ST_Point(".(float)$this->aNearPoint[1].",".(float)$this->aNearPoint[0]."),4326)";
595                                         $aSearches[0]['fLat'] = (float)$this->aNearPoint[0];
596                                         $aSearches[0]['fLon'] = (float)$this->aNearPoint[1];
597                                         $aSearches[0]['fRadius'] = (float)$this->aNearPoint[2];
598                                 }
599
600                                 // Any 'special' terms in the search?
601                                 $bSpecialTerms = false;
602                                 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
603                                 $aSpecialTerms = array();
604                                 foreach($aSpecialTermsRaw as $aSpecialTerm)
605                                 {
606                                         $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
607                                         $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
608                                 }
609
610                                 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
611                                 $aSpecialTerms = array();
612                                 if (isset($aStructuredQuery['amenity']) && $aStructuredQuery['amenity'])
613                                 {
614                                         $aSpecialTermsRaw[] = array('['.$aStructuredQuery['amenity'].']', $aStructuredQuery['amenity']);
615                                         unset($aStructuredQuery['amenity']);
616                                 }
617                                 foreach($aSpecialTermsRaw as $aSpecialTerm)
618                                 {
619                                         $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
620                                         $sToken = $this->oDB->getOne("select make_standard_name('".$aSpecialTerm[1]."') as string");
621                                         $sSQL = 'select * from (select word_id,word_token, word, class, type, country_code, operator';
622                                         $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';
623                                         if (CONST_Debug) var_Dump($sSQL);
624                                         $aSearchWords = $this->oDB->getAll($sSQL);
625                                         $aNewSearches = array();
626                                         foreach($aSearches as $aSearch)
627                                         {
628                                                 foreach($aSearchWords as $aSearchTerm)
629                                                 {
630                                                         $aNewSearch = $aSearch;
631                                                         if ($aSearchTerm['country_code'])
632                                                         {
633                                                                 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
634                                                                 $aNewSearches[] = $aNewSearch;
635                                                                 $bSpecialTerms = true;
636                                                         }
637                                                         if ($aSearchTerm['class'])
638                                                         {
639                                                                 $aNewSearch['sClass'] = $aSearchTerm['class'];
640                                                                 $aNewSearch['sType'] = $aSearchTerm['type'];
641                                                                 $aNewSearches[] = $aNewSearch;
642                                                                 $bSpecialTerms = true;
643                                                         }
644                                                 }
645                                         }
646                                         $aSearches = $aNewSearches;
647                                 }
648
649                                 // Split query into phrases
650                                 // Commas are used to reduce the search space by indicating where phrases split
651                                 if ($this->aStructuredQuery)
652                                 {
653                                         $aPhrases = $this->aStructuredQuery;
654                                         $bStructuredPhrases = true;
655                                 }
656                                 else
657                                 {
658                                         $aPhrases = explode(',',$sQuery);
659                                         $bStructuredPhrases = false;
660                                 }
661
662                                 // Convert each phrase to standard form
663                                 // Create a list of standard words
664                                 // Get all 'sets' of words
665                                 // Generate a complete list of all
666                                 $aTokens = array();
667                                 foreach($aPhrases as $iPhrase => $sPhrase)
668                                 {
669                                         $aPhrase = $this->oDB->getRow("select make_standard_name('".pg_escape_string($sPhrase)."') as string");
670                                         if (PEAR::isError($aPhrase))
671                                         {
672                                                 userError("Illegal query string (not an UTF-8 string): ".$sPhrase);
673                                                 if (CONST_Debug) var_dump($aPhrase);
674                                                 exit;
675                                         }
676                                         if (trim($aPhrase['string']))
677                                         {
678                                                 $aPhrases[$iPhrase] = $aPhrase;
679                                                 $aPhrases[$iPhrase]['words'] = explode(' ',$aPhrases[$iPhrase]['string']);
680                                                 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
681                                                 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
682                                         }
683                                         else
684                                         {
685                                                 unset($aPhrases[$iPhrase]);
686                                         }
687                                 }
688
689                                 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
690                                 $aPhraseTypes = array_keys($aPhrases);
691                                 $aPhrases = array_values($aPhrases);
692
693                                 if (sizeof($aTokens))
694                                 {
695                                         // Check which tokens we have, get the ID numbers
696                                         $sSQL = 'select word_id,word_token, word, class, type, country_code, operator, search_name_count';
697                                         $sSQL .= ' from word where word_token in ('.join(',',array_map("getDBQuoted",$aTokens)).')';
698
699                                         if (CONST_Debug) var_Dump($sSQL);
700
701                                         $aValidTokens = array();
702                                         if (sizeof($aTokens)) $aDatabaseWords = $this->oDB->getAll($sSQL);
703                                         else $aDatabaseWords = array();
704                                         if (PEAR::IsError($aDatabaseWords))
705                                         {
706                                                 failInternalError("Could not get word tokens.", $sSQL, $aDatabaseWords);
707                                         }
708                                         $aPossibleMainWordIDs = array();
709                                         $aWordFrequencyScores = array();
710                                         foreach($aDatabaseWords as $aToken)
711                                         {
712                                                 // Very special case - require 2 letter country param to match the country code found
713                                                 if ($bStructuredPhrases && $aToken['country_code'] && !empty($aStructuredQuery['country'])
714                                                                 && strlen($aStructuredQuery['country']) == 2 && strtolower($aStructuredQuery['country']) != $aToken['country_code'])
715                                                 {
716                                                         continue;
717                                                 }
718
719                                                 if (isset($aValidTokens[$aToken['word_token']]))
720                                                 {
721                                                         $aValidTokens[$aToken['word_token']][] = $aToken;
722                                                 }
723                                                 else
724                                                 {
725                                                         $aValidTokens[$aToken['word_token']] = array($aToken);
726                                                 }
727                                                 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
728                                                 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
729                                         }
730                                         if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
731
732                                         // Try and calculate GB postcodes we might be missing
733                                         foreach($aTokens as $sToken)
734                                         {
735                                                 // Source of gb postcodes is now definitive - always use
736                                                 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData))
737                                                 {
738                                                         if (substr($aData[1],-2,1) != ' ')
739                                                         {
740                                                                 $aData[0] = substr($aData[0],0,strlen($aData[1]-1)).' '.substr($aData[0],strlen($aData[1]-1));
741                                                                 $aData[1] = substr($aData[1],0,-1).' '.substr($aData[1],-1,1);
742                                                         }
743                                                         $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
744                                                         if ($aGBPostcodeLocation)
745                                                         {
746                                                                 $aValidTokens[$sToken] = $aGBPostcodeLocation;
747                                                         }
748                                                 }
749                                                 // US ZIP+4 codes - if there is no token,
750                                                 //      merge in the 5-digit ZIP code
751                                                 else if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData))
752                                                 {
753                                                         if (isset($aValidTokens[$aData[1]]))
754                                                         {
755                                                                 foreach($aValidTokens[$aData[1]] as $aToken)
756                                                                 {
757                                                                         if (!$aToken['class'])
758                                                                         {
759                                                                                 if (isset($aValidTokens[$sToken]))
760                                                                                 {
761                                                                                         $aValidTokens[$sToken][] = $aToken;
762                                                                                 }
763                                                                                 else
764                                                                                 {
765                                                                                         $aValidTokens[$sToken] = array($aToken);
766                                                                                 }
767                                                                         }
768                                                                 }
769                                                         }
770                                                 }
771                                         }
772
773                                         foreach($aTokens as $sToken)
774                                         {
775                                                 // Unknown single word token with a number - assume it is a house number
776                                                 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken,' ') === false && preg_match('/[0-9]/', $sToken))
777                                                 {
778                                                         $aValidTokens[' '.$sToken] = array(array('class'=>'place','type'=>'house'));
779                                                 }
780                                         }
781
782                                         // Any words that have failed completely?
783                                         // TODO: suggestions
784
785                                         // Start the search process
786                                         $aResultPlaceIDs = array();
787
788                                         /*
789                                            Calculate all searches using aValidTokens i.e.
790                                            'Wodsworth Road, Sheffield' =>
791
792                                            Phrase Wordset
793                                            0      0       (wodsworth road)
794                                            0      1       (wodsworth)(road)
795                                            1      0       (sheffield)
796
797                                            Score how good the search is so they can be ordered
798                                          */
799                                         foreach($aPhrases as $iPhrase => $sPhrase)
800                                         {
801                                                 $aNewPhraseSearches = array();
802                                                 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
803                                                 else $sPhraseType = '';
804
805                                                 foreach($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset)
806                                                 {
807                                                         // Too many permutations - too expensive
808                                                         if ($iWordSet > 120) break;
809
810                                                         $aWordsetSearches = $aSearches;
811
812                                                         // Add all words from this wordset
813                                                         foreach($aWordset as $iToken => $sToken)
814                                                         {
815                                                                 //echo "<br><b>$sToken</b>";
816                                                                 $aNewWordsetSearches = array();
817
818                                                                 foreach($aWordsetSearches as $aCurrentSearch)
819                                                                 {
820                                                                         //echo "<i>";
821                                                                         //var_dump($aCurrentSearch);
822                                                                         //echo "</i>";
823
824                                                                         // If the token is valid
825                                                                         if (isset($aValidTokens[' '.$sToken]))
826                                                                         {
827                                                                                 foreach($aValidTokens[' '.$sToken] as $aSearchTerm)
828                                                                                 {
829                                                                                         $aSearch = $aCurrentSearch;
830                                                                                         $aSearch['iSearchRank']++;
831                                                                                         if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0')
832                                                                                         {
833                                                                                                 if ($aSearch['sCountryCode'] === false)
834                                                                                                 {
835                                                                                                         $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
836                                                                                                         // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
837                                                                                                         // If reverse order is enabled, it may appear at the beginning as well.
838                                                                                                         if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases)) &&
839                                                                                                                         (!$this->bReverseInPlan || $iToken > 0 || $iPhrase > 0))
840                                                                                                         {
841                                                                                                                 $aSearch['iSearchRank'] += 5;
842                                                                                                         }
843                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
844                                                                                                 }
845                                                                                         }
846                                                                                         elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null)
847                                                                                         {
848                                                                                                 if ($aSearch['fLat'] === '')
849                                                                                                 {
850                                                                                                         $aSearch['fLat'] = $aSearchTerm['lat'];
851                                                                                                         $aSearch['fLon'] = $aSearchTerm['lon'];
852                                                                                                         $aSearch['fRadius'] = $aSearchTerm['radius'];
853                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
854                                                                                                 }
855                                                                                         }
856                                                                                         elseif ($sPhraseType == 'postalcode')
857                                                                                         {
858                                                                                                 // 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
859                                                                                                 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
860                                                                                                 {
861                                                                                                         // If we already have a name try putting the postcode first
862                                                                                                         if (sizeof($aSearch['aName']))
863                                                                                                         {
864                                                                                                                 $aNewSearch = $aSearch;
865                                                                                                                 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
866                                                                                                                 $aNewSearch['aName'] = array();
867                                                                                                                 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
868                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
869                                                                                                         }
870
871                                                                                                         if (sizeof($aSearch['aName']))
872                                                                                                         {
873                                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
874                                                                                                                 {
875                                                                                                                         $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
876                                                                                                                 }
877                                                                                                                 else
878                                                                                                                 {
879                                                                                                                         $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
880                                                                                                                         $aSearch['iSearchRank'] += 1000; // skip;
881                                                                                                                 }
882                                                                                                         }
883                                                                                                         else
884                                                                                                         {
885                                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
886                                                                                                                 //$aSearch['iNamePhrase'] = $iPhrase;
887                                                                                                         }
888                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
889                                                                                                 }
890
891                                                                                         }
892                                                                                         elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house')
893                                                                                         {
894                                                                                                 if ($aSearch['sHouseNumber'] === '')
895                                                                                                 {
896                                                                                                         $aSearch['sHouseNumber'] = $sToken;
897                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
898                                                                                                         /*
899                                                                                                         // Fall back to not searching for this item (better than nothing)
900                                                                                                         $aSearch = $aCurrentSearch;
901                                                                                                         $aSearch['iSearchRank'] += 1;
902                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
903                                                                                                          */
904                                                                                                 }
905                                                                                         }
906                                                                                         elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null)
907                                                                                         {
908                                                                                                 if ($aSearch['sClass'] === '')
909                                                                                                 {
910                                                                                                         $aSearch['sOperator'] = $aSearchTerm['operator'];
911                                                                                                         $aSearch['sClass'] = $aSearchTerm['class'];
912                                                                                                         $aSearch['sType'] = $aSearchTerm['type'];
913                                                                                                         if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
914                                                                                                         else $aSearch['sOperator'] = 'near'; // near = in for the moment
915                                                                                                         if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
916
917                                                                                                         // Do we have a shortcut id?
918                                                                                                         if ($aSearch['sOperator'] == 'name')
919                                                                                                         {
920                                                                                                                 $sSQL = "select get_tagpair('".$aSearch['sClass']."', '".$aSearch['sType']."')";
921                                                                                                                 if ($iAmenityID = $this->oDB->getOne($sSQL))
922                                                                                                                 {
923                                                                                                                         $aValidTokens[$aSearch['sClass'].':'.$aSearch['sType']] = array('word_id' => $iAmenityID);
924                                                                                                                         $aSearch['aName'][$iAmenityID] = $iAmenityID;
925                                                                                                                         $aSearch['sClass'] = '';
926                                                                                                                         $aSearch['sType'] = '';
927                                                                                                                 }
928                                                                                                         }
929                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
930                                                                                                 }
931                                                                                         }
932                                                                                         elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
933                                                                                         {
934                                                                                                 if (sizeof($aSearch['aName']))
935                                                                                                 {
936                                                                                                         if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strlen($sToken) < 4 || strpos($sToken, ' ') !== false))
937                                                                                                         {
938                                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
939                                                                                                         }
940                                                                                                         else
941                                                                                                         {
942                                                                                                                 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
943                                                                                                                 $aSearch['iSearchRank'] += 1000; // skip;
944                                                                                                         }
945                                                                                                 }
946                                                                                                 else
947                                                                                                 {
948                                                                                                         $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
949                                                                                                         //$aSearch['iNamePhrase'] = $iPhrase;
950                                                                                                 }
951                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
952                                                                                         }
953                                                                                 }
954                                                                         }
955                                                                         if (isset($aValidTokens[$sToken]))
956                                                                         {
957                                                                                 // Allow searching for a word - but at extra cost
958                                                                                 foreach($aValidTokens[$sToken] as $aSearchTerm)
959                                                                                 {
960                                                                                         if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])
961                                                                                         {
962                                                                                                 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strlen($sToken) >= 4)
963                                                                                                 {
964                                                                                                         $aSearch = $aCurrentSearch;
965                                                                                                         $aSearch['iSearchRank'] += 1;
966                                                                                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
967                                                                                                         {
968                                                                                                                 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
969                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
970                                                                                                         }
971                                                                                                         elseif (isset($aValidTokens[' '.$sToken])) // revert to the token version?
972                                                                                                         {
973                                                                                                                 foreach($aValidTokens[' '.$sToken] as $aSearchTermToken)
974                                                                                                                 {
975                                                                                                                         if (empty($aSearchTermToken['country_code'])
976                                                                                                                                         && empty($aSearchTermToken['lat'])
977                                                                                                                                         && empty($aSearchTermToken['class']))
978                                                                                                                         {
979                                                                                                                                 $aSearch = $aCurrentSearch;
980                                                                                                                                 $aSearch['iSearchRank'] += 1;
981                                                                                                                                 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
982                                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
983                                                                                                                         }
984                                                                                                                 }
985                                                                                                         }
986                                                                                                         else
987                                                                                                         {
988                                                                                                                 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
989                                                                                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
990                                                                                                         }
991                                                                                                 }
992
993                                                                                                 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)
994                                                                                                 {
995                                                                                                         $aSearch = $aCurrentSearch;
996                                                                                                         $aSearch['iSearchRank'] += 2;
997                                                                                                         if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
998                                                                                                         if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency)
999                                                                                                                 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
1000                                                                                                         else
1001                                                                                                                 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
1002                                                                                                         $aSearch['iNamePhrase'] = $iPhrase;
1003                                                                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
1004                                                                                                 }
1005                                                                                         }
1006                                                                                 }
1007                                                                         }
1008                                                                         else
1009                                                                         {
1010                                                                                 // Allow skipping a word - but at EXTREAM cost
1011                                                                                 //$aSearch = $aCurrentSearch;
1012                                                                                 //$aSearch['iSearchRank']+=100;
1013                                                                                 //$aNewWordsetSearches[] = $aSearch;
1014                                                                         }
1015                                                                 }
1016                                                                 // Sort and cut
1017                                                                 usort($aNewWordsetSearches, 'bySearchRank');
1018                                                                 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
1019                                                         }
1020                                                         //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
1021
1022                                                         $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
1023                                                         usort($aNewPhraseSearches, 'bySearchRank');
1024
1025                                                         $aSearchHash = array();
1026                                                         foreach($aNewPhraseSearches as $iSearch => $aSearch)
1027                                                         {
1028                                                                 $sHash = serialize($aSearch);
1029                                                                 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
1030                                                                 else $aSearchHash[$sHash] = 1;
1031                                                         }
1032
1033                                                         $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
1034                                                 }
1035
1036                                                 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1037                                                 $aGroupedSearches = array();
1038                                                 foreach($aNewPhraseSearches as $aSearch)
1039                                                 {
1040                                                         if ($aSearch['iSearchRank'] < $this->iMaxRank)
1041                                                         {
1042                                                                 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1043                                                                 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1044                                                         }
1045                                                 }
1046                                                 ksort($aGroupedSearches);
1047
1048                                                 $iSearchCount = 0;
1049                                                 $aSearches = array();
1050                                                 foreach($aGroupedSearches as $iScore => $aNewSearches)
1051                                                 {
1052                                                         $iSearchCount += sizeof($aNewSearches);
1053                                                         $aSearches = array_merge($aSearches, $aNewSearches);
1054                                                         if ($iSearchCount > 50) break;
1055                                                 }
1056
1057                                                 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1058
1059                                         }
1060
1061                                 }
1062                                 else
1063                                 {
1064                                         // Re-group the searches by their score, junk anything over 20 as just not worth trying
1065                                         $aGroupedSearches = array();
1066                                         foreach($aSearches as $aSearch)
1067                                         {
1068                                                 if ($aSearch['iSearchRank'] < $this->iMaxRank)
1069                                                 {
1070                                                         if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1071                                                         $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1072                                                 }
1073                                         }
1074                                         ksort($aGroupedSearches);
1075                                 }
1076
1077                                 if (CONST_Debug) var_Dump($aGroupedSearches);
1078
1079                                 if ($this->bReverseInPlan)
1080                                 {
1081                                         $aCopyGroupedSearches = $aGroupedSearches;
1082                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1083                                         {
1084                                                 foreach($aSearches as $iSearch => $aSearch)
1085                                                 {
1086                                                         if (sizeof($aSearch['aAddress']))
1087                                                         {
1088                                                                 $iReverseItem = array_pop($aSearch['aAddress']);
1089                                                                 if (isset($aPossibleMainWordIDs[$iReverseItem]))
1090                                                                 {
1091                                                                         $aSearch['aAddress'] = array_merge($aSearch['aAddress'], $aSearch['aName']);
1092                                                                         $aSearch['aName'] = array($iReverseItem);
1093                                                                         $aGroupedSearches[$iGroup][] = $aSearch;
1094                                                                 }
1095                                                                 //$aReverseSearch['aName'][$iReverseItem] = $iReverseItem;
1096                                                                 //$aGroupedSearches[$iGroup][] = $aReverseSearch;
1097                                                         }
1098                                                 }
1099                                         }
1100                                 }
1101
1102                                 if (CONST_Search_TryDroppedAddressTerms && sizeof($aStructuredQuery) > 0)
1103                                 {
1104                                         $aCopyGroupedSearches = $aGroupedSearches;
1105                                         foreach($aCopyGroupedSearches as $iGroup => $aSearches)
1106                                         {
1107                                                 foreach($aSearches as $iSearch => $aSearch)
1108                                                 {
1109                                                         $aReductionsList = array($aSearch['aAddress']);
1110                                                         $iSearchRank = $aSearch['iSearchRank'];
1111                                                         while(sizeof($aReductionsList) > 0)
1112                                                         {
1113                                                                 $iSearchRank += 5;
1114                                                                 if ($iSearchRank > iMaxRank) break 3;
1115                                                                 $aNewReductionsList = array();
1116                                                                 foreach($aReductionsList as $aReductionsWordList)
1117                                                                 {
1118                                                                         for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++)
1119                                                                         {
1120                                                                                 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1121                                                                                 $aReverseSearch = $aSearch;
1122                                                                                 $aSearch['aAddress'] = $aReductionsWordListResult;
1123                                                                                 $aSearch['iSearchRank'] = $iSearchRank;
1124                                                                                 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1125                                                                                 if (sizeof($aReductionsWordListResult) > 0)
1126                                                                                 {
1127                                                                                         $aNewReductionsList[] = $aReductionsWordListResult;
1128                                                                                 }
1129                                                                         }
1130                                                                 }
1131                                                                 $aReductionsList = $aNewReductionsList;
1132                                                         }
1133                                                 }
1134                                         }
1135                                         ksort($aGroupedSearches);
1136                                 }
1137
1138                                 // Filter out duplicate searches
1139                                 $aSearchHash = array();
1140                                 foreach($aGroupedSearches as $iGroup => $aSearches)
1141                                 {
1142                                         foreach($aSearches as $iSearch => $aSearch)
1143                                         {
1144                                                 $sHash = serialize($aSearch);
1145                                                 if (isset($aSearchHash[$sHash]))
1146                                                 {
1147                                                         unset($aGroupedSearches[$iGroup][$iSearch]);
1148                                                         if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1149                                                 }
1150                                                 else
1151                                                 {
1152                                                         $aSearchHash[$sHash] = 1;
1153                                                 }
1154                                         }
1155                                 }
1156
1157                                 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1158
1159                                 $iGroupLoop = 0;
1160                                 $iQueryLoop = 0;
1161                                 foreach($aGroupedSearches as $iGroupedRank => $aSearches)
1162                                 {
1163                                         $iGroupLoop++;
1164                                         foreach($aSearches as $aSearch)
1165                                         {
1166                                                 $iQueryLoop++;
1167
1168                                                 if (CONST_Debug) { echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>"; }
1169                                                 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1170
1171                                                 // No location term?
1172                                                 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon'])
1173                                                 {
1174                                                         if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber'])
1175                                                         {
1176                                                                 // Just looking for a country by code - look it up
1177                                                                 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank)
1178                                                                 {
1179                                                                         $sSQL = "select place_id from placex where calculated_country_code='".$aSearch['sCountryCode']."' and rank_search = 4";
1180                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1181                                                                         $sSQL .= " order by st_area(geometry) desc limit 1";
1182                                                                         if (CONST_Debug) var_dump($sSQL);
1183                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
1184                                                                 }
1185                                                         }
1186                                                         else
1187                                                         {
1188                                                                 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1189                                                                 if (!$aSearch['sClass']) continue;
1190                                                                 $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1191                                                                 if ($this->oDB->getOne($sSQL))
1192                                                                 {
1193                                                                         $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1194                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1195                                                                         $sSQL .= " where st_contains($this->sViewboxSmallSQL, ct.centroid)";
1196                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1197                                                                         if (sizeof($this->aExcludePlaceIDs))
1198                                                                         {
1199                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1200                                                                         }
1201                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1202                                                                         $sSQL .= " limit $this->iLimit";
1203                                                                         if (CONST_Debug) var_dump($sSQL);
1204                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
1205
1206                                                                         // If excluded place IDs are given, it is fair to assume that
1207                                                                         // there have been results in the small box, so no further
1208                                                                         // expansion in that case.
1209                                                                         if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs))
1210                                                                         {
1211                                                                                 $sSQL = "select place_id from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1212                                                                                 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1213                                                                                 $sSQL .= " where st_contains($this->sViewboxLargeSQL, ct.centroid)";
1214                                                                                 if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1215                                                                                 if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, ct.centroid) asc";
1216                                                                                 $sSQL .= " limit $this->iLimit";
1217                                                                                 if (CONST_Debug) var_dump($sSQL);
1218                                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
1219                                                                         }
1220                                                                 }
1221                                                                 else
1222                                                                 {
1223                                                                         $sSQL = "select place_id from placex where class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1224                                                                         $sSQL .= " and st_contains($this->sViewboxSmallSQL, geometry) and linked_place_id is null";
1225                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1226                                                                         if ($sViewboxCentreSQL) $sSQL .= " order by st_distance($sViewboxCentreSQL, centroid) asc";
1227                                                                         $sSQL .= " limit $this->iLimit";
1228                                                                         if (CONST_Debug) var_dump($sSQL);
1229                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
1230                                                                 }
1231                                                         }
1232                                                 }
1233                                                 else
1234                                                 {
1235                                                         $aPlaceIDs = array();
1236
1237                                                         // First we need a position, either aName or fLat or both
1238                                                         $aTerms = array();
1239                                                         $aOrder = array();
1240
1241                                                         // TODO: filter out the pointless search terms (2 letter name tokens and less)
1242                                                         // they might be right - but they are just too darned expensive to run
1243                                                         if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'],",")."]";
1244                                                         //if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'],",")."]";
1245                                                         if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress'])
1246                                                         {
1247                                                                 // For infrequent name terms disable index usage for address
1248                                                                 if (CONST_Search_NameOnlySearchFrequencyThreshold &&
1249                                                                                 sizeof($aSearch['aName']) == 1 &&
1250                                                                                 $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold)
1251                                                                 {
1252                                                                         //$aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'],$aSearch['aAddressNonSearch']),",")."]";
1253                                                                         $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddress'],",")."]";
1254                                                                 }
1255                                                                 else
1256                                                                 {
1257                                                                         $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'],",")."]";
1258                                                                         //if (sizeof($aSearch['aAddressNonSearch'])) $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'],",")."]";
1259                                                                 }
1260                                                         }
1261                                                         if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1262                                                         if ($aSearch['sHouseNumber']) $aTerms[] = "address_rank between 16 and 27";
1263                                                         if ($aSearch['fLon'] && $aSearch['fLat'])
1264                                                         {
1265                                                                 $aTerms[] = "ST_DWithin(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326), ".$aSearch['fRadius'].")";
1266                                                                 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1267                                                         }
1268                                                         if (sizeof($this->aExcludePlaceIDs))
1269                                                         {
1270                                                                 $aTerms[] = "place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1271                                                         }
1272                                                         if ($sCountryCodesSQL)
1273                                                         {
1274                                                                 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1275                                                         }
1276
1277                                                         if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1278                                                         if ($sNearPointSQL) $aOrder[] = "ST_Distance($sNearPointSQL, centroid) asc";
1279
1280                                                         if ($aSearch['sHouseNumber'])
1281                                                         {
1282                                                                 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1283                                                         }
1284                                                         else
1285                                                         {
1286                                                                 $sImportanceSQL = '(case when importance = 0 OR importance IS NULL then 0.75-(search_rank::float/40) else importance end)';
1287                                                         }
1288                                                         if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1289                                                         if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * case when ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1290
1291                                                         $aOrder[] = "$sImportanceSQL DESC";
1292                                                         if (sizeof($aSearch['aFullNameAddress']))
1293                                                         {
1294                                                                 $sExactMatchSQL = '(select count(*) from (select unnest(ARRAY['.join($aSearch['aFullNameAddress'],",").']) INTERSECT select unnest(nameaddress_vector))s) as exactmatch';
1295                                                                 $aOrder[] = 'exactmatch DESC';
1296                                                         } else {
1297                                                                 $sExactMatchSQL = '0::int as exactmatch';
1298                                                         }
1299
1300                                                         if (sizeof($aTerms))
1301                                                         {
1302                                                                 $sSQL = "select place_id, ";
1303                                                                 $sSQL .= $sExactMatchSQL;
1304                                                                 $sSQL .= " from search_name";
1305                                                                 $sSQL .= " where ".join(' and ',$aTerms);
1306                                                                 $sSQL .= " order by ".join(', ',$aOrder);
1307                                                                 if ($aSearch['sHouseNumber'] || $aSearch['sClass'])
1308                                                                         $sSQL .= " limit 50";
1309                                                                 elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass'])
1310                                                                         $sSQL .= " limit 1";
1311                                                                 else
1312                                                                         $sSQL .= " limit ".$this->iLimit;
1313
1314                                                                 if (CONST_Debug) { var_dump($sSQL); }
1315                                                                 $aViewBoxPlaceIDs = $this->oDB->getAll($sSQL);
1316                                                                 if (PEAR::IsError($aViewBoxPlaceIDs))
1317                                                                 {
1318                                                                         failInternalError("Could not get places for search terms.", $sSQL, $aViewBoxPlaceIDs);
1319                                                                 }
1320                                                                 //var_dump($aViewBoxPlaceIDs);
1321                                                                 // Did we have an viewbox matches?
1322                                                                 $aPlaceIDs = array();
1323                                                                 $bViewBoxMatch = false;
1324                                                                 foreach($aViewBoxPlaceIDs as $aViewBoxRow)
1325                                                                 {
1326                                                                         //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1327                                                                         //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1328                                                                         //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1329                                                                         //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1330                                                                         $aPlaceIDs[] = $aViewBoxRow['place_id'];
1331                                                                         $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1332                                                                 }
1333                                                         }
1334                                                         //var_Dump($aPlaceIDs);
1335                                                         //exit;
1336
1337                                                         if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs))
1338                                                         {
1339                                                                 $aRoadPlaceIDs = $aPlaceIDs;
1340                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1341
1342                                                                 // Now they are indexed look for a house attached to a street we found
1343                                                                 $sHouseNumberRegex = '\\\\m'.str_replace(' ','[-,/ ]',$aSearch['sHouseNumber']).'\\\\M';
1344                                                                 $sSQL = "select place_id from placex where parent_place_id in (".$sPlaceIDs.") and housenumber ~* E'".$sHouseNumberRegex."'";
1345                                                                 if (sizeof($this->aExcludePlaceIDs))
1346                                                                 {
1347                                                                         $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1348                                                                 }
1349                                                                 $sSQL .= " limit $this->iLimit";
1350                                                                 if (CONST_Debug) var_dump($sSQL);
1351                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
1352
1353                                                                 // If not try the aux fallback table
1354                                                                 /*
1355                                                                 if (!sizeof($aPlaceIDs))
1356                                                                 {
1357                                                                         $sSQL = "select place_id from location_property_aux where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1358                                                                         if (sizeof($this->aExcludePlaceIDs))
1359                                                                         {
1360                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1361                                                                         }
1362                                                                         //$sSQL .= " limit $this->iLimit";
1363                                                                         if (CONST_Debug) var_dump($sSQL);
1364                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
1365                                                                 }
1366                                                                 */
1367
1368                                                                 if (!sizeof($aPlaceIDs))
1369                                                                 {
1370                                                                         $sSQL = "select place_id from location_property_tiger where parent_place_id in (".$sPlaceIDs.") and housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1371                                                                         if (sizeof($this->aExcludePlaceIDs))
1372                                                                         {
1373                                                                                 $sSQL .= " and place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1374                                                                         }
1375                                                                         //$sSQL .= " limit $this->iLimit";
1376                                                                         if (CONST_Debug) var_dump($sSQL);
1377                                                                         $aPlaceIDs = $this->oDB->getCol($sSQL);
1378                                                                 }
1379
1380                                                                 // Fallback to the road
1381                                                                 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber']))
1382                                                                 {
1383                                                                         $aPlaceIDs = $aRoadPlaceIDs;
1384                                                                 }
1385
1386                                                         }
1387
1388                                                         if ($aSearch['sClass'] && sizeof($aPlaceIDs))
1389                                                         {
1390                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1391                                                                 $aClassPlaceIDs = array();
1392
1393                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name')
1394                                                                 {
1395                                                                         // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1396                                                                         $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and class='".$aSearch['sClass']."' and type='".$aSearch['sType']."'";
1397                                                                         $sSQL .= " and linked_place_id is null";
1398                                                                         if ($sCountryCodesSQL) $sSQL .= " and calculated_country_code in ($sCountryCodesSQL)";
1399                                                                         $sSQL .= " order by rank_search asc limit $this->iLimit";
1400                                                                         if (CONST_Debug) var_dump($sSQL);
1401                                                                         $aClassPlaceIDs = $this->oDB->getCol($sSQL);
1402                                                                 }
1403
1404                                                                 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') // & in
1405                                                                 {
1406                                                                         $sSQL = "select count(*) from pg_tables where tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1407                                                                         $bCacheTable = $this->oDB->getOne($sSQL);
1408
1409                                                                         $sSQL = "select min(rank_search) from placex where place_id in ($sPlaceIDs)";
1410
1411                                                                         if (CONST_Debug) var_dump($sSQL);
1412                                                                         $this->iMaxRank = ((int)$this->oDB->getOne($sSQL));
1413
1414                                                                         // For state / country level searches the normal radius search doesn't work very well
1415                                                                         $sPlaceGeom = false;
1416                                                                         if ($this->iMaxRank < 9 && $bCacheTable)
1417                                                                         {
1418                                                                                 // Try and get a polygon to search in instead
1419                                                                                 $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";
1420                                                                                 if (CONST_Debug) var_dump($sSQL);
1421                                                                                 $sPlaceGeom = $this->oDB->getOne($sSQL);
1422                                                                         }
1423
1424                                                                         if ($sPlaceGeom)
1425                                                                         {
1426                                                                                 $sPlaceIDs = false;
1427                                                                         }
1428                                                                         else
1429                                                                         {
1430                                                                                 $this->iMaxRank += 5;
1431                                                                                 $sSQL = "select place_id from placex where place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1432                                                                                 if (CONST_Debug) var_dump($sSQL);
1433                                                                                 $aPlaceIDs = $this->oDB->getCol($sSQL);
1434                                                                                 $sPlaceIDs = join(',',$aPlaceIDs);
1435                                                                         }
1436
1437                                                                         if ($sPlaceIDs || $sPlaceGeom)
1438                                                                         {
1439
1440                                                                                 $fRange = 0.01;
1441                                                                                 if ($bCacheTable)
1442                                                                                 {
1443                                                                                         // More efficient - can make the range bigger
1444                                                                                         $fRange = 0.05;
1445
1446                                                                                         $sOrderBySQL = '';
1447                                                                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.centroid)";
1448                                                                                         else if ($sPlaceIDs) $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1449                                                                                         else if ($sPlaceGeom) $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1450
1451                                                                                         $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1452                                                                                         if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1453                                                                                         if ($sPlaceIDs)
1454                                                                                         {
1455                                                                                                 $sSQL .= ",placex as f where ";
1456                                                                                                 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1457                                                                                         }
1458                                                                                         if ($sPlaceGeom)
1459                                                                                         {
1460                                                                                                 $sSQL .= " where ";
1461                                                                                                 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1462                                                                                         }
1463                                                                                         if (sizeof($this->aExcludePlaceIDs))
1464                                                                                         {
1465                                                                                                 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1466                                                                                         }
1467                                                                                         if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1468                                                                                         if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1469                                                                                         if ($iOffset) $sSQL .= " offset $iOffset";
1470                                                                                         $sSQL .= " limit $this->iLimit";
1471                                                                                         if (CONST_Debug) var_dump($sSQL);
1472                                                                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1473                                                                                 }
1474                                                                                 else
1475                                                                                 {
1476                                                                                         if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1477
1478                                                                                         $sOrderBySQL = '';
1479                                                                                         if ($sNearPointSQL) $sOrderBySQL = "ST_Distance($sNearPointSQL, l.geometry)";
1480                                                                                         else $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1481
1482                                                                                         $sSQL = "select distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'')." from placex as l,placex as f where ";
1483                                                                                         $sSQL .= "f.place_id in ( $sPlaceIDs) and ST_DWithin(l.geometry, f.centroid, $fRange) ";
1484                                                                                         $sSQL .= "and l.class='".$aSearch['sClass']."' and l.type='".$aSearch['sType']."' ";
1485                                                                                         if (sizeof($this->aExcludePlaceIDs))
1486                                                                                         {
1487                                                                                                 $sSQL .= " and l.place_id not in (".join(',',$this->aExcludePlaceIDs).")";
1488                                                                                         }
1489                                                                                         if ($sCountryCodesSQL) $sSQL .= " and l.calculated_country_code in ($sCountryCodesSQL)";
1490                                                                                         if ($sOrderBy) $sSQL .= "order by ".$OrderBysSQL." asc";
1491                                                                                         if ($iOffset) $sSQL .= " offset $iOffset";
1492                                                                                         $sSQL .= " limit $this->iLimit";
1493                                                                                         if (CONST_Debug) var_dump($sSQL);
1494                                                                                         $aClassPlaceIDs = array_merge($aClassPlaceIDs, $this->oDB->getCol($sSQL));
1495                                                                                 }
1496                                                                         }
1497                                                                 }
1498
1499                                                                 $aPlaceIDs = $aClassPlaceIDs;
1500
1501                                                         }
1502
1503                                                 }
1504
1505                                                 if (PEAR::IsError($aPlaceIDs))
1506                                                 {
1507                                                         failInternalError("Could not get place IDs from tokens." ,$sSQL, $aPlaceIDs);
1508                                                 }
1509
1510                                                 if (CONST_Debug) { echo "<br><b>Place IDs:</b> "; var_Dump($aPlaceIDs); }
1511
1512                                                 foreach($aPlaceIDs as $iPlaceID)
1513                                                 {
1514                                                         $aResultPlaceIDs[$iPlaceID] = $iPlaceID;
1515                                                 }
1516                                                 if ($iQueryLoop > 20) break;
1517                                         }
1518
1519                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30))
1520                                         {
1521                                                 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1522                                                 $sSQL = "select place_id from placex where place_id in (".join(',',$aResultPlaceIDs).") ";
1523                                                 $sSQL .= "and (placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1524                                                 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) $sSQL .= " OR (extratags->'place') = 'city'";
1525                                                 if ($this->aAddressRankList) $sSQL .= " OR placex.rank_address in (".join(',',$this->aAddressRankList).")";
1526                                                 $sSQL .= ") UNION select place_id from location_property_tiger where place_id in (".join(',',$aResultPlaceIDs).") ";
1527                                                 $sSQL .= "and (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1528                                                 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',',$this->aAddressRankList).")";
1529                                                 $sSQL .= ")";
1530                                                 if (CONST_Debug) var_dump($sSQL);
1531                                                 $aResultPlaceIDs = $this->oDB->getCol($sSQL);
1532                                         }
1533
1534                                         //exit;
1535                                         if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1536                                         if ($iGroupLoop > 4) break;
1537                                         if ($iQueryLoop > 30) break;
1538                                 }
1539
1540                                 // Did we find anything?
1541                                 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs))
1542                                 {
1543                                         $aSearchResults = $this->getDetails($aResultPlaceIDs);
1544                                 }
1545
1546                         }
1547                         else
1548                         {
1549                                 // Just interpret as a reverse geocode
1550                                 $iPlaceID = geocodeReverse((float)$this->aNearPoint[0], (float)$this->aNearPoint[1]);
1551                                 if ($iPlaceID)
1552                                         $aSearchResults = $this->getDetails(array($iPlaceID));
1553                                 else
1554                                         $aSearchResults = array();
1555                         }
1556
1557                         // No results? Done
1558                         if (!sizeof($aSearchResults))
1559                         {
1560                                 if ($this->bFallback)
1561                                 {
1562                                         if ($this->fallbackStructuredQuery())
1563                                         {
1564                                                 return $this->lookup();
1565                                         }
1566                                 }
1567
1568                                 return array();
1569                         }
1570
1571                         $aClassType = getClassTypesWithImportance();
1572                         $aRecheckWords = preg_split('/\b/u',$sQuery);
1573                         foreach($aRecheckWords as $i => $sWord)
1574                         {
1575                                 if (!$sWord) unset($aRecheckWords[$i]);
1576                         }
1577
1578                         foreach($aSearchResults as $iResNum => $aResult)
1579                         {
1580                                 if (CONST_Search_AreaPolygons)
1581                                 {
1582                                         // Get the bounding box and outline polygon
1583                                         $sSQL = "select place_id,0 as numfeatures,st_area(geometry) as area,";
1584                                         $sSQL .= "ST_Y(centroid) as centrelat,ST_X(centroid) as centrelon,";
1585                                         $sSQL .= "ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),4)) as minlat,ST_Y(ST_PointN(ST_ExteriorRing(Box2D(geometry)),2)) as maxlat,";
1586                                         $sSQL .= "ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),1)) as minlon,ST_X(ST_PointN(ST_ExteriorRing(Box2D(geometry)),3)) as maxlon";
1587                                         if ($this->bIncludePolygonAsGeoJSON) $sSQL .= ",ST_AsGeoJSON(geometry) as asgeojson";
1588                                         if ($this->bIncludePolygonAsKML) $sSQL .= ",ST_AsKML(geometry) as askml";
1589                                         if ($this->bIncludePolygonAsSVG) $sSQL .= ",ST_AsSVG(geometry) as assvg";
1590                                         if ($this->bIncludePolygonAsText || $this->bIncludePolygonAsPoints) $sSQL .= ",ST_AsText(geometry) as astext";
1591                                         $sSQL .= " from placex where place_id = ".$aResult['place_id'].' and st_geometrytype(Box2D(geometry)) = \'ST_Polygon\'';
1592                                         $aPointPolygon = $this->oDB->getRow($sSQL);
1593                                         if (PEAR::IsError($aPointPolygon))
1594                                         {
1595                                                 failInternalError("Could not get outline.", $sSQL, $aPointPolygon);
1596                                         }
1597
1598                                         if ($aPointPolygon['place_id'])
1599                                         {
1600                                                 if ($this->bIncludePolygonAsGeoJSON) $aResult['asgeojson'] = $aPointPolygon['asgeojson'];
1601                                                 if ($this->bIncludePolygonAsKML) $aResult['askml'] = $aPointPolygon['askml'];
1602                                                 if ($this->bIncludePolygonAsSVG) $aResult['assvg'] = $aPointPolygon['assvg'];
1603                                                 if ($this->bIncludePolygonAsText) $aResult['astext'] = $aPointPolygon['astext'];
1604
1605                                                 if ($aPointPolygon['centrelon'] !== null && $aPointPolygon['centrelat'] !== null )
1606                                                 {
1607                                                         $aResult['lat'] = $aPointPolygon['centrelat'];
1608                                                         $aResult['lon'] = $aPointPolygon['centrelon'];
1609                                                 }
1610
1611                                                 if ($this->bIncludePolygonAsPoints)
1612                                                 {
1613                                                         // Translate geometary string to point array
1614                                                         if (preg_match('#POLYGON\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1615                                                         {
1616                                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1617                                                         }
1618                             /*
1619                                                         elseif (preg_match('#MULTIPOLYGON\\(\\(\\(([- 0-9.,]+)#',$aPointPolygon['astext'],$aMatch))
1620                                                         {
1621                                                                 preg_match_all('/(-?[0-9.]+) (-?[0-9.]+)/',$aMatch[1],$aPolyPoints,PREG_SET_ORDER);
1622                                                         }
1623                             */
1624                                                         elseif (preg_match('#POINT\\((-?[0-9.]+) (-?[0-9.]+)\\)#',$aPointPolygon['astext'],$aMatch))
1625                                                         {
1626                                                                 $fRadius = 0.01;
1627                                                                 $iSteps = ($fRadius * 40000)^2;
1628                                                                 $fStepSize = (2*pi())/$iSteps;
1629                                                                 $aPolyPoints = array();
1630                                                                 for($f = 0; $f < 2*pi(); $f += $fStepSize)
1631                                                                 {
1632                                                                         $aPolyPoints[] = array('',$aMatch[1]+($fRadius*sin($f)),$aMatch[2]+($fRadius*cos($f)));
1633                                                                 }
1634                                                                 $aPointPolygon['minlat'] = $aPointPolygon['minlat'] - $fRadius;
1635                                                                 $aPointPolygon['maxlat'] = $aPointPolygon['maxlat'] + $fRadius;
1636                                                                 $aPointPolygon['minlon'] = $aPointPolygon['minlon'] - $fRadius;
1637                                                                 $aPointPolygon['maxlon'] = $aPointPolygon['maxlon'] + $fRadius;
1638                                                         }
1639                                                 }
1640
1641                                                 // Output data suitable for display (points and a bounding box)
1642                                                 if ($this->bIncludePolygonAsPoints && isset($aPolyPoints))
1643                                                 {
1644                                                         $aResult['aPolyPoints'] = array();
1645                                                         foreach($aPolyPoints as $aPoint)
1646                                                         {
1647                                                                 $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1648                                                         }
1649                                                 }
1650                                                 $aResult['aBoundingBox'] = array($aPointPolygon['minlat'],$aPointPolygon['maxlat'],$aPointPolygon['minlon'],$aPointPolygon['maxlon']);
1651                                         }
1652                                 }
1653
1654                                 if ($aResult['extra_place'] == 'city')
1655                                 {
1656                                         $aResult['class'] = 'place';
1657                                         $aResult['type'] = 'city';
1658                                         $aResult['rank_search'] = 16;
1659                                 }
1660
1661                                 if (!isset($aResult['aBoundingBox']))
1662                                 {
1663                                         // Default
1664                                         $fDiameter = 0.0001;
1665
1666                                         if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1667                                                         && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defdiameter'])
1668                                         {
1669                                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['defzoom'];
1670                                         }
1671                                         elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1672                                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'])
1673                                         {
1674                                                 $fDiameter = $aClassType[$aResult['class'].':'.$aResult['type']]['defdiameter'];
1675                                         }
1676                                         $fRadius = $fDiameter / 2;
1677
1678                                         $iSteps = max(8,min(100,$fRadius * 3.14 * 100000));
1679                                         $fStepSize = (2*pi())/$iSteps;
1680                                         $aPolyPoints = array();
1681                                         for($f = 0; $f < 2*pi(); $f += $fStepSize)
1682                                         {
1683                                                 $aPolyPoints[] = array('',$aResult['lon']+($fRadius*sin($f)),$aResult['lat']+($fRadius*cos($f)));
1684                                         }
1685                                         $aPointPolygon['minlat'] = $aResult['lat'] - $fRadius;
1686                                         $aPointPolygon['maxlat'] = $aResult['lat'] + $fRadius;
1687                                         $aPointPolygon['minlon'] = $aResult['lon'] - $fRadius;
1688                                         $aPointPolygon['maxlon'] = $aResult['lon'] + $fRadius;
1689
1690                                         // Output data suitable for display (points and a bounding box)
1691                                         if ($this->bIncludePolygonAsPoints)
1692                                         {
1693                                                 $aResult['aPolyPoints'] = array();
1694                                                 foreach($aPolyPoints as $aPoint)
1695                                                 {
1696                                                         $aResult['aPolyPoints'][] = array($aPoint[1], $aPoint[2]);
1697                                                 }
1698                                         }
1699                                         $aResult['aBoundingBox'] = array((string)$aPointPolygon['minlat'],(string)$aPointPolygon['maxlat'],(string)$aPointPolygon['minlon'],(string)$aPointPolygon['maxlon']);
1700                                 }
1701
1702                                 // Is there an icon set for this type of result?
1703                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1704                                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1705                                 {
1706                                         $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1707                                 }
1708
1709                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1710                                                 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1711                                 {
1712                                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1713                                 }
1714                                 elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1715                                                 && $aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1716                                 {
1717                                         $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1718                                 }
1719
1720                                 if ($this->bIncludeAddressDetails)
1721                                 {
1722                                         $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code']);
1723                                         if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city']))
1724                                         {
1725                                                 $aResult['address'] = array_merge(array('city' => array_shift(array_values($aResult['address']))), $aResult['address']);
1726                                         }
1727                                 }
1728
1729                                 // Adjust importance for the number of exact string matches in the result
1730                                 $aResult['importance'] = max(0.001,$aResult['importance']);
1731                                 $iCountWords = 0;
1732                                 $sAddress = $aResult['langaddress'];
1733                                 foreach($aRecheckWords as $i => $sWord)
1734                                 {
1735                                         if (stripos($sAddress, $sWord)!==false) $iCountWords++;
1736                                 }
1737
1738                                 $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
1739
1740                                 $aResult['name'] = $aResult['langaddress'];
1741                                 // secondary ordering (for results with same importance (the smaller the better):
1742                                 //   - approximate importance of address parts
1743                                 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1744                                 //   - number of exact matches from the query
1745                                 if (isset($this->exactMatchCache[$aResult['place_id']]))
1746                                         $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1747                                 else if (isset($this->exactMatchCache[$aResult['parent_place_id']]))
1748                                         $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1749                                 //  - importance of the class/type
1750                                 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1751                                         && $aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1752                                 {
1753                                         $aResult['foundorder'] = $aResult['foundorder'] + 0.000001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1754                                 }
1755                                 else
1756                                 {
1757                                         $aResult['foundorder'] = $aResult['foundorder'] + 0.001;
1758                                 }
1759                                 $aSearchResults[$iResNum] = $aResult;
1760                         }
1761                         uasort($aSearchResults, 'byImportance');
1762
1763                         $aOSMIDDone = array();
1764                         $aClassTypeNameDone = array();
1765                         $aToFilter = $aSearchResults;
1766                         $aSearchResults = array();
1767
1768                         $bFirst = true;
1769                         foreach($aToFilter as $iResNum => $aResult)
1770                         {
1771                                 if ($aResult['type'] == 'adminitrative') $aResult['type'] = 'administrative';
1772                                 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1773                                 if ($bFirst)
1774                                 {
1775                                         $fLat = $aResult['lat'];
1776                                         $fLon = $aResult['lon'];
1777                                         if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1778                                         $bFirst = false;
1779                                 }
1780                                 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1781                                                         && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']])))
1782                                 {
1783                                         $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1784                                         $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1785                                         $aSearchResults[] = $aResult;
1786                                 }
1787
1788                                 // Absolute limit on number of results
1789                                 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1790                         }
1791
1792                         return $aSearchResults;
1793
1794                 } // end lookup()
1795
1796
1797         } // end class
1798
1799
1800 /*
1801                 if (isset($_GET['route']) && $_GET['route'] && isset($_GET['routewidth']) && $_GET['routewidth'])
1802                 {
1803                         $aPoints = explode(',',$_GET['route']);
1804                         if (sizeof($aPoints) % 2 != 0)
1805                         {
1806                                 userError("Uneven number of points");
1807                                 exit;
1808                         }
1809                         $sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
1810                         $fPrevCoord = false;
1811                 }
1812 */