5 require_once(CONST_BasePath.'/lib/NearPoint.php');
6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
13 protected $aLangPrefOrder = array();
15 protected $bIncludeAddressDetails = false;
16 protected $bIncludeExtraTags = false;
17 protected $bIncludeNameDetails = false;
19 protected $bIncludePolygonAsPoints = false;
20 protected $bIncludePolygonAsText = false;
21 protected $bIncludePolygonAsGeoJSON = false;
22 protected $bIncludePolygonAsKML = false;
23 protected $bIncludePolygonAsSVG = false;
24 protected $fPolygonSimplificationThreshold = 0.0;
26 protected $aExcludePlaceIDs = array();
27 protected $bDeDupe = true;
28 protected $bReverseInPlan = false;
30 protected $iLimit = 20;
31 protected $iFinalLimit = 10;
32 protected $iOffset = 0;
33 protected $bFallback = false;
35 protected $aCountryCodes = false;
37 protected $bBoundedSearch = false;
38 protected $aViewBox = false;
39 protected $sViewboxCentreSQL = false;
40 protected $sViewboxSmallSQL = false;
41 protected $sViewboxLargeSQL = false;
43 protected $iMaxRank = 20;
44 protected $iMinAddressRank = 0;
45 protected $iMaxAddressRank = 30;
46 protected $aAddressRankList = array();
47 protected $exactMatchCache = array();
49 protected $sAllowedTypesSQLList = false;
51 protected $sQuery = false;
52 protected $aStructuredQuery = false;
55 public function __construct(&$oDB)
60 public function setReverseInPlan($bReverse)
62 $this->bReverseInPlan = $bReverse;
65 public function setLanguagePreference($aLangPref)
67 $this->aLangPrefOrder = $aLangPref;
70 public function getMoreUrlParams()
72 if ($this->aStructuredQuery) {
73 $aParams = $this->aStructuredQuery;
75 $aParams = array('q' => $this->sQuery);
78 if ($this->aExcludePlaceIDs) {
79 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
82 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
83 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
84 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
86 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
87 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
88 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
89 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
90 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
92 if ($this->fPolygonSimplificationThreshold > 0.0) {
93 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
96 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
97 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
99 if ($this->aCountryCodes) {
100 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
103 if ($this->aViewBox) {
104 $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
105 .','.$this->aViewBox[2].','.$this->aViewBox[1];
111 public function setIncludePolygonAsPoints($b = true)
113 $this->bIncludePolygonAsPoints = $b;
116 public function setIncludePolygonAsText($b = true)
118 $this->bIncludePolygonAsText = $b;
121 public function setIncludePolygonAsGeoJSON($b = true)
123 $this->bIncludePolygonAsGeoJSON = $b;
126 public function setIncludePolygonAsKML($b = true)
128 $this->bIncludePolygonAsKML = $b;
131 public function setIncludePolygonAsSVG($b = true)
133 $this->bIncludePolygonAsSVG = $b;
136 public function setPolygonSimplificationThreshold($f)
138 $this->fPolygonSimplificationThreshold = $f;
141 public function setLimit($iLimit = 10)
143 if ($iLimit > 50) $iLimit = 50;
144 if ($iLimit < 1) $iLimit = 1;
146 $this->iFinalLimit = $iLimit;
147 $this->iLimit = $iLimit + min($iLimit, 10);
150 public function setFeatureType($sFeatureType)
152 switch ($sFeatureType) {
154 $this->setRankRange(4, 4);
157 $this->setRankRange(8, 8);
160 $this->setRankRange(14, 16);
163 $this->setRankRange(8, 20);
168 public function setRankRange($iMin, $iMax)
170 $this->iMinAddressRank = $iMin;
171 $this->iMaxAddressRank = $iMax;
174 public function setRoute($aRoutePoints, $fRouteWidth)
176 $this->aViewBox = false;
178 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
180 foreach ($aRoutePoints as $aPoint) {
181 $fPoint = (float)$aPoint;
182 $this->sViewboxCentreSQL .= $sSep.$fPoint;
183 $sSep = ($sSep == ' ') ? ',' : ' ';
185 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
187 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
188 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
190 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
191 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
194 public function setViewbox($aViewbox)
196 $this->aViewBox = array_map('floatval', $aViewbox);
198 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
199 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
200 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
201 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
203 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
204 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
206 userError("Bad parameter 'viewbox'. Not a box.");
209 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
210 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
211 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
212 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
213 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
214 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
216 $this->sViewboxCentreSQL = false;
217 $this->sViewboxSmallSQL = sprintf(
218 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
224 $this->sViewboxLargeSQL = sprintf(
225 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
233 public function setQuery($sQueryString)
235 $this->sQuery = $sQueryString;
236 $this->aStructuredQuery = false;
239 public function getQueryString()
241 return $this->sQuery;
245 public function loadParamArray($oParams)
247 $this->bIncludeAddressDetails
248 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
249 $this->bIncludeExtraTags
250 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
251 $this->bIncludeNameDetails
252 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
254 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
255 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
257 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
258 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
260 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
262 // List of excluded Place IDs - used for more acurate pageing
263 $sExcluded = $oParams->getStringList('exclude_place_ids');
265 foreach ($sExcluded as $iExcludedPlaceID) {
266 $iExcludedPlaceID = (int)$iExcludedPlaceID;
267 if ($iExcludedPlaceID)
268 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
271 if (isset($aExcludePlaceIDs))
272 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
275 // Only certain ranks of feature
276 $sFeatureType = $oParams->getString('featureType');
277 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
278 if ($sFeatureType) $this->setFeatureType($sFeatureType);
281 $sCountries = $oParams->getStringList('countrycodes');
283 foreach ($sCountries as $sCountryCode) {
284 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
285 $aCountries[] = strtolower($sCountryCode);
288 if (isset($aCountries))
289 $this->aCountryCodes = $aCountries;
292 $aViewbox = $oParams->getStringList('viewboxlbrt');
294 if (count($aViewbox) != 4) {
295 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
297 $this->setViewbox($aViewbox);
299 $aViewbox = $oParams->getStringList('viewbox');
301 if (count($aViewbox) != 4) {
302 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
304 $this->setViewBox(array(
311 $aRoute = $oParams->getStringList('route');
312 $fRouteWidth = $oParams->getFloat('routewidth');
313 if ($aRoute && $fRouteWidth) {
314 $this->setRoute($aRoute, $fRouteWidth);
320 public function setQueryFromParams($oParams)
323 $sQuery = $oParams->getString('q');
325 $this->setStructuredQuery(
326 $oParams->getString('amenity'),
327 $oParams->getString('street'),
328 $oParams->getString('city'),
329 $oParams->getString('county'),
330 $oParams->getString('state'),
331 $oParams->getString('country'),
332 $oParams->getString('postalcode')
334 $this->setReverseInPlan(false);
336 $this->setQuery($sQuery);
340 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
342 $sValue = trim($sValue);
343 if (!$sValue) return false;
344 $this->aStructuredQuery[$sKey] = $sValue;
345 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
346 $this->iMinAddressRank = $iNewMinAddressRank;
347 $this->iMaxAddressRank = $iNewMaxAddressRank;
349 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
353 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
355 $this->sQuery = false;
358 $this->iMinAddressRank = 0;
359 $this->iMaxAddressRank = 30;
360 $this->aAddressRankList = array();
362 $this->aStructuredQuery = array();
363 $this->sAllowedTypesSQLList = '';
365 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
366 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
367 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
368 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
369 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
370 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
371 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
373 if (sizeof($this->aStructuredQuery) > 0) {
374 $this->sQuery = join(', ', $this->aStructuredQuery);
375 if ($this->iMaxAddressRank < 30) {
376 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
381 public function fallbackStructuredQuery()
383 if (!$this->aStructuredQuery) return false;
385 $aParams = $this->aStructuredQuery;
387 if (sizeof($aParams) == 1) return false;
389 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
391 foreach ($aOrderToFallback as $sType) {
392 if (isset($aParams[$sType])) {
393 unset($aParams[$sType]);
394 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
402 public function getDetails($aPlaceIDs)
404 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
405 if (sizeof($aPlaceIDs) == 0) return array();
407 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
409 // Get the details for display (is this a redundant extra step?)
410 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
412 $sImportanceSQL = '';
413 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
414 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
417 $sSQL .= " osm_type,";
421 $sSQL .= " admin_level,";
422 $sSQL .= " rank_search,";
423 $sSQL .= " rank_address,";
424 $sSQL .= " min(place_id) AS place_id, ";
425 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
426 $sSQL .= " country_code, ";
427 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
428 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
429 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
430 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
431 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
432 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
433 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
434 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
436 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
438 $sSQL .= " place_addressline s, ";
439 $sSQL .= " placex p";
440 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
441 $sSQL .= " AND p.place_id = s.address_place_id ";
442 $sSQL .= " AND s.isaddress ";
443 $sSQL .= " AND p.importance is not null ";
444 $sSQL .= " ) AS addressimportance, ";
445 $sSQL .= " (extratags->'place') AS extra_place ";
446 $sSQL .= " FROM placex";
447 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
449 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
450 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
451 $sSQL .= " OR (extratags->'place') = 'city'";
453 if ($this->aAddressRankList) {
454 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
457 if ($this->sAllowedTypesSQLList) {
458 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
460 $sSQL .= " AND linked_place_id is null ";
461 $sSQL .= " GROUP BY ";
462 $sSQL .= " osm_type, ";
463 $sSQL .= " osm_id, ";
466 $sSQL .= " admin_level, ";
467 $sSQL .= " rank_search, ";
468 $sSQL .= " rank_address, ";
469 $sSQL .= " country_code, ";
470 $sSQL .= " importance, ";
471 if (!$this->bDeDupe) $sSQL .= "place_id,";
472 $sSQL .= " langaddress, ";
473 $sSQL .= " placename, ";
475 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
476 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
477 $sSQL .= " extratags->'place' ";
482 $sSQL .= " 'P' as osm_type,";
483 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = parent_place_id) as osm_id,";
484 $sSQL .= " 'place' as class, 'postcode' as type,";
485 $sSQL .= " null as admin_level, rank_search, rank_address,";
486 $sSQL .= " place_id, parent_place_id, country_code,";
487 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
488 $sSQL .= " postcode as placename,";
489 $sSQL .= " postcode as ref,";
490 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
491 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
492 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
493 $sSQL .= $sImportanceSQL."(0.75-(rank_search::float/40)) AS importance, ";
495 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
497 $sSQL .= " place_addressline s, ";
498 $sSQL .= " placex p";
499 $sSQL .= " WHERE s.place_id = parent_place_id";
500 $sSQL .= " AND p.place_id = s.address_place_id ";
501 $sSQL .= " AND s.isaddress";
502 $sSQL .= " AND p.importance is not null";
503 $sSQL .= " ) AS addressimportance, ";
504 $sSQL .= " null AS extra_place ";
505 $sSQL .= "FROM location_postcode";
506 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
508 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
509 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
510 // with start- and endnumber, the common osm housenumbers are usually saved as points
513 $length = count($aPlaceIDs);
514 foreach ($aPlaceIDs as $placeID => $housenumber) {
516 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
517 if ($i<$length) $sHousenumbers .= ", ";
520 if (CONST_Use_US_Tiger_Data) {
521 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
524 $sSQL .= " 'T' AS osm_type, ";
525 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
526 $sSQL .= " 'place' AS class, ";
527 $sSQL .= " 'house' AS type, ";
528 $sSQL .= " null AS admin_level, ";
529 $sSQL .= " 30 AS rank_search, ";
530 $sSQL .= " 30 AS rank_address, ";
531 $sSQL .= " min(place_id) AS place_id, ";
532 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
533 $sSQL .= " 'us' AS country_code, ";
534 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
535 $sSQL .= " null AS placename, ";
536 $sSQL .= " null AS ref, ";
537 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
538 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
539 $sSQL .= " avg(st_x(centroid)) AS lon, ";
540 $sSQL .= " avg(st_y(centroid)) AS lat,";
541 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
543 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
545 $sSQL .= " place_addressline s, ";
546 $sSQL .= " placex p";
547 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
548 $sSQL .= " AND p.place_id = s.address_place_id ";
549 $sSQL .= " AND s.isaddress";
550 $sSQL .= " AND p.importance is not null";
551 $sSQL .= " ) AS addressimportance, ";
552 $sSQL .= " null AS extra_place ";
554 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
555 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
556 $sSQL .= " parent_place_id, ";
557 $sSQL .= " housenumber_for_place";
559 $sSQL .= " location_property_tiger ";
560 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
562 $sSQL .= " housenumber_for_place>=0";
563 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
564 $sSQL .= " ) AS blub"; //postgres wants an alias here
565 $sSQL .= " GROUP BY";
566 $sSQL .= " place_id, ";
567 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
568 if (!$this->bDeDupe) $sSQL .= ", place_id ";
571 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
574 $sSQL .= " 'W' AS osm_type, ";
575 $sSQL .= " osm_id, ";
576 $sSQL .= " 'place' AS class, ";
577 $sSQL .= " 'house' AS type, ";
578 $sSQL .= " null AS admin_level, ";
579 $sSQL .= " 30 AS rank_search, ";
580 $sSQL .= " 30 AS rank_address, ";
581 $sSQL .= " min(place_id) as place_id, ";
582 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
583 $sSQL .= " country_code, ";
584 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
585 $sSQL .= " null AS placename, ";
586 $sSQL .= " null AS ref, ";
587 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
588 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
589 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
590 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
591 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
594 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
596 $sSQL .= " place_addressline s, ";
597 $sSQL .= " placex p";
598 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
599 $sSQL .= " AND p.place_id = s.address_place_id ";
600 $sSQL .= " AND s.isaddress ";
601 $sSQL .= " AND p.importance is not null";
602 $sSQL .= " ) AS addressimportance,";
603 $sSQL .= " null AS extra_place ";
606 $sSQL .= " osm_id, ";
607 $sSQL .= " place_id, ";
608 $sSQL .= " country_code, ";
609 $sSQL .= " CASE "; // interpolate the housenumbers here
610 $sSQL .= " WHEN startnumber != endnumber ";
611 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
612 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
613 $sSQL .= " END as centroid, ";
614 $sSQL .= " parent_place_id, ";
615 $sSQL .= " housenumber_for_place ";
617 $sSQL .= " location_property_osmline ";
618 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
620 $sSQL .= " WHERE housenumber_for_place>=0 ";
621 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
622 $sSQL .= " ) as blub"; //postgres wants an alias here
623 $sSQL .= " GROUP BY ";
624 $sSQL .= " osm_id, ";
625 $sSQL .= " place_id, ";
626 $sSQL .= " housenumber_for_place, ";
627 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
628 if (!$this->bDeDupe) $sSQL .= ", place_id ";
630 if (CONST_Use_Aux_Location_data) {
633 $sSQL .= " 'L' AS osm_type, ";
634 $sSQL .= " place_id AS osm_id, ";
635 $sSQL .= " 'place' AS class,";
636 $sSQL .= " 'house' AS type, ";
637 $sSQL .= " null AS admin_level, ";
638 $sSQL .= " 0 AS rank_search,";
639 $sSQL .= " 0 AS rank_address, ";
640 $sSQL .= " min(place_id) AS place_id,";
641 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
642 $sSQL .= " 'us' AS country_code, ";
643 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
644 $sSQL .= " null AS placename, ";
645 $sSQL .= " null AS ref, ";
646 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
647 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
648 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
649 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
650 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
652 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
654 $sSQL .= " place_addressline s, ";
655 $sSQL .= " placex p";
656 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
657 $sSQL .= " AND p.place_id = s.address_place_id ";
658 $sSQL .= " AND s.isaddress";
659 $sSQL .= " AND p.importance is not null";
660 $sSQL .= " ) AS addressimportance, ";
661 $sSQL .= " null AS extra_place ";
662 $sSQL .= " FROM location_property_aux ";
663 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
664 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
665 $sSQL .= " GROUP BY ";
666 $sSQL .= " place_id, ";
667 if (!$this->bDeDupe) $sSQL .= "place_id, ";
668 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
672 $sSQL .= " order by importance desc";
677 $aSearchResults = chksql(
678 $this->oDB->getAll($sSQL),
679 "Could not get details for place."
682 return $aSearchResults;
685 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
688 Calculate all searches using aValidTokens i.e.
689 'Wodsworth Road, Sheffield' =>
693 0 1 (wodsworth)(road)
696 Score how good the search is so they can be ordered
698 foreach ($aPhrases as $iPhrase => $aPhrase) {
699 $aNewPhraseSearches = array();
700 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
701 else $sPhraseType = '';
703 foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
704 // Too many permutations - too expensive
705 if ($iWordSet > 120) break;
707 $aWordsetSearches = $aSearches;
709 // Add all words from this wordset
710 foreach ($aWordset as $iToken => $sToken) {
711 //echo "<br><b>$sToken</b>";
712 $aNewWordsetSearches = array();
714 foreach ($aWordsetSearches as $aCurrentSearch) {
716 //var_dump($aCurrentSearch);
719 // If the token is valid
720 if (isset($aValidTokens[' '.$sToken])) {
721 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
722 $aSearch = $aCurrentSearch;
723 $aSearch['iSearchRank']++;
724 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
725 if ($aSearch['sCountryCode'] === false) {
726 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
727 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
728 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
729 $aSearch['iSearchRank'] += 5;
731 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
733 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
734 if ($aSearch['oNear'] === false) {
735 $aSearch['oNear'] = new NearPoint(
738 $aSearchTerm['radius']
740 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
742 } elseif ($sPhraseType == 'postalcode' || ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode')) {
743 // 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
744 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
745 // If we have structured search or this is the first term,
746 // make the postcode the primary search element.
747 if ($aSearchTerm['operator'] == '' && ($sPhraseType == 'postalcode' || sizeof($aSearch['aName']) == 0)) {
748 $aNewSearch = $aSearch;
749 $aNewSearch['sOperator'] = 'postcode';
750 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
751 $aNewSearch['aName'][$aSearchTerm['word_id']] = substr($aSearchTerm['word_token'], 1);
752 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
755 // If we have a structured search or this is not the first term,
756 // add the postcode as an addendum.
757 if ($sPhraseType == 'postalcode' || sizeof($aSearch['aName'])) {
758 $aSearch['sPostcode'] = $aSearchTerm['word_token'];
759 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
762 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
763 if ($aSearch['sHouseNumber'] === '') {
764 $aSearch['sHouseNumber'] = $sToken;
765 // sanity check: if the housenumber is not mainly made
766 // up of numbers, add a penalty
767 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
768 // also housenumbers should appear in the first or second phrase
769 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
770 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
772 // Fall back to not searching for this item (better than nothing)
773 $aSearch = $aCurrentSearch;
774 $aSearch['iSearchRank'] += 1;
775 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
778 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
779 // require a normalized exact match of the term
780 // if we have the normalizer version of the query
782 if ($aSearch['sClass'] === ''
783 && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
784 $aSearch['sClass'] = $aSearchTerm['class'];
785 $aSearch['sType'] = $aSearchTerm['type'];
786 if ($aSearchTerm['operator'] == '') {
787 $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' : 'near';
788 $aSearch['iSearchRank'] += 2;
790 $aSearch['sOperator'] = 'near'; // near = in for the moment
793 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
795 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
796 if (sizeof($aSearch['aName'])) {
797 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
798 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
800 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
801 $aSearch['iSearchRank'] += 1000; // skip;
804 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
805 //$aSearch['iNamePhrase'] = $iPhrase;
807 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
811 // Look for partial matches.
812 // Note that there is no point in adding country terms here
813 // because country are omitted in the address.
814 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
815 // Allow searching for a word - but at extra cost
816 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
817 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
818 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
819 $aSearch = $aCurrentSearch;
820 $aSearch['iSearchRank'] += 1;
821 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
822 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
823 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
824 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
825 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
826 $aSearch['iSearchRank'] += 1;
827 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
828 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
829 if (empty($aSearchTermToken['country_code'])
830 && empty($aSearchTermToken['lat'])
831 && empty($aSearchTermToken['class'])
833 $aSearch = $aCurrentSearch;
834 $aSearch['iSearchRank'] += 1;
835 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
836 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
840 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
841 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
842 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
846 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
847 $aSearch = $aCurrentSearch;
848 $aSearch['iSearchRank'] += 1;
849 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
850 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
851 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
852 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
854 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
856 $aSearch['iNamePhrase'] = $iPhrase;
857 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
862 // Allow skipping a word - but at EXTREAM cost
863 //$aSearch = $aCurrentSearch;
864 //$aSearch['iSearchRank']+=100;
865 //$aNewWordsetSearches[] = $aSearch;
869 usort($aNewWordsetSearches, 'bySearchRank');
870 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
872 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
874 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
875 usort($aNewPhraseSearches, 'bySearchRank');
877 $aSearchHash = array();
878 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
879 $sHash = serialize($aSearch);
880 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
881 else $aSearchHash[$sHash] = 1;
884 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
887 // Re-group the searches by their score, junk anything over 20 as just not worth trying
888 $aGroupedSearches = array();
889 foreach ($aNewPhraseSearches as $aSearch) {
890 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
891 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
892 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
895 ksort($aGroupedSearches);
898 $aSearches = array();
899 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
900 $iSearchCount += sizeof($aNewSearches);
901 $aSearches = array_merge($aSearches, $aNewSearches);
902 if ($iSearchCount > 50) break;
905 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
907 return $aGroupedSearches;
910 /* Perform the actual query lookup.
912 Returns an ordered list of results, each with the following fields:
913 osm_type: type of corresponding OSM object
917 P - postcode (internally computed)
918 osm_id: id of corresponding OSM object
919 class: general object class (corresponds to tag key of primary OSM tag)
920 type: subclass of object (corresponds to tag value of primary OSM tag)
921 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
922 rank_search: rank in search hierarchy
923 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
924 rank_address: rank in address hierarchy (determines orer in address)
925 place_id: internal key (may differ between different instances)
926 country_code: ISO country code
927 langaddress: localized full address
928 placename: localized name of object
929 ref: content of ref tag (if available)
932 importance: importance of place based on Wikipedia link count
933 addressimportance: cumulated importance of address elements
934 extra_place: type of place (for admin boundaries, if there is a place tag)
935 aBoundingBox: bounding Box
936 label: short description of the object class/type (English only)
937 name: full name (currently the same as langaddress)
938 foundorder: secondary ordering for places with same importance
942 public function lookup()
944 if (!$this->sQuery && !$this->aStructuredQuery) return array();
946 $oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
947 if ($oNormalizer !== null) {
948 $sNormQuery = $oNormalizer->transliterate($this->sQuery);
953 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
954 $sCountryCodesSQL = false;
955 if ($this->aCountryCodes) {
956 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
959 $sQuery = $this->sQuery;
960 if (!preg_match('//u', $sQuery)) {
961 userError("Query string is not UTF-8 encoded.");
964 // Conflicts between US state abreviations and various words for 'the' in different languages
965 if (isset($this->aLangPrefOrder['name:en'])) {
966 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
967 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
968 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
971 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
972 if ($this->sViewboxCentreSQL) {
973 // For complex viewboxes (routes) precompute the bounding geometry
975 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
976 "Could not get small viewbox"
978 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
981 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
982 "Could not get large viewbox"
984 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
987 // Do we have anything that looks like a lat/lon pair?
989 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
990 $oNearPoint = $aLooksLike['pt'];
991 $sQuery = $aLooksLike['query'];
994 $aSearchResults = array();
995 if ($sQuery || $this->aStructuredQuery) {
996 // Start with a blank search
1000 'iNamePhrase' => -1,
1001 'sCountryCode' => false,
1003 'aAddress' => array(),
1004 'aFullNameAddress' => array(),
1005 'aNameNonSearch' => array(),
1006 'aAddressNonSearch' => array(),
1008 'aFeatureName' => array(),
1011 'sHouseNumber' => '',
1013 'oNear' => $oNearPoint
1017 // Any 'special' terms in the search?
1018 $bSpecialTerms = false;
1019 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1020 $aSpecialTerms = array();
1021 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1022 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1023 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
1026 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1027 $aSpecialTerms = array();
1028 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
1029 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
1030 unset($this->aStructuredQuery['amenity']);
1033 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1034 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1035 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
1036 $sSQL = 'SELECT * ';
1038 $sSQL .= ' SELECT word_id, word_token, word, class, type, country_code, operator';
1039 $sSQL .= ' FROM word ';
1040 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
1042 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1043 $sSQL .= ' OR country_code is not null';
1044 if (CONST_Debug) var_Dump($sSQL);
1045 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1046 $aNewSearches = array();
1047 foreach ($aSearches as $aSearch) {
1048 foreach ($aSearchWords as $aSearchTerm) {
1049 $aNewSearch = $aSearch;
1050 if ($aSearchTerm['country_code']) {
1051 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1052 $aNewSearches[] = $aNewSearch;
1053 $bSpecialTerms = true;
1055 if ($aSearchTerm['class']) {
1056 $aNewSearch['sClass'] = $aSearchTerm['class'];
1057 $aNewSearch['sType'] = $aSearchTerm['type'];
1058 $aNewSearches[] = $aNewSearch;
1059 $bSpecialTerms = true;
1063 $aSearches = $aNewSearches;
1066 // Split query into phrases
1067 // Commas are used to reduce the search space by indicating where phrases split
1068 if ($this->aStructuredQuery) {
1069 $aPhrases = $this->aStructuredQuery;
1070 $bStructuredPhrases = true;
1072 $aPhrases = explode(',', $sQuery);
1073 $bStructuredPhrases = false;
1076 // Convert each phrase to standard form
1077 // Create a list of standard words
1078 // Get all 'sets' of words
1079 // Generate a complete list of all
1081 foreach ($aPhrases as $iPhrase => $sPhrase) {
1083 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1084 "Cannot normalize query string (is it a UTF-8 string?)"
1086 if (trim($aPhrase['string'])) {
1087 $aPhrases[$iPhrase] = $aPhrase;
1088 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1089 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1090 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1092 unset($aPhrases[$iPhrase]);
1096 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1097 $aPhraseTypes = array_keys($aPhrases);
1098 $aPhrases = array_values($aPhrases);
1100 if (sizeof($aTokens)) {
1101 // Check which tokens we have, get the ID numbers
1102 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1103 $sSQL .= ' FROM word ';
1104 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1106 if (CONST_Debug) var_Dump($sSQL);
1108 $aValidTokens = array();
1109 if (sizeof($aTokens)) {
1110 $aDatabaseWords = chksql(
1111 $this->oDB->getAll($sSQL),
1112 "Could not get word tokens."
1115 $aDatabaseWords = array();
1117 $aPossibleMainWordIDs = array();
1118 $aWordFrequencyScores = array();
1119 foreach ($aDatabaseWords as $aToken) {
1120 // Very special case - require 2 letter country param to match the country code found
1121 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1122 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1127 if (isset($aValidTokens[$aToken['word_token']])) {
1128 $aValidTokens[$aToken['word_token']][] = $aToken;
1130 $aValidTokens[$aToken['word_token']] = array($aToken);
1132 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1133 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1135 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1137 // Try and calculate GB postcodes we might be missing
1138 foreach ($aTokens as $sToken) {
1139 // Source of gb postcodes is now definitive - always use
1140 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1141 if (substr($aData[1], -2, 1) != ' ') {
1142 $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1143 $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1145 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1146 if ($aGBPostcodeLocation) {
1147 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1149 } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1150 // US ZIP+4 codes - if there is no token,
1151 // merge in the 5-digit ZIP code
1152 if (isset($aValidTokens[$aData[1]])) {
1153 foreach ($aValidTokens[$aData[1]] as $aToken) {
1154 if (!$aToken['class']) {
1155 if (isset($aValidTokens[$sToken])) {
1156 $aValidTokens[$sToken][] = $aToken;
1158 $aValidTokens[$sToken] = array($aToken);
1166 foreach ($aTokens as $sToken) {
1167 // Unknown single word token with a number - assume it is a house number
1168 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1169 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1173 // Any words that have failed completely?
1174 // TODO: suggestions
1176 // Start the search process
1177 // array with: placeid => -1 | tiger-housenumber
1178 $aResultPlaceIDs = array();
1180 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1182 if ($this->bReverseInPlan) {
1183 // Reverse phrase array and also reverse the order of the wordsets in
1184 // the first and final phrase. Don't bother about phrases in the middle
1185 // because order in the address doesn't matter.
1186 $aPhrases = array_reverse($aPhrases);
1187 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1188 if (sizeof($aPhrases) > 1) {
1189 $aFinalPhrase = end($aPhrases);
1190 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1192 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1194 foreach ($aGroupedSearches as $aSearches) {
1195 foreach ($aSearches as $aSearch) {
1196 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1197 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1198 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1203 $aGroupedSearches = $aReverseGroupedSearches;
1204 ksort($aGroupedSearches);
1207 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1208 $aGroupedSearches = array();
1209 foreach ($aSearches as $aSearch) {
1210 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1211 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1212 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1215 ksort($aGroupedSearches);
1218 if (CONST_Debug) var_Dump($aGroupedSearches);
1219 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1220 $aCopyGroupedSearches = $aGroupedSearches;
1221 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1222 foreach ($aSearches as $iSearch => $aSearch) {
1223 $aReductionsList = array($aSearch['aAddress']);
1224 $iSearchRank = $aSearch['iSearchRank'];
1225 while (sizeof($aReductionsList) > 0) {
1227 if ($iSearchRank > iMaxRank) break 3;
1228 $aNewReductionsList = array();
1229 foreach ($aReductionsList as $aReductionsWordList) {
1230 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1231 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1232 $aReverseSearch = $aSearch;
1233 $aSearch['aAddress'] = $aReductionsWordListResult;
1234 $aSearch['iSearchRank'] = $iSearchRank;
1235 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1236 if (sizeof($aReductionsWordListResult) > 0) {
1237 $aNewReductionsList[] = $aReductionsWordListResult;
1241 $aReductionsList = $aNewReductionsList;
1245 ksort($aGroupedSearches);
1248 // Filter out duplicate searches
1249 $aSearchHash = array();
1250 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1251 foreach ($aSearches as $iSearch => $aSearch) {
1252 $sHash = serialize($aSearch);
1253 if (isset($aSearchHash[$sHash])) {
1254 unset($aGroupedSearches[$iGroup][$iSearch]);
1255 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1257 $aSearchHash[$sHash] = 1;
1262 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1266 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1268 foreach ($aSearches as $aSearch) {
1270 $searchedHousenumber = -1;
1272 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1273 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1275 // No location term?
1276 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1277 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1278 // Just looking for a country by code - look it up
1279 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1280 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1281 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1282 if ($bBoundingBoxSearch)
1283 $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1284 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1285 if (CONST_Debug) var_dump($sSQL);
1286 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1288 $aPlaceIDs = array();
1291 if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1292 if (!$aSearch['sClass']) continue;
1294 $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1295 if (chksql($this->oDB->getOne($sSQL))) {
1296 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1297 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1298 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1299 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1300 if (sizeof($this->aExcludePlaceIDs)) {
1301 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1303 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1304 $sSQL .= " limit $this->iLimit";
1305 if (CONST_Debug) var_dump($sSQL);
1306 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1308 // If excluded place IDs are given, it is fair to assume that
1309 // there have been results in the small box, so no further
1310 // expansion in that case.
1311 // Also don't expand if bounded results were requested.
1312 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1313 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1314 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1315 $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1316 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1317 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1318 $sSQL .= " LIMIT $this->iLimit";
1319 if (CONST_Debug) var_dump($sSQL);
1320 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1323 $sSQL = "SELECT place_id ";
1324 $sSQL .= "FROM placex ";
1325 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1326 $sSQL .= " AND type='".$aSearch['sType']."'";
1327 $sSQL .= " AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1328 $sSQL .= " AND linked_place_id is null";
1329 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1330 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1331 $sSQL .= " LIMIT $this->iLimit";
1332 if (CONST_Debug) var_dump($sSQL);
1333 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1336 } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1337 // If a coordinate is given, the search must either
1338 // be for a name or a special search. Ignore everythin else.
1339 $aPlaceIDs = array();
1340 } elseif ($aSearch['sOperator'] == 'postcode') {
1341 $sSQL = "SELECT p.place_id FROM location_postcode p ";
1342 if (sizeof($aSearch['aAddress'])) {
1343 $sSQL .= ", search_name s ";
1344 $sSQL .= "WHERE s.place_id = p.parent_place_id ";
1345 $sSQL .= "AND array_cat(s.nameaddress_vector, s.name_vector) @> ARRAY[".join($aSearch['aAddress'], ",")."] AND ";
1349 $sSQL .= "p.postcode = '".pg_escape_string(reset($aSearch['aName']))."'";
1350 if ($aSearch['sCountryCode']) {
1351 $sSQL .= " AND p.country_code = '".$aSearch['sCountryCode']."'";
1353 if ($sCountryCodesSQL) {
1354 $sSQL .= " AND p.country_code in ($sCountryCodesSQL)";
1356 $sSQL .= " LIMIT $this->iLimit";
1357 if (CONST_Debug) var_dump($sSQL);
1358 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1360 $aPlaceIDs = array();
1362 // First we need a position, either aName or fLat or both
1366 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1367 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1370 $aOrder[0] .= " EXISTS(";
1371 $aOrder[0] .= " SELECT place_id ";
1372 $aOrder[0] .= " FROM placex ";
1373 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1374 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1375 $aOrder[0] .= " LIMIT 1";
1376 $aOrder[0] .= " ) ";
1377 // also housenumbers from interpolation lines table are needed
1378 $aOrder[0] .= " OR EXISTS(";
1379 $aOrder[0] .= " SELECT place_id ";
1380 $aOrder[0] .= " FROM location_property_osmline ";
1381 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1382 $aOrder[0] .= " AND startnumber is not NULL";
1383 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1384 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1385 $aOrder[0] .= " LIMIT 1";
1388 $aOrder[0] .= " DESC";
1391 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1392 // they might be right - but they are just too darned expensive to run
1393 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1394 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1395 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1396 // For infrequent name terms disable index usage for address
1397 if (CONST_Search_NameOnlySearchFrequencyThreshold
1398 && sizeof($aSearch['aName']) == 1
1399 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1401 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1403 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1404 if (sizeof($aSearch['aAddressNonSearch'])) {
1405 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1409 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1410 if ($aSearch['sHouseNumber']) {
1411 $aTerms[] = "address_rank between 16 and 27";
1413 if ($this->iMinAddressRank > 0) {
1414 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1416 if ($this->iMaxAddressRank < 30) {
1417 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1420 if ($aSearch['oNear']) {
1421 $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1423 $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1425 if (sizeof($this->aExcludePlaceIDs)) {
1426 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1428 if ($sCountryCodesSQL) {
1429 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1432 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1434 $aOrder[] = $oNearPoint->distanceSQL('centroid');
1437 if ($aSearch['sHouseNumber']) {
1438 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1440 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1442 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1443 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1445 $aOrder[] = "$sImportanceSQL DESC";
1446 if (sizeof($aSearch['aFullNameAddress'])) {
1447 $sExactMatchSQL = ' ( ';
1448 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
1449 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1450 $sExactMatchSQL .= ' INTERSECT ';
1451 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
1452 $sExactMatchSQL .= ' ) s';
1453 $sExactMatchSQL .= ') as exactmatch';
1454 $aOrder[] = 'exactmatch DESC';
1456 $sExactMatchSQL = '0::int as exactmatch';
1459 if (sizeof($aTerms)) {
1460 $sSQL = "SELECT place_id, ";
1461 $sSQL .= $sExactMatchSQL;
1462 $sSQL .= " FROM search_name";
1463 $sSQL .= " WHERE ".join(' and ', $aTerms);
1464 $sSQL .= " ORDER BY ".join(', ', $aOrder);
1465 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1466 $sSQL .= " LIMIT 20";
1467 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1468 $sSQL .= " LIMIT 1";
1470 $sSQL .= " LIMIT ".$this->iLimit;
1473 if (CONST_Debug) var_dump($sSQL);
1474 $aViewBoxPlaceIDs = chksql(
1475 $this->oDB->getAll($sSQL),
1476 "Could not get places for search terms."
1478 //var_dump($aViewBoxPlaceIDs);
1479 // Did we have an viewbox matches?
1480 $aPlaceIDs = array();
1481 $bViewBoxMatch = false;
1482 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1483 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1484 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1485 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1486 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1487 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1488 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1491 //var_Dump($aPlaceIDs);
1494 //now search for housenumber, if housenumber provided
1495 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1496 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1497 $aRoadPlaceIDs = $aPlaceIDs;
1498 $sPlaceIDs = join(',', $aPlaceIDs);
1500 // Now they are indexed, look for a house attached to a street we found
1501 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1502 $sSQL = "SELECT place_id FROM placex ";
1503 $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1504 if (sizeof($this->aExcludePlaceIDs)) {
1505 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1507 $sSQL .= " LIMIT $this->iLimit";
1508 if (CONST_Debug) var_dump($sSQL);
1509 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1511 // if nothing found, search in the interpolation line table
1512 if (!sizeof($aPlaceIDs)) {
1513 // do we need to use transliteration and the regex for housenumbers???
1514 //new query for lines, not housenumbers anymore
1515 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1516 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1517 if ($searchedHousenumber%2 == 0) {
1518 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1519 $sSQL .= "interpolationtype='even'";
1521 //look for housenumber in streets with interpolationtype odd or all
1522 $sSQL .= "interpolationtype='odd'";
1524 $sSQL .= " or interpolationtype='all') and ";
1525 $sSQL .= $searchedHousenumber.">=startnumber and ";
1526 $sSQL .= $searchedHousenumber."<=endnumber";
1528 if (sizeof($this->aExcludePlaceIDs)) {
1529 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1531 //$sSQL .= " limit $this->iLimit";
1532 if (CONST_Debug) var_dump($sSQL);
1534 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1537 // If nothing found try the aux fallback table
1538 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1539 $sSQL = "SELECT place_id FROM location_property_aux ";
1540 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1541 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1542 if (sizeof($this->aExcludePlaceIDs)) {
1543 $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1545 //$sSQL .= " limit $this->iLimit";
1546 if (CONST_Debug) var_dump($sSQL);
1547 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1550 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1551 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1552 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1553 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1554 if ($searchedHousenumber%2 == 0) {
1555 $sSQL .= "interpolationtype='even'";
1557 $sSQL .= "interpolationtype='odd'";
1559 $sSQL .= " or interpolationtype='all') and ";
1560 $sSQL .= $searchedHousenumber.">=startnumber and ";
1561 $sSQL .= $searchedHousenumber."<=endnumber";
1563 if (sizeof($this->aExcludePlaceIDs)) {
1564 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1566 //$sSQL .= " limit $this->iLimit";
1567 if (CONST_Debug) var_dump($sSQL);
1569 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1572 // Fallback to the road (if no housenumber was found)
1573 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1574 $aPlaceIDs = $aRoadPlaceIDs;
1575 //set to -1, if no housenumbers were found
1576 $searchedHousenumber = -1;
1578 //else: housenumber was found, remains saved in searchedHousenumber
1582 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1583 $sPlaceIDs = join(',', $aPlaceIDs);
1584 $aClassPlaceIDs = array();
1586 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1587 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1588 $sSQL = "SELECT place_id ";
1589 $sSQL .= " FROM placex ";
1590 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1591 $sSQL .= " AND class='".$aSearch['sClass']."' ";
1592 $sSQL .= " AND type='".$aSearch['sType']."'";
1593 $sSQL .= " AND linked_place_id is null";
1594 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1595 $sSQL .= " ORDER BY rank_search ASC ";
1596 $sSQL .= " LIMIT $this->iLimit";
1597 if (CONST_Debug) var_dump($sSQL);
1598 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1601 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1602 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
1603 $sSQL = "SELECT count(*) FROM pg_tables ";
1604 $sSQL .= "WHERE tablename = '$sClassTable'";
1605 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1607 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1609 if (CONST_Debug) var_dump($sSQL);
1610 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1612 // For state / country level searches the normal radius search doesn't work very well
1613 $sPlaceGeom = false;
1614 if ($this->iMaxRank < 9 && $bCacheTable) {
1615 // Try and get a polygon to search in instead
1616 $sSQL = "SELECT geometry ";
1617 $sSQL .= " FROM placex";
1618 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1619 $sSQL .= " AND rank_search < $this->iMaxRank + 5";
1620 $sSQL .= " AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1621 $sSQL .= " ORDER BY rank_search ASC ";
1622 $sSQL .= " LIMIT 1";
1623 if (CONST_Debug) var_dump($sSQL);
1624 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1630 $this->iMaxRank += 5;
1631 $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1632 if (CONST_Debug) var_dump($sSQL);
1633 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1634 $sPlaceIDs = join(',', $aPlaceIDs);
1637 if ($sPlaceIDs || $sPlaceGeom) {
1640 // More efficient - can make the range bigger
1645 $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1646 } elseif ($sPlaceIDs) {
1647 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1648 } elseif ($sPlaceGeom) {
1649 $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1652 $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
1653 $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
1654 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1656 $sSQL .= ",placex as f where ";
1657 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1661 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1663 if (sizeof($this->aExcludePlaceIDs)) {
1664 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1666 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1667 $sSQL .= 'limit 300) i ';
1668 if ($sOrderBySQL) $sSQL .= "order by order_term asc";
1669 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1670 $sSQL .= " limit $this->iLimit";
1671 if (CONST_Debug) var_dump($sSQL);
1672 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1674 if ($aSearch['oNear']) {
1675 $fRange = $aSearch['oNear']->radius();
1680 $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1682 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1685 $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1686 $sSQL .= " FROM placex as l, placex as f ";
1687 $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1688 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1689 $sSQL .= " AND l.class='".$aSearch['sClass']."' ";
1690 $sSQL .= " AND l.type='".$aSearch['sType']."' ";
1691 if (sizeof($this->aExcludePlaceIDs)) {
1692 $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1694 if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1695 if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1696 if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1697 $sSQL .= " limit $this->iLimit";
1698 if (CONST_Debug) var_dump($sSQL);
1699 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1703 $aPlaceIDs = $aClassPlaceIDs;
1708 echo "<br><b>Place IDs:</b> ";
1709 var_Dump($aPlaceIDs);
1712 foreach ($aPlaceIDs as $iPlaceID) {
1713 // array for placeID => -1 | Tiger housenumber
1714 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1716 if ($iQueryLoop > 20) break;
1719 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1720 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1721 // reduces the number of place ids, like a filter
1722 // rank_address is 30 for interpolated housenumbers
1723 $sSQL = "SELECT place_id ";
1724 $sSQL .= "FROM placex ";
1725 $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1727 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1728 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1729 $sSQL .= " OR (extratags->'place') = 'city'";
1731 if ($this->aAddressRankList) {
1732 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1734 if (CONST_Use_US_Tiger_Data) {
1737 $sSQL .= " SELECT place_id ";
1738 $sSQL .= " FROM location_property_tiger ";
1739 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1740 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1741 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1743 $sSQL .= ") UNION ";
1744 $sSQL .= " SELECT place_id ";
1745 $sSQL .= " FROM location_property_osmline ";
1746 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1747 $sSQL .= " AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1748 if (CONST_Debug) var_dump($sSQL);
1749 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1751 foreach ($aFilteredPlaceIDs as $placeID) {
1752 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1754 $aResultPlaceIDs = $tempIDs;
1758 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1759 if ($iGroupLoop > 4) break;
1760 if ($iQueryLoop > 30) break;
1763 // Did we find anything?
1764 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1765 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1768 // Just interpret as a reverse geocode
1769 $oReverse = new ReverseGeocode($this->oDB);
1770 $oReverse->setZoom(18);
1772 $aLookup = $oReverse->lookup(
1778 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1780 if ($aLookup['place_id']) {
1781 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1782 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1784 $aSearchResults = array();
1789 if (!sizeof($aSearchResults)) {
1790 if ($this->bFallback) {
1791 if ($this->fallbackStructuredQuery()) {
1792 return $this->lookup();
1799 $aClassType = getClassTypesWithImportance();
1800 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1801 foreach ($aRecheckWords as $i => $sWord) {
1802 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1806 echo '<i>Recheck words:<\i>';
1807 var_dump($aRecheckWords);
1810 $oPlaceLookup = new PlaceLookup($this->oDB);
1811 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1812 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1813 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1814 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1815 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1816 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1818 foreach ($aSearchResults as $iResNum => $aResult) {
1820 $fDiameter = getResultDiameter($aResult);
1822 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1823 if ($aOutlineResult) {
1824 $aResult = array_merge($aResult, $aOutlineResult);
1827 if ($aResult['extra_place'] == 'city') {
1828 $aResult['class'] = 'place';
1829 $aResult['type'] = 'city';
1830 $aResult['rank_search'] = 16;
1833 // Is there an icon set for this type of result?
1834 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1835 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1837 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1840 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1841 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1843 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1844 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1845 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1847 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1849 // if tag '&addressdetails=1' is set in query
1850 if ($this->bIncludeAddressDetails) {
1851 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1852 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1853 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1854 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1858 if ($this->bIncludeExtraTags) {
1859 if ($aResult['extra']) {
1860 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1862 $aResult['sExtraTags'] = (object) array();
1866 if ($this->bIncludeNameDetails) {
1867 if ($aResult['names']) {
1868 $aResult['sNameDetails'] = json_decode($aResult['names']);
1870 $aResult['sNameDetails'] = (object) array();
1874 // Adjust importance for the number of exact string matches in the result
1875 $aResult['importance'] = max(0.001, $aResult['importance']);
1877 $sAddress = $aResult['langaddress'];
1878 foreach ($aRecheckWords as $i => $sWord) {
1879 if (stripos($sAddress, $sWord)!==false) {
1881 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1885 $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
1887 $aResult['name'] = $aResult['langaddress'];
1888 // secondary ordering (for results with same importance (the smaller the better):
1889 // - approximate importance of address parts
1890 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1891 // - number of exact matches from the query
1892 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1893 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1894 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1895 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1897 // - importance of the class/type
1898 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1899 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1901 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1903 $aResult['foundorder'] += 0.01;
1905 if (CONST_Debug) var_dump($aResult);
1906 $aSearchResults[$iResNum] = $aResult;
1908 uasort($aSearchResults, 'byImportance');
1910 $aOSMIDDone = array();
1911 $aClassTypeNameDone = array();
1912 $aToFilter = $aSearchResults;
1913 $aSearchResults = array();
1916 foreach ($aToFilter as $iResNum => $aResult) {
1917 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1919 $fLat = $aResult['lat'];
1920 $fLon = $aResult['lon'];
1921 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1924 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1925 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1927 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1928 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1929 $aSearchResults[] = $aResult;
1932 // Absolute limit on number of results
1933 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1936 return $aSearchResults;