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