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;
54 protected $oNormalizer = null;
57 public function __construct(&$oDB)
60 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
63 private function normTerm($sTerm)
65 if ($this->oNormalizer === null) {
69 return $this->oNormalizer->transliterate($sTerm);
72 public function setReverseInPlan($bReverse)
74 $this->bReverseInPlan = $bReverse;
77 public function setLanguagePreference($aLangPref)
79 $this->aLangPrefOrder = $aLangPref;
82 public function getMoreUrlParams()
84 if ($this->aStructuredQuery) {
85 $aParams = $this->aStructuredQuery;
87 $aParams = array('q' => $this->sQuery);
90 if ($this->aExcludePlaceIDs) {
91 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
94 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
95 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
96 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
98 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
99 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
100 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
101 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
102 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
104 if ($this->fPolygonSimplificationThreshold > 0.0) {
105 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
108 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
109 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
111 if ($this->aCountryCodes) {
112 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
115 if ($this->aViewBox) {
116 $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
117 .','.$this->aViewBox[2].','.$this->aViewBox[1];
123 public function setIncludePolygonAsPoints($b = true)
125 $this->bIncludePolygonAsPoints = $b;
128 public function setIncludePolygonAsText($b = true)
130 $this->bIncludePolygonAsText = $b;
133 public function setIncludePolygonAsGeoJSON($b = true)
135 $this->bIncludePolygonAsGeoJSON = $b;
138 public function setIncludePolygonAsKML($b = true)
140 $this->bIncludePolygonAsKML = $b;
143 public function setIncludePolygonAsSVG($b = true)
145 $this->bIncludePolygonAsSVG = $b;
148 public function setPolygonSimplificationThreshold($f)
150 $this->fPolygonSimplificationThreshold = $f;
153 public function setLimit($iLimit = 10)
155 if ($iLimit > 50) $iLimit = 50;
156 if ($iLimit < 1) $iLimit = 1;
158 $this->iFinalLimit = $iLimit;
159 $this->iLimit = $iLimit + min($iLimit, 10);
162 public function setFeatureType($sFeatureType)
164 switch ($sFeatureType) {
166 $this->setRankRange(4, 4);
169 $this->setRankRange(8, 8);
172 $this->setRankRange(14, 16);
175 $this->setRankRange(8, 20);
180 public function setRankRange($iMin, $iMax)
182 $this->iMinAddressRank = $iMin;
183 $this->iMaxAddressRank = $iMax;
186 public function setRoute($aRoutePoints, $fRouteWidth)
188 $this->aViewBox = false;
190 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
192 foreach ($aRoutePoints as $aPoint) {
193 $fPoint = (float)$aPoint;
194 $this->sViewboxCentreSQL .= $sSep.$fPoint;
195 $sSep = ($sSep == ' ') ? ',' : ' ';
197 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
199 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
200 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
202 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
203 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
206 public function setViewbox($aViewbox)
208 $this->aViewBox = array_map('floatval', $aViewbox);
210 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
211 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
212 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
213 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
215 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
216 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
218 userError("Bad parameter 'viewbox'. Not a box.");
221 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
222 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
223 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
224 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
225 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
226 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
228 $this->sViewboxCentreSQL = false;
229 $this->sViewboxSmallSQL = sprintf(
230 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
236 $this->sViewboxLargeSQL = sprintf(
237 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
245 public function setQuery($sQueryString)
247 $this->sQuery = $sQueryString;
248 $this->aStructuredQuery = false;
251 public function getQueryString()
253 return $this->sQuery;
257 public function loadParamArray($oParams)
259 $this->bIncludeAddressDetails
260 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
261 $this->bIncludeExtraTags
262 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
263 $this->bIncludeNameDetails
264 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
266 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
267 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
269 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
270 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
272 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
274 // List of excluded Place IDs - used for more acurate pageing
275 $sExcluded = $oParams->getStringList('exclude_place_ids');
277 foreach ($sExcluded as $iExcludedPlaceID) {
278 $iExcludedPlaceID = (int)$iExcludedPlaceID;
279 if ($iExcludedPlaceID)
280 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
283 if (isset($aExcludePlaceIDs))
284 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
287 // Only certain ranks of feature
288 $sFeatureType = $oParams->getString('featureType');
289 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
290 if ($sFeatureType) $this->setFeatureType($sFeatureType);
293 $sCountries = $oParams->getStringList('countrycodes');
295 foreach ($sCountries as $sCountryCode) {
296 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
297 $aCountries[] = strtolower($sCountryCode);
300 if (isset($aCountries))
301 $this->aCountryCodes = $aCountries;
304 $aViewbox = $oParams->getStringList('viewboxlbrt');
306 if (count($aViewbox) != 4) {
307 userError("Bad parmater 'viewboxlbrt'. Expected 4 coordinates.");
309 $this->setViewbox($aViewbox);
311 $aViewbox = $oParams->getStringList('viewbox');
313 if (count($aViewbox) != 4) {
314 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
316 $this->setViewBox($aViewbox);
318 $aRoute = $oParams->getStringList('route');
319 $fRouteWidth = $oParams->getFloat('routewidth');
320 if ($aRoute && $fRouteWidth) {
321 $this->setRoute($aRoute, $fRouteWidth);
327 public function setQueryFromParams($oParams)
330 $sQuery = $oParams->getString('q');
332 $this->setStructuredQuery(
333 $oParams->getString('amenity'),
334 $oParams->getString('street'),
335 $oParams->getString('city'),
336 $oParams->getString('county'),
337 $oParams->getString('state'),
338 $oParams->getString('country'),
339 $oParams->getString('postalcode')
341 $this->setReverseInPlan(false);
343 $this->setQuery($sQuery);
347 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
349 $sValue = trim($sValue);
350 if (!$sValue) return false;
351 $this->aStructuredQuery[$sKey] = $sValue;
352 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
353 $this->iMinAddressRank = $iNewMinAddressRank;
354 $this->iMaxAddressRank = $iNewMaxAddressRank;
356 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
360 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
362 $this->sQuery = false;
365 $this->iMinAddressRank = 0;
366 $this->iMaxAddressRank = 30;
367 $this->aAddressRankList = array();
369 $this->aStructuredQuery = array();
370 $this->sAllowedTypesSQLList = False;
372 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
373 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
374 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
375 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
376 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
377 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
378 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
380 if (sizeof($this->aStructuredQuery) > 0) {
381 $this->sQuery = join(', ', $this->aStructuredQuery);
382 if ($this->iMaxAddressRank < 30) {
383 $this->sAllowedTypesSQLList = '(\'place\',\'boundary\')';
388 public function fallbackStructuredQuery()
390 if (!$this->aStructuredQuery) return false;
392 $aParams = $this->aStructuredQuery;
394 if (sizeof($aParams) == 1) return false;
396 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
398 foreach ($aOrderToFallback as $sType) {
399 if (isset($aParams[$sType])) {
400 unset($aParams[$sType]);
401 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
409 public function getDetails($aPlaceIDs)
411 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
412 if (sizeof($aPlaceIDs) == 0) return array();
414 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
416 // Get the details for display (is this a redundant extra step?)
417 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
419 $sImportanceSQL = '';
420 $sImportanceSQLGeom = '';
421 if ($this->sViewboxSmallSQL) {
422 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
423 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, geometry) THEN 1 ELSE 0.75 END * ";
425 if ($this->sViewboxLargeSQL) {
426 $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
427 $sImportanceSQLGeom .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, geometry) THEN 1 ELSE 0.75 END * ";
431 $sSQL .= " osm_type,";
435 $sSQL .= " admin_level,";
436 $sSQL .= " rank_search,";
437 $sSQL .= " rank_address,";
438 $sSQL .= " min(place_id) AS place_id, ";
439 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
440 $sSQL .= " country_code, ";
441 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
442 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
443 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
444 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
445 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
446 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
447 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
448 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
450 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
452 $sSQL .= " place_addressline s, ";
453 $sSQL .= " placex p";
454 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
455 $sSQL .= " AND p.place_id = s.address_place_id ";
456 $sSQL .= " AND s.isaddress ";
457 $sSQL .= " AND p.importance is not null ";
458 $sSQL .= " ) AS addressimportance, ";
459 $sSQL .= " (extratags->'place') AS extra_place ";
460 $sSQL .= " FROM placex";
461 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
463 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
464 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
465 $sSQL .= " OR (extratags->'place') = 'city'";
467 if ($this->aAddressRankList) {
468 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
471 if ($this->sAllowedTypesSQLList) {
472 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
474 $sSQL .= " AND linked_place_id is null ";
475 $sSQL .= " GROUP BY ";
476 $sSQL .= " osm_type, ";
477 $sSQL .= " osm_id, ";
480 $sSQL .= " admin_level, ";
481 $sSQL .= " rank_search, ";
482 $sSQL .= " rank_address, ";
483 $sSQL .= " country_code, ";
484 $sSQL .= " importance, ";
485 if (!$this->bDeDupe) $sSQL .= "place_id,";
486 $sSQL .= " langaddress, ";
487 $sSQL .= " placename, ";
489 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
490 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
491 $sSQL .= " extratags->'place' ";
496 $sSQL .= " 'P' as osm_type,";
497 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = lp.parent_place_id) as osm_id,";
498 $sSQL .= " 'place' as class, 'postcode' as type,";
499 $sSQL .= " null as admin_level, rank_search, rank_address,";
500 $sSQL .= " place_id, parent_place_id, country_code,";
501 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
502 $sSQL .= " postcode as placename,";
503 $sSQL .= " postcode as ref,";
504 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
505 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
506 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
507 $sSQL .= $sImportanceSQLGeom."(0.75-(rank_search::float/40)) AS importance, ";
509 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
511 $sSQL .= " place_addressline s, ";
512 $sSQL .= " placex p";
513 $sSQL .= " WHERE s.place_id = lp.parent_place_id";
514 $sSQL .= " AND p.place_id = s.address_place_id ";
515 $sSQL .= " AND s.isaddress";
516 $sSQL .= " AND p.importance is not null";
517 $sSQL .= " ) AS addressimportance, ";
518 $sSQL .= " null AS extra_place ";
519 $sSQL .= "FROM location_postcode lp";
520 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
522 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
523 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
524 // with start- and endnumber, the common osm housenumbers are usually saved as points
527 $length = count($aPlaceIDs);
528 foreach ($aPlaceIDs as $placeID => $housenumber) {
530 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
531 if ($i<$length) $sHousenumbers .= ", ";
534 if (CONST_Use_US_Tiger_Data) {
535 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
538 $sSQL .= " 'T' AS osm_type, ";
539 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
540 $sSQL .= " 'place' AS class, ";
541 $sSQL .= " 'house' AS type, ";
542 $sSQL .= " null AS admin_level, ";
543 $sSQL .= " 30 AS rank_search, ";
544 $sSQL .= " 30 AS rank_address, ";
545 $sSQL .= " min(place_id) AS place_id, ";
546 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
547 $sSQL .= " 'us' AS country_code, ";
548 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
549 $sSQL .= " null AS placename, ";
550 $sSQL .= " null AS ref, ";
551 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
552 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
553 $sSQL .= " avg(st_x(centroid)) AS lon, ";
554 $sSQL .= " avg(st_y(centroid)) AS lat,";
555 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
557 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
559 $sSQL .= " place_addressline s, ";
560 $sSQL .= " placex p";
561 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
562 $sSQL .= " AND p.place_id = s.address_place_id ";
563 $sSQL .= " AND s.isaddress";
564 $sSQL .= " AND p.importance is not null";
565 $sSQL .= " ) AS addressimportance, ";
566 $sSQL .= " null AS extra_place ";
568 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
569 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
570 $sSQL .= " parent_place_id, ";
571 $sSQL .= " housenumber_for_place";
573 $sSQL .= " location_property_tiger ";
574 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
576 $sSQL .= " housenumber_for_place>=0";
577 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
578 $sSQL .= " ) AS blub"; //postgres wants an alias here
579 $sSQL .= " GROUP BY";
580 $sSQL .= " place_id, ";
581 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
582 if (!$this->bDeDupe) $sSQL .= ", place_id ";
585 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
588 $sSQL .= " 'W' AS osm_type, ";
589 $sSQL .= " osm_id, ";
590 $sSQL .= " 'place' AS class, ";
591 $sSQL .= " 'house' AS type, ";
592 $sSQL .= " null AS admin_level, ";
593 $sSQL .= " 30 AS rank_search, ";
594 $sSQL .= " 30 AS rank_address, ";
595 $sSQL .= " min(place_id) as place_id, ";
596 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
597 $sSQL .= " country_code, ";
598 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
599 $sSQL .= " null AS placename, ";
600 $sSQL .= " null AS ref, ";
601 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
602 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
603 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
604 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
605 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
608 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
610 $sSQL .= " place_addressline s, ";
611 $sSQL .= " placex p";
612 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
613 $sSQL .= " AND p.place_id = s.address_place_id ";
614 $sSQL .= " AND s.isaddress ";
615 $sSQL .= " AND p.importance is not null";
616 $sSQL .= " ) AS addressimportance,";
617 $sSQL .= " null AS extra_place ";
620 $sSQL .= " osm_id, ";
621 $sSQL .= " place_id, ";
622 $sSQL .= " country_code, ";
623 $sSQL .= " CASE "; // interpolate the housenumbers here
624 $sSQL .= " WHEN startnumber != endnumber ";
625 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
626 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
627 $sSQL .= " END as centroid, ";
628 $sSQL .= " parent_place_id, ";
629 $sSQL .= " housenumber_for_place ";
631 $sSQL .= " location_property_osmline ";
632 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
634 $sSQL .= " WHERE housenumber_for_place>=0 ";
635 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
636 $sSQL .= " ) as blub"; //postgres wants an alias here
637 $sSQL .= " GROUP BY ";
638 $sSQL .= " osm_id, ";
639 $sSQL .= " place_id, ";
640 $sSQL .= " housenumber_for_place, ";
641 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
642 if (!$this->bDeDupe) $sSQL .= ", place_id ";
644 if (CONST_Use_Aux_Location_data) {
647 $sSQL .= " 'L' AS osm_type, ";
648 $sSQL .= " place_id AS osm_id, ";
649 $sSQL .= " 'place' AS class,";
650 $sSQL .= " 'house' AS type, ";
651 $sSQL .= " null AS admin_level, ";
652 $sSQL .= " 0 AS rank_search,";
653 $sSQL .= " 0 AS rank_address, ";
654 $sSQL .= " min(place_id) AS place_id,";
655 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
656 $sSQL .= " 'us' AS country_code, ";
657 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
658 $sSQL .= " null AS placename, ";
659 $sSQL .= " null AS ref, ";
660 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
661 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
662 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
663 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
664 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
666 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
668 $sSQL .= " place_addressline s, ";
669 $sSQL .= " placex p";
670 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
671 $sSQL .= " AND p.place_id = s.address_place_id ";
672 $sSQL .= " AND s.isaddress";
673 $sSQL .= " AND p.importance is not null";
674 $sSQL .= " ) AS addressimportance, ";
675 $sSQL .= " null AS extra_place ";
676 $sSQL .= " FROM location_property_aux ";
677 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
678 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
679 $sSQL .= " GROUP BY ";
680 $sSQL .= " place_id, ";
681 if (!$this->bDeDupe) $sSQL .= "place_id, ";
682 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
686 $sSQL .= " order by importance desc";
691 $aSearchResults = chksql(
692 $this->oDB->getAll($sSQL),
693 "Could not get details for place."
696 return $aSearchResults;
699 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
702 Calculate all searches using aValidTokens i.e.
703 'Wodsworth Road, Sheffield' =>
707 0 1 (wodsworth)(road)
710 Score how good the search is so they can be ordered
714 foreach ($aPhrases as $iPhrase => $aPhrase) {
715 $aNewPhraseSearches = array();
716 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
717 else $sPhraseType = '';
719 foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
720 // Too many permutations - too expensive
721 if ($iWordSet > 120) break;
723 $aWordsetSearches = $aSearches;
725 // Add all words from this wordset
726 foreach ($aWordset as $iToken => $sToken) {
727 //echo "<br><b>$sToken</b>";
728 $aNewWordsetSearches = array();
730 foreach ($aWordsetSearches as $aCurrentSearch) {
732 //var_dump($aCurrentSearch);
735 // If the token is valid
736 if (isset($aValidTokens[' '.$sToken])) {
737 // TODO variable should go into aCurrentSearch
738 $bHavePostcode = false;
739 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
740 $aSearch = $aCurrentSearch;
741 $aSearch['iSearchRank']++;
742 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
743 if ($aSearch['sCountryCode'] === false) {
744 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
745 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
746 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
747 $aSearch['iSearchRank'] += 5;
749 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
750 // If it is at the beginning, we can be almost sure that this is the wrong order
751 // Increase score for all searches.
752 if ($iToken == 0 && $iPhrase == 0) {
756 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode') {
757 // 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
758 if ($aSearch['sPostcode'] === '' &&
759 isset($aSearchTerm['word']) && $aSearchTerm['word'] && strpos($sNormQuery, $this->normTerm($aSearchTerm['word'])) !== false) {
760 // If we have structured search or this is the first term,
761 // make the postcode the primary search element.
762 if (!$bHavePostcode && $aSearch['sOperator'] === '' && ($sPhraseType == 'postalcode' || ($iToken == 0 && $iPhrase == 0))) {
763 $aNewSearch = $aSearch;
764 $aNewSearch['sOperator'] = 'postcode';
765 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
766 $aNewSearch['aName'] = array($aSearchTerm['word_id'] => $aSearchTerm['word']);
767 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
768 $bHavePostcode = true;
771 // If we have a structured search or this is not the first term,
772 // add the postcode as an addendum.
773 if ($aSearch['sOperator'] !== 'postcode' && ($sPhraseType == 'postalcode' || sizeof($aSearch['aName']))) {
774 $aSearch['sPostcode'] = $aSearchTerm['word'];
775 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
778 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
779 if ($aSearch['sHouseNumber'] === '' && $aSearch['sOperator'] !== 'postcode') {
780 $aSearch['sHouseNumber'] = $sToken;
781 // sanity check: if the housenumber is not mainly made
782 // up of numbers, add a penalty
783 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
784 // also must not appear in the middle of the address
785 if ($aSearch['aAddress'] || $aSearch['aAddressNonSearch']) $aSearch['iSearchRank'] += 1;
786 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
788 // Fall back to not searching for this item (better than nothing)
789 $aSearch = $aCurrentSearch;
790 $aSearch['iSearchRank'] += 1;
791 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
794 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
795 // require a normalized exact match of the term
796 // if we have the normalizer version of the query
798 if ($aSearch['sOperator'] === ''
799 && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
800 $aSearch['sClass'] = $aSearchTerm['class'];
801 $aSearch['sType'] = $aSearchTerm['type'];
802 if ($aSearchTerm['operator'] == '') {
803 $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' : 'near';
804 $aSearch['iSearchRank'] += 2;
806 $aSearch['sOperator'] = 'near'; // near = in for the moment
809 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
811 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
812 if (sizeof($aSearch['aName'])) {
813 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
814 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
816 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
817 $aSearch['iSearchRank'] += 1000; // skip;
820 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
821 //$aSearch['iNamePhrase'] = $iPhrase;
823 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
827 // Look for partial matches.
828 // Note that there is no point in adding country terms here
829 // because country are omitted in the address.
830 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
831 // Allow searching for a word - but at extra cost
832 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
833 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
834 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
835 $aSearch = $aCurrentSearch;
836 $aSearch['iSearchRank'] += 1;
837 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
838 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
839 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
840 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
841 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
842 $aSearch['iSearchRank'] += 1;
843 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
844 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
845 if (empty($aSearchTermToken['country_code'])
846 && empty($aSearchTermToken['lat'])
847 && empty($aSearchTermToken['class'])
849 $aSearch = $aCurrentSearch;
850 $aSearch['iSearchRank'] += 1;
851 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
852 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
856 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
857 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
858 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
862 if ((!$aCurrentSearch['sPostcode'] && !$aCurrentSearch['aAddress'] && !$aCurrentSearch['aAddressNonSearch'])
863 && (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase)) {
864 $aSearch = $aCurrentSearch;
865 $aSearch['iSearchRank'] += 1;
866 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
867 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
868 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
869 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
871 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
873 $aSearch['iNamePhrase'] = $iPhrase;
874 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
879 // Allow skipping a word - but at EXTREAM cost
880 //$aSearch = $aCurrentSearch;
881 //$aSearch['iSearchRank']+=100;
882 //$aNewWordsetSearches[] = $aSearch;
886 usort($aNewWordsetSearches, 'bySearchRank');
887 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
889 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
891 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
892 usort($aNewPhraseSearches, 'bySearchRank');
894 $aSearchHash = array();
895 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
896 $sHash = serialize($aSearch);
897 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
898 else $aSearchHash[$sHash] = 1;
901 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
904 // Re-group the searches by their score, junk anything over 20 as just not worth trying
905 $aGroupedSearches = array();
906 foreach ($aNewPhraseSearches as $aSearch) {
907 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
908 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
909 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
912 ksort($aGroupedSearches);
915 $aSearches = array();
916 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
917 $iSearchCount += sizeof($aNewSearches);
918 $aSearches = array_merge($aSearches, $aNewSearches);
919 if ($iSearchCount > 50) break;
922 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
925 // Revisit searches, drop bad searches and give penalty to unlikely combinations.
926 $aGroupedSearches = array();
927 foreach ($aSearches as $aSearch) {
928 if (!$aSearch['aName']) {
929 if ($aSearch['sHouseNumber']) {
933 if ($this->aCountryCodes && $aSearch['sCountryCode']
934 && !in_array($aSearch['sCountryCode'], $this->aCountryCodes)) {
938 $aSearch['iSearchRank'] += $iGlobalRank;
939 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
941 ksort($aGroupedSearches);
943 return $aGroupedSearches;
946 /* Perform the actual query lookup.
948 Returns an ordered list of results, each with the following fields:
949 osm_type: type of corresponding OSM object
953 P - postcode (internally computed)
954 osm_id: id of corresponding OSM object
955 class: general object class (corresponds to tag key of primary OSM tag)
956 type: subclass of object (corresponds to tag value of primary OSM tag)
957 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
958 rank_search: rank in search hierarchy
959 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
960 rank_address: rank in address hierarchy (determines orer in address)
961 place_id: internal key (may differ between different instances)
962 country_code: ISO country code
963 langaddress: localized full address
964 placename: localized name of object
965 ref: content of ref tag (if available)
968 importance: importance of place based on Wikipedia link count
969 addressimportance: cumulated importance of address elements
970 extra_place: type of place (for admin boundaries, if there is a place tag)
971 aBoundingBox: bounding Box
972 label: short description of the object class/type (English only)
973 name: full name (currently the same as langaddress)
974 foundorder: secondary ordering for places with same importance
978 public function lookup()
980 if (!$this->sQuery && !$this->aStructuredQuery) return array();
982 $sNormQuery = $this->normTerm($this->sQuery);
983 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
984 $sCountryCodesSQL = false;
985 if ($this->aCountryCodes) {
986 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
989 $sQuery = $this->sQuery;
990 if (!preg_match('//u', $sQuery)) {
991 userError("Query string is not UTF-8 encoded.");
994 // Conflicts between US state abreviations and various words for 'the' in different languages
995 if (isset($this->aLangPrefOrder['name:en'])) {
996 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
997 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
998 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
1001 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
1002 if ($this->sViewboxCentreSQL) {
1003 // For complex viewboxes (routes) precompute the bounding geometry
1005 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
1006 "Could not get small viewbox"
1008 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
1011 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
1012 "Could not get large viewbox"
1014 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
1017 // Do we have anything that looks like a lat/lon pair?
1018 $oNearPoint = false;
1019 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
1020 $oNearPoint = $aLooksLike['pt'];
1021 $sQuery = $aLooksLike['query'];
1024 $aSearchResults = array();
1025 if ($sQuery || $this->aStructuredQuery) {
1026 // Start with a single blank search
1027 $aSearches = array(new SearchDescription());
1030 $aSearches[0]->setNear($oNearPoint);
1034 $sQuery = $aSearches[0]->extractKeyValuePairs($sQuery);
1040 '/\\[([\\w ]*)\\]/u',
1045 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1046 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1047 if (!$sSpecialTerm) {
1048 $sSpecialTerm = $aSpecialTerm[1];
1052 if (!$sSpecialTerm && $this->aStructuredQuery
1053 && isset($this->aStructuredQuery['amenity'])) {
1054 $sSpecialTerm = $this->aStructuredQuery['amenity'];
1055 unset($this->aStructuredQuery['amenity']);
1058 if ($sSpecialTerm && !$aSearches[0]->hasOperator()) {
1059 $sSpecialTerm = pg_escape_string($sSpecialTerm);
1061 $this->oDB->getOne("SELECT make_standard_name('$sSpecialTerm')"),
1062 "Cannot decode query. Wrong encoding?"
1064 $sSQL = 'SELECT class, type FROM word ';
1065 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
1066 $sSQL .= ' AND class is not null AND class not in (\'place\')';
1067 if (CONST_Debug) var_Dump($sSQL);
1068 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1069 $aNewSearches = array();
1070 foreach ($aSearches as $oSearch) {
1071 foreach ($aSearchWords as $aSearchTerm) {
1072 $oNewSearch = clone $oSearch;
1073 $oNewSearch->setPoiSearch(
1075 $aSearchTerm['class'],
1076 $aSearchTerm['type'],
1078 $aNewSearches[] = $oNewSearch;
1081 $aSearches = $aNewSearches;
1084 // Split query into phrases
1085 // Commas are used to reduce the search space by indicating where phrases split
1086 if ($this->aStructuredQuery) {
1087 $aPhrases = $this->aStructuredQuery;
1088 $bStructuredPhrases = true;
1090 $aPhrases = explode(',', $sQuery);
1091 $bStructuredPhrases = false;
1094 // Convert each phrase to standard form
1095 // Create a list of standard words
1096 // Get all 'sets' of words
1097 // Generate a complete list of all
1099 foreach ($aPhrases as $iPhrase => $sPhrase) {
1101 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1102 "Cannot normalize query string (is it a UTF-8 string?)"
1104 if (trim($aPhrase['string'])) {
1105 $aPhrases[$iPhrase] = $aPhrase;
1106 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1107 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1108 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1110 unset($aPhrases[$iPhrase]);
1114 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1115 $aPhraseTypes = array_keys($aPhrases);
1116 $aPhrases = array_values($aPhrases);
1118 if (sizeof($aTokens)) {
1119 // Check which tokens we have, get the ID numbers
1120 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1121 $sSQL .= ' FROM word ';
1122 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1124 if (CONST_Debug) var_Dump($sSQL);
1126 $aValidTokens = array();
1127 $aDatabaseWords = chksql(
1128 $this->oDB->getAll($sSQL),
1129 "Could not get word tokens."
1131 $aPossibleMainWordIDs = array();
1132 $aWordFrequencyScores = array();
1133 foreach ($aDatabaseWords as $aToken) {
1134 // Very special case - require 2 letter country param to match the country code found
1135 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1136 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1141 if (isset($aValidTokens[$aToken['word_token']])) {
1142 $aValidTokens[$aToken['word_token']][] = $aToken;
1144 $aValidTokens[$aToken['word_token']] = array($aToken);
1146 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1147 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1149 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1151 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1152 foreach ($aTokens as $sToken) {
1153 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1154 if (isset($aValidTokens[$aData[1]])) {
1155 foreach ($aValidTokens[$aData[1]] as $aToken) {
1156 if (!$aToken['class']) {
1157 if (isset($aValidTokens[$sToken])) {
1158 $aValidTokens[$sToken][] = $aToken;
1160 $aValidTokens[$sToken] = array($aToken);
1168 foreach ($aTokens as $sToken) {
1169 // Unknown single word token with a number - assume it is a house number
1170 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1171 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1175 // Any words that have failed completely?
1176 // TODO: suggestions
1178 // Start the search process
1179 // array with: placeid => -1 | tiger-housenumber
1180 $aResultPlaceIDs = array();
1182 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1184 if ($this->bReverseInPlan) {
1185 // Reverse phrase array and also reverse the order of the wordsets in
1186 // the first and final phrase. Don't bother about phrases in the middle
1187 // because order in the address doesn't matter.
1188 $aPhrases = array_reverse($aPhrases);
1189 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1190 if (sizeof($aPhrases) > 1) {
1191 $aFinalPhrase = end($aPhrases);
1192 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1194 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1196 foreach ($aGroupedSearches as $aSearches) {
1197 foreach ($aSearches as $aSearch) {
1198 if (!isset($aReverseGroupedSearches[$aSearch->getRank()])) {
1199 $aReverseGroupedSearches[$aSearch->getRank()] = array();
1201 $aReverseGroupedSearches[$aSearch->getRank()][] = $aSearch;
1205 $aGroupedSearches = $aReverseGroupedSearches;
1206 ksort($aGroupedSearches);
1209 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1210 $aGroupedSearches = array();
1211 foreach ($aSearches as $aSearch) {
1212 if ($aSearch->getRank() < $this->iMaxRank) {
1213 if (!isset($aGroupedSearches[$aSearch->getRank()])) $aGroupedSearches[$aSearch->getRank()] = array();
1214 $aGroupedSearches[$aSearch->getRank()][] = $aSearch;
1217 ksort($aGroupedSearches);
1220 // Filter out duplicate searches
1221 $aSearchHash = array();
1222 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1223 foreach ($aSearches as $iSearch => $aSearch) {
1224 $sHash = serialize($aSearch);
1225 if (isset($aSearchHash[$sHash])) {
1226 unset($aGroupedSearches[$iGroup][$iSearch]);
1227 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1229 $aSearchHash[$sHash] = 1;
1234 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1238 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1240 foreach ($aSearches as $oSearch) {
1242 $searchedHousenumber = -1;
1244 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1245 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($oSearch)), $aValidTokens);
1247 $aPlaceIDs = array();
1248 if ($oSearch->isCountrySearch()) {
1249 // Just looking for a country - look it up
1250 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1251 $aPlaceIDs = $oSearch->queryCountry(
1253 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : ''
1256 } elseif (!$oSearch->isNamedSearch()) {
1257 // looking for a POI in a geographic area
1258 if (!$bBoundingBoxSearch && !$oSearch->isNearSearch()) {
1262 $aPlaceIDs = $oSearch->queryNearbyPoi(
1265 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1267 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1270 } elseif ($oSearch->isOperator(Operator::POSTCODE)) {
1271 $aPlaceIDs = $oSearch->queryPostcode(
1278 // First search for places according to name and address.
1279 $aNamedPlaceIDs = $oSearch->queryNamedPlace(
1281 $aWordFrequencyScores,
1283 $this->iMinAddressRank,
1284 $this->iMaxAddressRank,
1285 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : '',
1286 $bBoundingBoxSearch ? $this->sViewboxSmallSQL : '',
1287 $bBoundingBoxSearch ? $this->sViewboxLargeSQL : '',
1291 if (sizeof($aNamedPlaceIDs)) {
1292 foreach ($aNamedPlaceIDs as $aRow) {
1293 $aPlaceIDs[] = $aRow['place_id'];
1294 $this->exactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
1298 //now search for housenumber, if housenumber provided
1299 if ($oSearch->hasHouseNumber() && sizeof($aPlaceIDs)) {
1300 $aResult = $oSearch->queryHouseNumber(
1303 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : ''
1307 if (sizeof($aResult)) {
1308 $searchedHousenumber = $aResult['iHouseNumber'];
1309 $aPlaceIDs = $aResults['aPlaceIDs'];
1310 } elseif (!$oSearch->looksLikeFullAddress()) {
1311 $aPlaceIDs = array();
1315 // finally get POIs if requested
1316 if ($oSearch->isPoiSearch() && sizeof($aPlaceIDs)) {
1317 $aPlaceIDs = $oSearch->queryPoiByOperator(
1320 $this->aExcludePlaceIDs ? join(',', $this->aExcludePlaceIDs) : ''
1327 echo "<br><b>Place IDs:</b> ";
1328 var_Dump($aPlaceIDs);
1331 if (sizeof($aPlaceIDs) && $oSearch->getPostcode()) {
1332 $sSQL = 'SELECT place_id FROM placex';
1333 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1334 $sSQL .= " AND postcode = '".$oSearch->getPostcode()."'";
1335 if (CONST_Debug) var_dump($sSQL);
1336 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1337 if ($aFilteredPlaceIDs) {
1338 $aPlaceIDs = $aFilteredPlaceIDs;
1340 echo "<br><b>Place IDs after postcode filtering:</b> ";
1341 var_Dump($aPlaceIDs);
1346 foreach ($aPlaceIDs as $iPlaceID) {
1347 // array for placeID => -1 | Tiger housenumber
1348 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1350 if ($iQueryLoop > 20) break;
1353 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1354 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1355 // reduces the number of place ids, like a filter
1356 // rank_address is 30 for interpolated housenumbers
1357 $sWherePlaceId = 'WHERE place_id in (';
1358 $sWherePlaceId .= join(',', array_keys($aResultPlaceIDs)).') ';
1360 $sSQL = "SELECT place_id ";
1361 $sSQL .= "FROM placex ".$sWherePlaceId;
1363 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1364 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1365 $sSQL .= " OR (extratags->'place') = 'city'";
1367 if ($this->aAddressRankList) {
1368 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1370 $sSQL .= " ) UNION ";
1371 $sSQL .= " SELECT place_id FROM location_postcode lp ".$sWherePlaceId;
1372 $sSQL .= " AND (lp.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1373 if ($this->aAddressRankList) {
1374 $sSQL .= " OR lp.rank_address in (".join(',', $this->aAddressRankList).")";
1377 if (CONST_Use_US_Tiger_Data && $this->iMaxAddressRank == 30) {
1379 $sSQL .= " SELECT place_id ";
1380 $sSQL .= " FROM location_property_tiger ".$sWherePlaceId;
1382 if ($this->iMaxAddressRank == 30) {
1384 $sSQL .= " SELECT place_id ";
1385 $sSQL .= " FROM location_property_osmline ".$sWherePlaceId;
1387 if (CONST_Debug) var_dump($sSQL);
1388 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1390 foreach ($aFilteredPlaceIDs as $placeID) {
1391 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1393 $aResultPlaceIDs = $tempIDs;
1397 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1398 if ($iGroupLoop > 4) break;
1399 if ($iQueryLoop > 30) break;
1402 // Did we find anything?
1403 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1404 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1407 // Just interpret as a reverse geocode
1408 $oReverse = new ReverseGeocode($this->oDB);
1409 $oReverse->setZoom(18);
1411 $aLookup = $oReverse->lookup(
1417 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1419 if ($aLookup['place_id']) {
1420 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1421 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1423 $aSearchResults = array();
1428 if (!sizeof($aSearchResults)) {
1429 if ($this->bFallback) {
1430 if ($this->fallbackStructuredQuery()) {
1431 return $this->lookup();
1438 $aClassType = getClassTypesWithImportance();
1439 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1440 foreach ($aRecheckWords as $i => $sWord) {
1441 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1445 echo '<i>Recheck words:<\i>';
1446 var_dump($aRecheckWords);
1449 $oPlaceLookup = new PlaceLookup($this->oDB);
1450 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1451 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1452 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1453 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1454 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1455 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1457 foreach ($aSearchResults as $iResNum => $aResult) {
1459 $fDiameter = getResultDiameter($aResult);
1461 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1462 if ($aOutlineResult) {
1463 $aResult = array_merge($aResult, $aOutlineResult);
1466 if ($aResult['extra_place'] == 'city') {
1467 $aResult['class'] = 'place';
1468 $aResult['type'] = 'city';
1469 $aResult['rank_search'] = 16;
1472 // Is there an icon set for this type of result?
1473 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1474 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1476 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1479 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1480 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1482 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1483 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1484 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1486 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1488 // if tag '&addressdetails=1' is set in query
1489 if ($this->bIncludeAddressDetails) {
1490 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1491 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1492 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1493 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1497 if ($this->bIncludeExtraTags) {
1498 if ($aResult['extra']) {
1499 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1501 $aResult['sExtraTags'] = (object) array();
1505 if ($this->bIncludeNameDetails) {
1506 if ($aResult['names']) {
1507 $aResult['sNameDetails'] = json_decode($aResult['names']);
1509 $aResult['sNameDetails'] = (object) array();
1513 // Adjust importance for the number of exact string matches in the result
1514 $aResult['importance'] = max(0.001, $aResult['importance']);
1516 $sAddress = $aResult['langaddress'];
1517 foreach ($aRecheckWords as $i => $sWord) {
1518 if (stripos($sAddress, $sWord)!==false) {
1520 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1524 $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
1526 $aResult['name'] = $aResult['langaddress'];
1527 // secondary ordering (for results with same importance (the smaller the better):
1528 // - approximate importance of address parts
1529 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1530 // - number of exact matches from the query
1531 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1532 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1533 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1534 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1536 // - importance of the class/type
1537 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1538 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1540 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1542 $aResult['foundorder'] += 0.01;
1544 if (CONST_Debug) var_dump($aResult);
1545 $aSearchResults[$iResNum] = $aResult;
1547 uasort($aSearchResults, 'byImportance');
1549 $aOSMIDDone = array();
1550 $aClassTypeNameDone = array();
1551 $aToFilter = $aSearchResults;
1552 $aSearchResults = array();
1555 foreach ($aToFilter as $iResNum => $aResult) {
1556 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1558 $fLat = $aResult['lat'];
1559 $fLon = $aResult['lon'];
1560 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1563 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1564 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1566 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1567 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1568 $aSearchResults[] = $aResult;
1571 // Absolute limit on number of results
1572 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1575 return $aSearchResults;