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