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