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' ";
479 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
480 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
481 // with start- and endnumber, the common osm housenumbers are usually saved as points
484 $length = count($aPlaceIDs);
485 foreach ($aPlaceIDs as $placeID => $housenumber) {
487 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
488 if ($i<$length) $sHousenumbers .= ", ";
491 if (CONST_Use_US_Tiger_Data) {
492 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
495 $sSQL .= " 'T' AS osm_type, ";
496 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
497 $sSQL .= " 'place' AS class, ";
498 $sSQL .= " 'house' AS type, ";
499 $sSQL .= " null AS admin_level, ";
500 $sSQL .= " 30 AS rank_search, ";
501 $sSQL .= " 30 AS rank_address, ";
502 $sSQL .= " min(place_id) AS place_id, ";
503 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
504 $sSQL .= " 'us' AS country_code, ";
505 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
506 $sSQL .= " null AS placename, ";
507 $sSQL .= " null AS ref, ";
508 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
509 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
510 $sSQL .= " avg(st_x(centroid)) AS lon, ";
511 $sSQL .= " avg(st_y(centroid)) AS lat,";
512 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
514 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
516 $sSQL .= " place_addressline s, ";
517 $sSQL .= " placex p";
518 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
519 $sSQL .= " AND p.place_id = s.address_place_id ";
520 $sSQL .= " AND s.isaddress";
521 $sSQL .= " AND p.importance is not null";
522 $sSQL .= " ) AS addressimportance, ";
523 $sSQL .= " null AS extra_place ";
525 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
526 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
527 $sSQL .= " parent_place_id, ";
528 $sSQL .= " housenumber_for_place";
530 $sSQL .= " location_property_tiger ";
531 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
533 $sSQL .= " housenumber_for_place>=0";
534 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
535 $sSQL .= " ) AS blub"; //postgres wants an alias here
536 $sSQL .= " GROUP BY";
537 $sSQL .= " place_id, ";
538 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
539 if (!$this->bDeDupe) $sSQL .= ", place_id ";
542 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
545 $sSQL .= " 'W' AS osm_type, ";
546 $sSQL .= " osm_id, ";
547 $sSQL .= " 'place' AS class, ";
548 $sSQL .= " 'house' AS type, ";
549 $sSQL .= " null AS admin_level, ";
550 $sSQL .= " 30 AS rank_search, ";
551 $sSQL .= " 30 AS rank_address, ";
552 $sSQL .= " min(place_id) as place_id, ";
553 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
554 $sSQL .= " country_code, ";
555 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
556 $sSQL .= " null AS placename, ";
557 $sSQL .= " null AS ref, ";
558 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
559 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
560 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
561 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
562 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
565 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
567 $sSQL .= " place_addressline s, ";
568 $sSQL .= " placex p";
569 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
570 $sSQL .= " AND p.place_id = s.address_place_id ";
571 $sSQL .= " AND s.isaddress ";
572 $sSQL .= " AND p.importance is not null";
573 $sSQL .= " ) AS addressimportance,";
574 $sSQL .= " null AS extra_place ";
577 $sSQL .= " osm_id, ";
578 $sSQL .= " place_id, ";
579 $sSQL .= " country_code, ";
580 $sSQL .= " CASE "; // interpolate the housenumbers here
581 $sSQL .= " WHEN startnumber != endnumber ";
582 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
583 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
584 $sSQL .= " END as centroid, ";
585 $sSQL .= " parent_place_id, ";
586 $sSQL .= " housenumber_for_place ";
588 $sSQL .= " location_property_osmline ";
589 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
591 $sSQL .= " WHERE housenumber_for_place>=0 ";
592 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
593 $sSQL .= " ) as blub"; //postgres wants an alias here
594 $sSQL .= " GROUP BY ";
595 $sSQL .= " osm_id, ";
596 $sSQL .= " place_id, ";
597 $sSQL .= " housenumber_for_place, ";
598 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
599 if (!$this->bDeDupe) $sSQL .= ", place_id ";
601 if (CONST_Use_Aux_Location_data) {
604 $sSQL .= " 'L' AS osm_type, ";
605 $sSQL .= " place_id AS osm_id, ";
606 $sSQL .= " 'place' AS class,";
607 $sSQL .= " 'house' AS type, ";
608 $sSQL .= " null AS admin_level, ";
609 $sSQL .= " 0 AS rank_search,";
610 $sSQL .= " 0 AS rank_address, ";
611 $sSQL .= " min(place_id) AS place_id,";
612 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
613 $sSQL .= " 'us' AS country_code, ";
614 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
615 $sSQL .= " null AS placename, ";
616 $sSQL .= " null AS ref, ";
617 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
618 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
619 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
620 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
621 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
623 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
625 $sSQL .= " place_addressline s, ";
626 $sSQL .= " placex p";
627 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
628 $sSQL .= " AND p.place_id = s.address_place_id ";
629 $sSQL .= " AND s.isaddress";
630 $sSQL .= " AND p.importance is not null";
631 $sSQL .= " ) AS addressimportance, ";
632 $sSQL .= " null AS extra_place ";
633 $sSQL .= " FROM location_property_aux ";
634 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
635 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
636 $sSQL .= " GROUP BY ";
637 $sSQL .= " place_id, ";
638 if (!$this->bDeDupe) $sSQL .= "place_id, ";
639 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
643 $sSQL .= " order by importance desc";
648 $aSearchResults = chksql(
649 $this->oDB->getAll($sSQL),
650 "Could not get details for place."
653 return $aSearchResults;
656 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
659 Calculate all searches using aValidTokens i.e.
660 'Wodsworth Road, Sheffield' =>
664 0 1 (wodsworth)(road)
667 Score how good the search is so they can be ordered
669 foreach ($aPhrases as $iPhrase => $sPhrase) {
670 $aNewPhraseSearches = array();
671 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
672 else $sPhraseType = '';
674 foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
675 // Too many permutations - too expensive
676 if ($iWordSet > 120) break;
678 $aWordsetSearches = $aSearches;
680 // Add all words from this wordset
681 foreach ($aWordset as $iToken => $sToken) {
682 //echo "<br><b>$sToken</b>";
683 $aNewWordsetSearches = array();
685 foreach ($aWordsetSearches as $aCurrentSearch) {
687 //var_dump($aCurrentSearch);
690 // If the token is valid
691 if (isset($aValidTokens[' '.$sToken])) {
692 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
693 $aSearch = $aCurrentSearch;
694 $aSearch['iSearchRank']++;
695 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
696 if ($aSearch['sCountryCode'] === false) {
697 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
698 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
699 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
700 $aSearch['iSearchRank'] += 5;
702 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
704 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
705 if ($aSearch['oNear'] === false) {
706 $aSearch['oNear'] = new NearPoint(
709 $aSearchTerm['radius']
711 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
713 } elseif ($sPhraseType == 'postalcode') {
714 // 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
715 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
716 // If we already have a name try putting the postcode first
717 if (sizeof($aSearch['aName'])) {
718 $aNewSearch = $aSearch;
719 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
720 $aNewSearch['aName'] = array();
721 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
722 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
725 if (sizeof($aSearch['aName'])) {
726 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
727 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
729 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
730 $aSearch['iSearchRank'] += 1000; // skip;
733 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
734 //$aSearch['iNamePhrase'] = $iPhrase;
736 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
738 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
739 if ($aSearch['sHouseNumber'] === '') {
740 $aSearch['sHouseNumber'] = $sToken;
741 // sanity check: if the housenumber is not mainly made
742 // up of numbers, add a penalty
743 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
744 // also housenumbers should appear in the first or second phrase
745 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
746 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
748 // Fall back to not searching for this item (better than nothing)
749 $aSearch = $aCurrentSearch;
750 $aSearch['iSearchRank'] += 1;
751 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
754 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
755 // require a normalized exact match of the term
756 // if we have the normalizer version of the query
758 if ($aSearch['sClass'] === ''
759 && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
760 $aSearch['sClass'] = $aSearchTerm['class'];
761 $aSearch['sType'] = $aSearchTerm['type'];
762 if ($aSearchTerm['operator'] == '') {
763 $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' : 'near';
764 $aSearch['iSearchRank'] += 2;
766 $aSearch['sOperator'] = 'near'; // near = in for the moment
769 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
771 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
772 if (sizeof($aSearch['aName'])) {
773 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
774 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
776 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
777 $aSearch['iSearchRank'] += 1000; // skip;
780 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
781 //$aSearch['iNamePhrase'] = $iPhrase;
783 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
787 // Look for partial matches.
788 // Note that there is no point in adding country terms here
789 // because country are omitted in the address.
790 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
791 // Allow searching for a word - but at extra cost
792 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
793 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
794 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
795 $aSearch = $aCurrentSearch;
796 $aSearch['iSearchRank'] += 1;
797 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
798 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
799 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
800 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
801 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
802 $aSearch['iSearchRank'] += 1;
803 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
804 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
805 if (empty($aSearchTermToken['country_code'])
806 && empty($aSearchTermToken['lat'])
807 && empty($aSearchTermToken['class'])
809 $aSearch = $aCurrentSearch;
810 $aSearch['iSearchRank'] += 1;
811 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
812 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
816 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
817 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
818 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
822 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
823 $aSearch = $aCurrentSearch;
824 $aSearch['iSearchRank'] += 1;
825 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
826 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
827 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
828 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
830 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
832 $aSearch['iNamePhrase'] = $iPhrase;
833 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
838 // Allow skipping a word - but at EXTREAM cost
839 //$aSearch = $aCurrentSearch;
840 //$aSearch['iSearchRank']+=100;
841 //$aNewWordsetSearches[] = $aSearch;
845 usort($aNewWordsetSearches, 'bySearchRank');
846 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
848 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
850 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
851 usort($aNewPhraseSearches, 'bySearchRank');
853 $aSearchHash = array();
854 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
855 $sHash = serialize($aSearch);
856 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
857 else $aSearchHash[$sHash] = 1;
860 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
863 // Re-group the searches by their score, junk anything over 20 as just not worth trying
864 $aGroupedSearches = array();
865 foreach ($aNewPhraseSearches as $aSearch) {
866 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
867 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
868 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
871 ksort($aGroupedSearches);
874 $aSearches = array();
875 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
876 $iSearchCount += sizeof($aNewSearches);
877 $aSearches = array_merge($aSearches, $aNewSearches);
878 if ($iSearchCount > 50) break;
881 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
883 return $aGroupedSearches;
886 /* Perform the actual query lookup.
888 Returns an ordered list of results, each with the following fields:
889 osm_type: type of corresponding OSM object
893 P - postcode (internally computed)
894 osm_id: id of corresponding OSM object
895 class: general object class (corresponds to tag key of primary OSM tag)
896 type: subclass of object (corresponds to tag value of primary OSM tag)
897 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
898 rank_search: rank in search hierarchy
899 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
900 rank_address: rank in address hierarchy (determines orer in address)
901 place_id: internal key (may differ between different instances)
902 country_code: ISO country code
903 langaddress: localized full address
904 placename: localized name of object
905 ref: content of ref tag (if available)
908 importance: importance of place based on Wikipedia link count
909 addressimportance: cumulated importance of address elements
910 extra_place: type of place (for admin boundaries, if there is a place tag)
911 aBoundingBox: bounding Box
912 label: short description of the object class/type (English only)
913 name: full name (currently the same as langaddress)
914 foundorder: secondary ordering for places with same importance
918 public function lookup()
920 if (!$this->sQuery && !$this->aStructuredQuery) return array();
922 $oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
923 if ($oNormalizer !== null) {
924 $sNormQuery = $oNormalizer->transliterate($this->sQuery);
929 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
930 $sCountryCodesSQL = false;
931 if ($this->aCountryCodes) {
932 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
935 $sQuery = $this->sQuery;
936 if (!preg_match('//u', $sQuery)) {
937 userError("Query string is not UTF-8 encoded.");
940 // Conflicts between US state abreviations and various words for 'the' in different languages
941 if (isset($this->aLangPrefOrder['name:en'])) {
942 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
943 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
944 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
947 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
948 if ($this->sViewboxCentreSQL) {
949 // For complex viewboxes (routes) precompute the bounding geometry
951 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
952 "Could not get small viewbox"
954 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
957 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
958 "Could not get large viewbox"
960 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
963 // Do we have anything that looks like a lat/lon pair?
965 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
966 $oNearPoint = $aLooksLike['pt'];
967 $sQuery = $aLooksLike['query'];
970 $aSearchResults = array();
971 if ($sQuery || $this->aStructuredQuery) {
972 // Start with a blank search
977 'sCountryCode' => false,
979 'aAddress' => array(),
980 'aFullNameAddress' => array(),
981 'aNameNonSearch' => array(),
982 'aAddressNonSearch' => array(),
984 'aFeatureName' => array(),
987 'sHouseNumber' => '',
988 'oNear' => $oNearPoint
992 // Any 'special' terms in the search?
993 $bSpecialTerms = false;
994 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
995 $aSpecialTerms = array();
996 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
997 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
998 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
1001 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1002 $aSpecialTerms = array();
1003 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
1004 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
1005 unset($this->aStructuredQuery['amenity']);
1008 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1009 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1010 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
1011 $sSQL = 'SELECT * ';
1013 $sSQL .= ' SELECT word_id, word_token, word, class, type, country_code, operator';
1014 $sSQL .= ' FROM word ';
1015 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
1017 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1018 $sSQL .= ' OR country_code is not null';
1019 if (CONST_Debug) var_Dump($sSQL);
1020 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1021 $aNewSearches = array();
1022 foreach ($aSearches as $aSearch) {
1023 foreach ($aSearchWords as $aSearchTerm) {
1024 $aNewSearch = $aSearch;
1025 if ($aSearchTerm['country_code']) {
1026 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1027 $aNewSearches[] = $aNewSearch;
1028 $bSpecialTerms = true;
1030 if ($aSearchTerm['class']) {
1031 $aNewSearch['sClass'] = $aSearchTerm['class'];
1032 $aNewSearch['sType'] = $aSearchTerm['type'];
1033 $aNewSearches[] = $aNewSearch;
1034 $bSpecialTerms = true;
1038 $aSearches = $aNewSearches;
1041 // Split query into phrases
1042 // Commas are used to reduce the search space by indicating where phrases split
1043 if ($this->aStructuredQuery) {
1044 $aPhrases = $this->aStructuredQuery;
1045 $bStructuredPhrases = true;
1047 $aPhrases = explode(',', $sQuery);
1048 $bStructuredPhrases = false;
1051 // Convert each phrase to standard form
1052 // Create a list of standard words
1053 // Get all 'sets' of words
1054 // Generate a complete list of all
1056 foreach ($aPhrases as $iPhrase => $sPhrase) {
1058 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1059 "Cannot normalize query string (is it a UTF-8 string?)"
1061 if (trim($aPhrase['string'])) {
1062 $aPhrases[$iPhrase] = $aPhrase;
1063 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1064 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1065 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1067 unset($aPhrases[$iPhrase]);
1071 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1072 $aPhraseTypes = array_keys($aPhrases);
1073 $aPhrases = array_values($aPhrases);
1075 if (sizeof($aTokens)) {
1076 // Check which tokens we have, get the ID numbers
1077 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1078 $sSQL .= ' FROM word ';
1079 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1081 if (CONST_Debug) var_Dump($sSQL);
1083 $aValidTokens = array();
1084 if (sizeof($aTokens)) {
1085 $aDatabaseWords = chksql(
1086 $this->oDB->getAll($sSQL),
1087 "Could not get word tokens."
1090 $aDatabaseWords = array();
1092 $aPossibleMainWordIDs = array();
1093 $aWordFrequencyScores = array();
1094 foreach ($aDatabaseWords as $aToken) {
1095 // Very special case - require 2 letter country param to match the country code found
1096 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1097 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1102 if (isset($aValidTokens[$aToken['word_token']])) {
1103 $aValidTokens[$aToken['word_token']][] = $aToken;
1105 $aValidTokens[$aToken['word_token']] = array($aToken);
1107 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1108 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1110 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1112 // Try and calculate GB postcodes we might be missing
1113 foreach ($aTokens as $sToken) {
1114 // Source of gb postcodes is now definitive - always use
1115 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1116 if (substr($aData[1], -2, 1) != ' ') {
1117 $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1118 $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1120 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1121 if ($aGBPostcodeLocation) {
1122 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1124 } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1125 // US ZIP+4 codes - if there is no token,
1126 // merge in the 5-digit ZIP code
1127 if (isset($aValidTokens[$aData[1]])) {
1128 foreach ($aValidTokens[$aData[1]] as $aToken) {
1129 if (!$aToken['class']) {
1130 if (isset($aValidTokens[$sToken])) {
1131 $aValidTokens[$sToken][] = $aToken;
1133 $aValidTokens[$sToken] = array($aToken);
1141 foreach ($aTokens as $sToken) {
1142 // Unknown single word token with a number - assume it is a house number
1143 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1144 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1148 // Any words that have failed completely?
1149 // TODO: suggestions
1151 // Start the search process
1152 // array with: placeid => -1 | tiger-housenumber
1153 $aResultPlaceIDs = array();
1155 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1157 if ($this->bReverseInPlan) {
1158 // Reverse phrase array and also reverse the order of the wordsets in
1159 // the first and final phrase. Don't bother about phrases in the middle
1160 // because order in the address doesn't matter.
1161 $aPhrases = array_reverse($aPhrases);
1162 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1163 if (sizeof($aPhrases) > 1) {
1164 $aFinalPhrase = end($aPhrases);
1165 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1167 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1169 foreach ($aGroupedSearches as $aSearches) {
1170 foreach ($aSearches as $aSearch) {
1171 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1172 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1173 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1178 $aGroupedSearches = $aReverseGroupedSearches;
1179 ksort($aGroupedSearches);
1182 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1183 $aGroupedSearches = array();
1184 foreach ($aSearches as $aSearch) {
1185 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1186 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1187 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1190 ksort($aGroupedSearches);
1193 if (CONST_Debug) var_Dump($aGroupedSearches);
1194 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1195 $aCopyGroupedSearches = $aGroupedSearches;
1196 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1197 foreach ($aSearches as $iSearch => $aSearch) {
1198 $aReductionsList = array($aSearch['aAddress']);
1199 $iSearchRank = $aSearch['iSearchRank'];
1200 while (sizeof($aReductionsList) > 0) {
1202 if ($iSearchRank > iMaxRank) break 3;
1203 $aNewReductionsList = array();
1204 foreach ($aReductionsList as $aReductionsWordList) {
1205 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1206 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1207 $aReverseSearch = $aSearch;
1208 $aSearch['aAddress'] = $aReductionsWordListResult;
1209 $aSearch['iSearchRank'] = $iSearchRank;
1210 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1211 if (sizeof($aReductionsWordListResult) > 0) {
1212 $aNewReductionsList[] = $aReductionsWordListResult;
1216 $aReductionsList = $aNewReductionsList;
1220 ksort($aGroupedSearches);
1223 // Filter out duplicate searches
1224 $aSearchHash = array();
1225 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1226 foreach ($aSearches as $iSearch => $aSearch) {
1227 $sHash = serialize($aSearch);
1228 if (isset($aSearchHash[$sHash])) {
1229 unset($aGroupedSearches[$iGroup][$iSearch]);
1230 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1232 $aSearchHash[$sHash] = 1;
1237 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1241 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1243 foreach ($aSearches as $aSearch) {
1245 $searchedHousenumber = -1;
1247 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1248 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1250 // No location term?
1251 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1252 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1253 // Just looking for a country by code - look it up
1254 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1255 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1256 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1257 if ($bBoundingBoxSearch)
1258 $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1259 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1260 if (CONST_Debug) var_dump($sSQL);
1261 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1263 $aPlaceIDs = array();
1266 if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1267 if (!$aSearch['sClass']) continue;
1269 $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1270 if (chksql($this->oDB->getOne($sSQL))) {
1271 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1272 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1273 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1274 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1275 if (sizeof($this->aExcludePlaceIDs)) {
1276 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1278 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1279 $sSQL .= " limit $this->iLimit";
1280 if (CONST_Debug) var_dump($sSQL);
1281 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1283 // If excluded place IDs are given, it is fair to assume that
1284 // there have been results in the small box, so no further
1285 // expansion in that case.
1286 // Also don't expand if bounded results were requested.
1287 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1288 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1289 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1290 $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1291 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1292 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1293 $sSQL .= " LIMIT $this->iLimit";
1294 if (CONST_Debug) var_dump($sSQL);
1295 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1298 $sSQL = "SELECT place_id ";
1299 $sSQL .= "FROM placex ";
1300 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1301 $sSQL .= " AND type='".$aSearch['sType']."'";
1302 $sSQL .= " AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1303 $sSQL .= " AND linked_place_id is null";
1304 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1305 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1306 $sSQL .= " LIMIT $this->iLimit";
1307 if (CONST_Debug) var_dump($sSQL);
1308 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1311 } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1312 // If a coordinate is given, the search must either
1313 // be for a name or a special search. Ignore everythin else.
1314 $aPlaceIDs = array();
1316 $aPlaceIDs = array();
1318 // First we need a position, either aName or fLat or both
1322 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1323 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1326 $aOrder[0] .= " EXISTS(";
1327 $aOrder[0] .= " SELECT place_id ";
1328 $aOrder[0] .= " FROM placex ";
1329 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1330 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1331 $aOrder[0] .= " LIMIT 1";
1332 $aOrder[0] .= " ) ";
1333 // also housenumbers from interpolation lines table are needed
1334 $aOrder[0] .= " OR EXISTS(";
1335 $aOrder[0] .= " SELECT place_id ";
1336 $aOrder[0] .= " FROM location_property_osmline ";
1337 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1338 $aOrder[0] .= " AND startnumber is not NULL";
1339 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1340 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1341 $aOrder[0] .= " LIMIT 1";
1344 $aOrder[0] .= " DESC";
1347 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1348 // they might be right - but they are just too darned expensive to run
1349 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1350 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1351 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1352 // For infrequent name terms disable index usage for address
1353 if (CONST_Search_NameOnlySearchFrequencyThreshold
1354 && sizeof($aSearch['aName']) == 1
1355 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1357 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1359 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1360 if (sizeof($aSearch['aAddressNonSearch'])) {
1361 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1365 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1366 if ($aSearch['sHouseNumber']) {
1367 $aTerms[] = "address_rank between 16 and 27";
1369 if ($this->iMinAddressRank > 0) {
1370 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1372 if ($this->iMaxAddressRank < 30) {
1373 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1376 if ($aSearch['oNear']) {
1377 $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1379 $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1381 if (sizeof($this->aExcludePlaceIDs)) {
1382 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1384 if ($sCountryCodesSQL) {
1385 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1388 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1390 $aOrder[] = $oNearPoint->distanceSQL('centroid');
1393 if ($aSearch['sHouseNumber']) {
1394 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1396 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1398 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1399 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1401 $aOrder[] = "$sImportanceSQL DESC";
1402 if (sizeof($aSearch['aFullNameAddress'])) {
1403 $sExactMatchSQL = ' ( ';
1404 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
1405 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1406 $sExactMatchSQL .= ' INTERSECT ';
1407 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
1408 $sExactMatchSQL .= ' ) s';
1409 $sExactMatchSQL .= ') as exactmatch';
1410 $aOrder[] = 'exactmatch DESC';
1412 $sExactMatchSQL = '0::int as exactmatch';
1415 if (sizeof($aTerms)) {
1416 $sSQL = "SELECT place_id, ";
1417 $sSQL .= $sExactMatchSQL;
1418 $sSQL .= " FROM search_name";
1419 $sSQL .= " WHERE ".join(' and ', $aTerms);
1420 $sSQL .= " ORDER BY ".join(', ', $aOrder);
1421 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1422 $sSQL .= " LIMIT 20";
1423 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1424 $sSQL .= " LIMIT 1";
1426 $sSQL .= " LIMIT ".$this->iLimit;
1429 if (CONST_Debug) var_dump($sSQL);
1430 $aViewBoxPlaceIDs = chksql(
1431 $this->oDB->getAll($sSQL),
1432 "Could not get places for search terms."
1434 //var_dump($aViewBoxPlaceIDs);
1435 // Did we have an viewbox matches?
1436 $aPlaceIDs = array();
1437 $bViewBoxMatch = false;
1438 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1439 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1440 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1441 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1442 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1443 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1444 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1447 //var_Dump($aPlaceIDs);
1450 //now search for housenumber, if housenumber provided
1451 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1452 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1453 $aRoadPlaceIDs = $aPlaceIDs;
1454 $sPlaceIDs = join(',', $aPlaceIDs);
1456 // Now they are indexed, look for a house attached to a street we found
1457 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1458 $sSQL = "SELECT place_id FROM placex ";
1459 $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1460 if (sizeof($this->aExcludePlaceIDs)) {
1461 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1463 $sSQL .= " LIMIT $this->iLimit";
1464 if (CONST_Debug) var_dump($sSQL);
1465 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1467 // if nothing found, search in the interpolation line table
1468 if (!sizeof($aPlaceIDs)) {
1469 // do we need to use transliteration and the regex for housenumbers???
1470 //new query for lines, not housenumbers anymore
1471 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1472 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1473 if ($searchedHousenumber%2 == 0) {
1474 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1475 $sSQL .= "interpolationtype='even'";
1477 //look for housenumber in streets with interpolationtype odd or all
1478 $sSQL .= "interpolationtype='odd'";
1480 $sSQL .= " or interpolationtype='all') and ";
1481 $sSQL .= $searchedHousenumber.">=startnumber and ";
1482 $sSQL .= $searchedHousenumber."<=endnumber";
1484 if (sizeof($this->aExcludePlaceIDs)) {
1485 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1487 //$sSQL .= " limit $this->iLimit";
1488 if (CONST_Debug) var_dump($sSQL);
1490 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1493 // If nothing found try the aux fallback table
1494 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1495 $sSQL = "SELECT place_id FROM location_property_aux ";
1496 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1497 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1498 if (sizeof($this->aExcludePlaceIDs)) {
1499 $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1501 //$sSQL .= " limit $this->iLimit";
1502 if (CONST_Debug) var_dump($sSQL);
1503 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1506 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1507 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1508 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1509 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1510 if ($searchedHousenumber%2 == 0) {
1511 $sSQL .= "interpolationtype='even'";
1513 $sSQL .= "interpolationtype='odd'";
1515 $sSQL .= " or interpolationtype='all') and ";
1516 $sSQL .= $searchedHousenumber.">=startnumber and ";
1517 $sSQL .= $searchedHousenumber."<=endnumber";
1519 if (sizeof($this->aExcludePlaceIDs)) {
1520 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1522 //$sSQL .= " limit $this->iLimit";
1523 if (CONST_Debug) var_dump($sSQL);
1525 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1528 // Fallback to the road (if no housenumber was found)
1529 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1530 $aPlaceIDs = $aRoadPlaceIDs;
1531 //set to -1, if no housenumbers were found
1532 $searchedHousenumber = -1;
1534 //else: housenumber was found, remains saved in searchedHousenumber
1538 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1539 $sPlaceIDs = join(',', $aPlaceIDs);
1540 $aClassPlaceIDs = array();
1542 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1543 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1544 $sSQL = "SELECT place_id ";
1545 $sSQL .= " FROM placex ";
1546 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1547 $sSQL .= " AND class='".$aSearch['sClass']."' ";
1548 $sSQL .= " AND type='".$aSearch['sType']."'";
1549 $sSQL .= " AND linked_place_id is null";
1550 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1551 $sSQL .= " ORDER BY rank_search ASC ";
1552 $sSQL .= " LIMIT $this->iLimit";
1553 if (CONST_Debug) var_dump($sSQL);
1554 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1557 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1558 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
1559 $sSQL = "SELECT count(*) FROM pg_tables ";
1560 $sSQL .= "WHERE tablename = '$sClassTable'";
1561 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1563 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1565 if (CONST_Debug) var_dump($sSQL);
1566 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1568 // For state / country level searches the normal radius search doesn't work very well
1569 $sPlaceGeom = false;
1570 if ($this->iMaxRank < 9 && $bCacheTable) {
1571 // Try and get a polygon to search in instead
1572 $sSQL = "SELECT geometry ";
1573 $sSQL .= " FROM placex";
1574 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1575 $sSQL .= " AND rank_search < $this->iMaxRank + 5";
1576 $sSQL .= " AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1577 $sSQL .= " ORDER BY rank_search ASC ";
1578 $sSQL .= " LIMIT 1";
1579 if (CONST_Debug) var_dump($sSQL);
1580 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1586 $this->iMaxRank += 5;
1587 $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1588 if (CONST_Debug) var_dump($sSQL);
1589 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1590 $sPlaceIDs = join(',', $aPlaceIDs);
1593 if ($sPlaceIDs || $sPlaceGeom) {
1596 // More efficient - can make the range bigger
1601 $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1602 } elseif ($sPlaceIDs) {
1603 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1604 } elseif ($sPlaceGeom) {
1605 $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1608 $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
1609 $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
1610 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1612 $sSQL .= ",placex as f where ";
1613 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1617 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1619 if (sizeof($this->aExcludePlaceIDs)) {
1620 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1622 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1623 $sSQL .= 'limit 300) i ';
1624 if ($sOrderBySQL) $sSQL .= "order by order_term asc";
1625 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1626 $sSQL .= " limit $this->iLimit";
1627 if (CONST_Debug) var_dump($sSQL);
1628 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1630 if ($aSearch['oNear']) {
1631 $fRange = $aSearch['oNear']->radius();
1636 $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1638 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1641 $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1642 $sSQL .= " FROM placex as l, placex as f ";
1643 $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1644 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1645 $sSQL .= " AND l.class='".$aSearch['sClass']."' ";
1646 $sSQL .= " AND l.type='".$aSearch['sType']."' ";
1647 if (sizeof($this->aExcludePlaceIDs)) {
1648 $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1650 if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1651 if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1652 if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1653 $sSQL .= " limit $this->iLimit";
1654 if (CONST_Debug) var_dump($sSQL);
1655 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1659 $aPlaceIDs = $aClassPlaceIDs;
1664 echo "<br><b>Place IDs:</b> ";
1665 var_Dump($aPlaceIDs);
1668 foreach ($aPlaceIDs as $iPlaceID) {
1669 // array for placeID => -1 | Tiger housenumber
1670 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1672 if ($iQueryLoop > 20) break;
1675 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1676 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1677 // reduces the number of place ids, like a filter
1678 // rank_address is 30 for interpolated housenumbers
1679 $sSQL = "SELECT place_id ";
1680 $sSQL .= "FROM placex ";
1681 $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1683 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1684 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1685 $sSQL .= " OR (extratags->'place') = 'city'";
1687 if ($this->aAddressRankList) {
1688 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1690 if (CONST_Use_US_Tiger_Data) {
1693 $sSQL .= " SELECT place_id ";
1694 $sSQL .= " FROM location_property_tiger ";
1695 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1696 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1697 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1699 $sSQL .= ") UNION ";
1700 $sSQL .= " SELECT place_id ";
1701 $sSQL .= " FROM location_property_osmline ";
1702 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1703 $sSQL .= " AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1704 if (CONST_Debug) var_dump($sSQL);
1705 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1707 foreach ($aFilteredPlaceIDs as $placeID) {
1708 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1710 $aResultPlaceIDs = $tempIDs;
1714 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1715 if ($iGroupLoop > 4) break;
1716 if ($iQueryLoop > 30) break;
1719 // Did we find anything?
1720 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1721 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1724 // Just interpret as a reverse geocode
1725 $oReverse = new ReverseGeocode($this->oDB);
1726 $oReverse->setZoom(18);
1728 $aLookup = $oReverse->lookup(
1734 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1736 if ($aLookup['place_id']) {
1737 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1738 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1740 $aSearchResults = array();
1745 if (!sizeof($aSearchResults)) {
1746 if ($this->bFallback) {
1747 if ($this->fallbackStructuredQuery()) {
1748 return $this->lookup();
1755 $aClassType = getClassTypesWithImportance();
1756 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1757 foreach ($aRecheckWords as $i => $sWord) {
1758 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1762 echo '<i>Recheck words:<\i>';
1763 var_dump($aRecheckWords);
1766 $oPlaceLookup = new PlaceLookup($this->oDB);
1767 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1768 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1769 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1770 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1771 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1772 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1774 foreach ($aSearchResults as $iResNum => $aResult) {
1776 $fDiameter = getResultDiameter($aResult);
1778 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1779 if ($aOutlineResult) {
1780 $aResult = array_merge($aResult, $aOutlineResult);
1783 if ($aResult['extra_place'] == 'city') {
1784 $aResult['class'] = 'place';
1785 $aResult['type'] = 'city';
1786 $aResult['rank_search'] = 16;
1789 // Is there an icon set for this type of result?
1790 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1791 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1793 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1796 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1797 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1799 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1800 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1801 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1803 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1805 // if tag '&addressdetails=1' is set in query
1806 if ($this->bIncludeAddressDetails) {
1807 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1808 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1809 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1810 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1814 if ($this->bIncludeExtraTags) {
1815 if ($aResult['extra']) {
1816 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1818 $aResult['sExtraTags'] = (object) array();
1822 if ($this->bIncludeNameDetails) {
1823 if ($aResult['names']) {
1824 $aResult['sNameDetails'] = json_decode($aResult['names']);
1826 $aResult['sNameDetails'] = (object) array();
1830 // Adjust importance for the number of exact string matches in the result
1831 $aResult['importance'] = max(0.001, $aResult['importance']);
1833 $sAddress = $aResult['langaddress'];
1834 foreach ($aRecheckWords as $i => $sWord) {
1835 if (stripos($sAddress, $sWord)!==false) {
1837 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1841 $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
1843 $aResult['name'] = $aResult['langaddress'];
1844 // secondary ordering (for results with same importance (the smaller the better):
1845 // - approximate importance of address parts
1846 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1847 // - number of exact matches from the query
1848 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1849 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1850 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1851 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1853 // - importance of the class/type
1854 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1855 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1857 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1859 $aResult['foundorder'] += 0.01;
1861 if (CONST_Debug) var_dump($aResult);
1862 $aSearchResults[$iResNum] = $aResult;
1864 uasort($aSearchResults, 'byImportance');
1866 $aOSMIDDone = array();
1867 $aClassTypeNameDone = array();
1868 $aToFilter = $aSearchResults;
1869 $aSearchResults = array();
1872 foreach ($aToFilter as $iResNum => $aResult) {
1873 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1875 $fLat = $aResult['lat'];
1876 $fLon = $aResult['lon'];
1877 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1880 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1881 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1883 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1884 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1885 $aSearchResults[] = $aResult;
1888 // Absolute limit on number of results
1889 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1892 return $aSearchResults;