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