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