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 getIncludeAddressDetails()
72 return $this->bIncludeAddressDetails;
75 public function getIncludeExtraTags()
77 return $this->bIncludeExtraTags;
80 public function getIncludeNameDetails()
82 return $this->bIncludeNameDetails;
85 public function setIncludePolygonAsPoints($b = true)
87 $this->bIncludePolygonAsPoints = $b;
90 public function setIncludePolygonAsText($b = true)
92 $this->bIncludePolygonAsText = $b;
95 public function setIncludePolygonAsGeoJSON($b = true)
97 $this->bIncludePolygonAsGeoJSON = $b;
100 public function setIncludePolygonAsKML($b = true)
102 $this->bIncludePolygonAsKML = $b;
105 public function setIncludePolygonAsSVG($b = true)
107 $this->bIncludePolygonAsSVG = $b;
110 public function setPolygonSimplificationThreshold($f)
112 $this->fPolygonSimplificationThreshold = $f;
115 public function setLimit($iLimit = 10)
117 if ($iLimit > 50) $iLimit = 50;
118 if ($iLimit < 1) $iLimit = 1;
120 $this->iFinalLimit = $iLimit;
121 $this->iLimit = $iLimit + min($iLimit, 10);
124 public function getExcludedPlaceIDs()
126 return $this->aExcludePlaceIDs;
130 public function getCountryCodes()
132 return $this->aCountryCodes;
135 public function getViewBoxString()
137 if (!$this->aViewBox) return null;
138 return $this->aViewBox[0].','.$this->aViewBox[3].','.$this->aViewBox[2].','.$this->aViewBox[1];
141 public function setFeatureType($sFeatureType)
143 switch ($sFeatureType) {
145 $this->setRankRange(4, 4);
148 $this->setRankRange(8, 8);
151 $this->setRankRange(14, 16);
154 $this->setRankRange(8, 20);
159 public function setRankRange($iMin, $iMax)
161 $this->iMinAddressRank = $iMin;
162 $this->iMaxAddressRank = $iMax;
165 public function setRoute($aRoutePoints, $fRouteWidth)
167 $this->aViewBox = false;
169 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
171 foreach ($aRoutePoints as $aPoint) {
172 $fPoint = (float)$aPoint;
173 $this->sViewboxCentreSQL .= $sSep.$fPoint;
174 $sSep = ($sSep == ' ') ? ',' : ' ';
176 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
178 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
179 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
181 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
182 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
185 public function setViewbox($aViewbox)
187 $this->aViewBox = array_map('floatval', $aViewbox);
189 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
190 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
191 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
192 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
194 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
195 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
197 userError("Bad parameter 'viewbox'. Not a box.");
200 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
201 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
202 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
203 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
204 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
205 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
207 $this->sViewboxCentreSQL = false;
208 $this->sViewboxSmallSQL = sprintf(
209 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
215 $this->sViewboxLargeSQL = sprintf(
216 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
224 public function setQuery($sQueryString)
226 $this->sQuery = $sQueryString;
227 $this->aStructuredQuery = false;
230 public function getQueryString()
232 return $this->sQuery;
236 public function loadParamArray($oParams)
238 $this->bIncludeAddressDetails
239 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
240 $this->bIncludeExtraTags
241 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
242 $this->bIncludeNameDetails
243 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
245 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
246 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
248 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
249 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
251 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
253 // List of excluded Place IDs - used for more acurate pageing
254 $sExcluded = $oParams->getStringList('exclude_place_ids');
256 foreach ($sExcluded as $iExcludedPlaceID) {
257 $iExcludedPlaceID = (int)$iExcludedPlaceID;
258 if ($iExcludedPlaceID)
259 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
262 if (isset($aExcludePlaceIDs))
263 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
266 // Only certain ranks of feature
267 $sFeatureType = $oParams->getString('featureType');
268 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
269 if ($sFeatureType) $this->setFeatureType($sFeatureType);
272 $sCountries = $oParams->getStringList('countrycodes');
274 foreach ($sCountries as $sCountryCode) {
275 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
276 $aCountries[] = strtolower($sCountryCode);
279 if (isset($aCountries))
280 $this->aCountryCodes = $aCountries;
283 $aViewbox = $oParams->getStringList('viewboxlbrt');
285 if (count($aViewbox) != 4) {
286 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
288 $this->setViewbox($aViewbox);
290 $aViewbox = $oParams->getStringList('viewbox');
292 if (count($aViewbox) != 4) {
293 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
295 $this->setViewBox(array(
302 $aRoute = $oParams->getStringList('route');
303 $fRouteWidth = $oParams->getFloat('routewidth');
304 if ($aRoute && $fRouteWidth) {
305 $this->setRoute($aRoute, $fRouteWidth);
311 public function setQueryFromParams($oParams)
314 $sQuery = $oParams->getString('q');
316 $this->setStructuredQuery(
317 $oParams->getString('amenity'),
318 $oParams->getString('street'),
319 $oParams->getString('city'),
320 $oParams->getString('county'),
321 $oParams->getString('state'),
322 $oParams->getString('country'),
323 $oParams->getString('postalcode')
325 $this->setReverseInPlan(false);
327 $this->setQuery($sQuery);
331 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
333 $sValue = trim($sValue);
334 if (!$sValue) return false;
335 $this->aStructuredQuery[$sKey] = $sValue;
336 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
337 $this->iMinAddressRank = $iNewMinAddressRank;
338 $this->iMaxAddressRank = $iNewMaxAddressRank;
340 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
344 public function setStructuredQuery($sAmentiy = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
346 $this->sQuery = false;
349 $this->iMinAddressRank = 0;
350 $this->iMaxAddressRank = 30;
351 $this->aAddressRankList = array();
353 $this->aStructuredQuery = array();
354 $this->sAllowedTypesSQLList = '';
356 $this->loadStructuredAddressElement($sAmentiy, 'amenity', 26, 30, false);
357 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
358 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
359 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
360 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
361 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
362 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
364 if (sizeof($this->aStructuredQuery) > 0) {
365 $this->sQuery = join(', ', $this->aStructuredQuery);
366 if ($this->iMaxAddressRank < 30) {
367 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
372 public function fallbackStructuredQuery()
374 if (!$this->aStructuredQuery) return false;
376 $aParams = $this->aStructuredQuery;
378 if (sizeof($aParams) == 1) return false;
380 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
382 foreach ($aOrderToFallback as $sType) {
383 if (isset($aParams[$sType])) {
384 unset($aParams[$sType]);
385 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
393 public function getDetails($aPlaceIDs)
395 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
396 if (sizeof($aPlaceIDs) == 0) return array();
398 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
400 // Get the details for display (is this a redundant extra step?)
401 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
403 $sImportanceSQL = '';
404 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
405 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
408 $sSQL .= " osm_type,";
412 $sSQL .= " admin_level,";
413 $sSQL .= " rank_search,";
414 $sSQL .= " rank_address,";
415 $sSQL .= " min(place_id) AS place_id, ";
416 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
417 $sSQL .= " calculated_country_code AS country_code, ";
418 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
419 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
420 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
421 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
422 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
423 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
424 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
425 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
427 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
429 $sSQL .= " place_addressline s, ";
430 $sSQL .= " placex p";
431 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
432 $sSQL .= " AND p.place_id = s.address_place_id ";
433 $sSQL .= " AND s.isaddress ";
434 $sSQL .= " AND p.importance is not null ";
435 $sSQL .= " ) AS addressimportance, ";
436 $sSQL .= " (extratags->'place') AS extra_place ";
437 $sSQL .= " FROM placex";
438 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
440 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
441 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
442 $sSQL .= " OR (extratags->'place') = 'city'";
444 if ($this->aAddressRankList) {
445 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
448 if ($this->sAllowedTypesSQLList) {
449 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
451 $sSQL .= " AND linked_place_id is null ";
452 $sSQL .= " GROUP BY ";
453 $sSQL .= " osm_type, ";
454 $sSQL .= " osm_id, ";
457 $sSQL .= " admin_level, ";
458 $sSQL .= " rank_search, ";
459 $sSQL .= " rank_address, ";
460 $sSQL .= " calculated_country_code, ";
461 $sSQL .= " importance, ";
462 if (!$this->bDeDupe) $sSQL .= "place_id,";
463 $sSQL .= " langaddress, ";
464 $sSQL .= " placename, ";
466 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
467 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
468 $sSQL .= " extratags->'place' ";
470 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
471 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
472 // with start- and endnumber, the common osm housenumbers are usually saved as points
475 $length = count($aPlaceIDs);
476 foreach ($aPlaceIDs as $placeID => $housenumber) {
478 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
479 if ($i<$length) $sHousenumbers .= ", ";
482 if (CONST_Use_US_Tiger_Data) {
483 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
486 $sSQL .= " 'T' AS osm_type, ";
487 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as osm_id, ";
488 $sSQL .= " 'place' AS class, ";
489 $sSQL .= " 'house' AS type, ";
490 $sSQL .= " null AS admin_level, ";
491 $sSQL .= " 30 AS rank_search, ";
492 $sSQL .= " 30 AS rank_address, ";
493 $sSQL .= " min(place_id) AS place_id, ";
494 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
495 $sSQL .= " 'us' AS country_code, ";
496 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress,";
497 $sSQL .= " null AS placename, ";
498 $sSQL .= " null AS ref, ";
499 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
500 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
501 $sSQL .= " avg(st_x(centroid)) AS lon, ";
502 $sSQL .= " avg(st_y(centroid)) AS lat,";
503 $sSQL .= " ".$sImportanceSQL."-1.15 AS importance, ";
505 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
507 $sSQL .= " place_addressline s, ";
508 $sSQL .= " placex p";
509 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
510 $sSQL .= " AND p.place_id = s.address_place_id ";
511 $sSQL .= " AND s.isaddress";
512 $sSQL .= " AND p.importance is not null";
513 $sSQL .= " ) AS addressimportance, ";
514 $sSQL .= " null AS extra_place ";
516 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
517 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
518 $sSQL .= " parent_place_id, ";
519 $sSQL .= " housenumber_for_place";
521 $sSQL .= " location_property_tiger ";
522 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
524 $sSQL .= " housenumber_for_place>=0";
525 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
526 $sSQL .= " ) AS blub"; //postgres wants an alias here
527 $sSQL .= " GROUP BY";
528 $sSQL .= " place_id, ";
529 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
530 if (!$this->bDeDupe) $sSQL .= ", place_id ";
533 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
536 $sSQL .= " 'W' AS osm_type, ";
537 $sSQL .= " osm_id, ";
538 $sSQL .= " 'place' AS class, ";
539 $sSQL .= " 'house' AS type, ";
540 $sSQL .= " null AS admin_level, ";
541 $sSQL .= " 30 AS rank_search, ";
542 $sSQL .= " 30 AS rank_address, ";
543 $sSQL .= " min(place_id) as place_id, ";
544 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
545 $sSQL .= " calculated_country_code AS country_code, ";
546 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
547 $sSQL .= " null AS placename, ";
548 $sSQL .= " null AS ref, ";
549 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
550 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
551 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
552 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
553 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
556 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
558 $sSQL .= " place_addressline s, ";
559 $sSQL .= " placex p";
560 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
561 $sSQL .= " AND p.place_id = s.address_place_id ";
562 $sSQL .= " AND s.isaddress ";
563 $sSQL .= " AND p.importance is not null";
564 $sSQL .= " ) AS addressimportance,";
565 $sSQL .= " null AS extra_place ";
568 $sSQL .= " osm_id, ";
569 $sSQL .= " place_id, ";
570 $sSQL .= " calculated_country_code, ";
571 $sSQL .= " CASE "; // interpolate the housenumbers here
572 $sSQL .= " WHEN startnumber != endnumber ";
573 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
574 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
575 $sSQL .= " END as centroid, ";
576 $sSQL .= " parent_place_id, ";
577 $sSQL .= " housenumber_for_place ";
579 $sSQL .= " location_property_osmline ";
580 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
582 $sSQL .= " WHERE housenumber_for_place>=0 ";
583 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
584 $sSQL .= " ) as blub"; //postgres wants an alias here
585 $sSQL .= " GROUP BY ";
586 $sSQL .= " osm_id, ";
587 $sSQL .= " place_id, ";
588 $sSQL .= " housenumber_for_place, ";
589 $sSQL .= " calculated_country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
590 if (!$this->bDeDupe) $sSQL .= ", place_id ";
592 if (CONST_Use_Aux_Location_data) {
595 $sSQL .= " 'L' AS osm_type, ";
596 $sSQL .= " place_id AS osm_id, ";
597 $sSQL .= " 'place' AS class,";
598 $sSQL .= " 'house' AS type, ";
599 $sSQL .= " null AS admin_level, ";
600 $sSQL .= " 0 AS rank_search,";
601 $sSQL .= " 0 AS rank_address, ";
602 $sSQL .= " min(place_id) AS place_id,";
603 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
604 $sSQL .= " 'us' AS country_code, ";
605 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
606 $sSQL .= " null AS placename, ";
607 $sSQL .= " null AS ref, ";
608 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
609 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
610 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
611 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
612 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
614 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
616 $sSQL .= " place_addressline s, ";
617 $sSQL .= " placex p";
618 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
619 $sSQL .= " AND p.place_id = s.address_place_id ";
620 $sSQL .= " AND s.isaddress";
621 $sSQL .= " AND p.importance is not null";
622 $sSQL .= " ) AS addressimportance, ";
623 $sSQL .= " null AS extra_place ";
624 $sSQL .= " FROM location_property_aux ";
625 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
626 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
627 $sSQL .= " GROUP BY ";
628 $sSQL .= " place_id, ";
629 if (!$this->bDeDupe) $sSQL .= "place_id, ";
630 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
634 $sSQL .= " order by importance desc";
639 $aSearchResults = chksql(
640 $this->oDB->getAll($sSQL),
641 "Could not get details for place."
644 return $aSearchResults;
647 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases)
650 Calculate all searches using aValidTokens i.e.
651 'Wodsworth Road, Sheffield' =>
655 0 1 (wodsworth)(road)
658 Score how good the search is so they can be ordered
660 foreach ($aPhrases as $iPhrase => $sPhrase) {
661 $aNewPhraseSearches = array();
662 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
663 else $sPhraseType = '';
665 foreach ($aPhrases[$iPhrase]['wordsets'] as $iWordSet => $aWordset) {
666 // Too many permutations - too expensive
667 if ($iWordSet > 120) break;
669 $aWordsetSearches = $aSearches;
671 // Add all words from this wordset
672 foreach ($aWordset as $iToken => $sToken) {
673 //echo "<br><b>$sToken</b>";
674 $aNewWordsetSearches = array();
676 foreach ($aWordsetSearches as $aCurrentSearch) {
678 //var_dump($aCurrentSearch);
681 // If the token is valid
682 if (isset($aValidTokens[' '.$sToken])) {
683 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
684 $aSearch = $aCurrentSearch;
685 $aSearch['iSearchRank']++;
686 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
687 if ($aSearch['sCountryCode'] === false) {
688 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
689 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
690 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
691 $aSearch['iSearchRank'] += 5;
693 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
695 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
696 if ($aSearch['fLat'] === '') {
697 $aSearch['fLat'] = $aSearchTerm['lat'];
698 $aSearch['fLon'] = $aSearchTerm['lon'];
699 $aSearch['fRadius'] = $aSearchTerm['radius'];
700 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
702 } elseif ($sPhraseType == 'postalcode') {
703 // 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
704 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
705 // If we already have a name try putting the postcode first
706 if (sizeof($aSearch['aName'])) {
707 $aNewSearch = $aSearch;
708 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
709 $aNewSearch['aName'] = array();
710 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
711 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
714 if (sizeof($aSearch['aName'])) {
715 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
716 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
718 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
719 $aSearch['iSearchRank'] += 1000; // skip;
722 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
723 //$aSearch['iNamePhrase'] = $iPhrase;
725 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
727 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
728 if ($aSearch['sHouseNumber'] === '') {
729 $aSearch['sHouseNumber'] = $sToken;
730 // sanity check: if the housenumber is not mainly made
731 // up of numbers, add a penalty
732 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
733 // also housenumbers should appear in the first or second phrase
734 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
735 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
737 // Fall back to not searching for this item (better than nothing)
738 $aSearch = $aCurrentSearch;
739 $aSearch['iSearchRank'] += 1;
740 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
743 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
744 if ($aSearch['sClass'] === '') {
745 $aSearch['sOperator'] = $aSearchTerm['operator'];
746 $aSearch['sClass'] = $aSearchTerm['class'];
747 $aSearch['sType'] = $aSearchTerm['type'];
748 if (sizeof($aSearch['aName'])) $aSearch['sOperator'] = 'name';
749 else $aSearch['sOperator'] = 'near'; // near = in for the moment
750 if (strlen($aSearchTerm['operator']) == 0) $aSearch['iSearchRank'] += 1;
752 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
754 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
755 if (sizeof($aSearch['aName'])) {
756 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
757 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
759 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
760 $aSearch['iSearchRank'] += 1000; // skip;
763 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
764 //$aSearch['iNamePhrase'] = $iPhrase;
766 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
770 // Look for partial matches.
771 // Note that there is no point in adding country terms here
772 // because country are omitted in the address.
773 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
774 // Allow searching for a word - but at extra cost
775 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
776 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
777 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
778 $aSearch = $aCurrentSearch;
779 $aSearch['iSearchRank'] += 1;
780 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
781 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
782 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
783 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
784 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
785 $aSearch['iSearchRank'] += 1;
786 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
787 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
788 if (empty($aSearchTermToken['country_code'])
789 && empty($aSearchTermToken['lat'])
790 && empty($aSearchTermToken['class'])
792 $aSearch = $aCurrentSearch;
793 $aSearch['iSearchRank'] += 1;
794 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
795 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
799 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
800 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
801 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
805 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
806 $aSearch = $aCurrentSearch;
807 $aSearch['iSearchRank'] += 1;
808 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
809 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
810 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
811 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
813 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
815 $aSearch['iNamePhrase'] = $iPhrase;
816 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
821 // Allow skipping a word - but at EXTREAM cost
822 //$aSearch = $aCurrentSearch;
823 //$aSearch['iSearchRank']+=100;
824 //$aNewWordsetSearches[] = $aSearch;
828 usort($aNewWordsetSearches, 'bySearchRank');
829 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
831 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
833 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
834 usort($aNewPhraseSearches, 'bySearchRank');
836 $aSearchHash = array();
837 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
838 $sHash = serialize($aSearch);
839 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
840 else $aSearchHash[$sHash] = 1;
843 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
846 // Re-group the searches by their score, junk anything over 20 as just not worth trying
847 $aGroupedSearches = array();
848 foreach ($aNewPhraseSearches as $aSearch) {
849 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
850 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
851 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
854 ksort($aGroupedSearches);
857 $aSearches = array();
858 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
859 $iSearchCount += sizeof($aNewSearches);
860 $aSearches = array_merge($aSearches, $aNewSearches);
861 if ($iSearchCount > 50) break;
864 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
866 return $aGroupedSearches;
869 /* Perform the actual query lookup.
871 Returns an ordered list of results, each with the following fields:
872 osm_type: type of corresponding OSM object
876 P - postcode (internally computed)
877 osm_id: id of corresponding OSM object
878 class: general object class (corresponds to tag key of primary OSM tag)
879 type: subclass of object (corresponds to tag value of primary OSM tag)
880 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
881 rank_search: rank in search hierarchy
882 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
883 rank_address: rank in address hierarchy (determines orer in address)
884 place_id: internal key (may differ between different instances)
885 country_code: ISO country code
886 langaddress: localized full address
887 placename: localized name of object
888 ref: content of ref tag (if available)
891 importance: importance of place based on Wikipedia link count
892 addressimportance: cumulated importance of address elements
893 extra_place: type of place (for admin boundaries, if there is a place tag)
894 aBoundingBox: bounding Box
895 label: short description of the object class/type (English only)
896 name: full name (currently the same as langaddress)
897 foundorder: secondary ordering for places with same importance
901 public function lookup()
903 if (!$this->sQuery && !$this->aStructuredQuery) return false;
905 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
906 $sCountryCodesSQL = false;
907 if ($this->aCountryCodes) {
908 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
911 $sQuery = $this->sQuery;
912 if (!preg_match('//u', $sQuery)) {
913 userError("Query string is not UTF-8 encoded.");
916 // Conflicts between US state abreviations and various words for 'the' in different languages
917 if (isset($this->aLangPrefOrder['name:en'])) {
918 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
919 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
920 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
923 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
924 if ($this->sViewboxCentreSQL) {
925 // For complex viewboxes (routes) precompute the bounding geometry
927 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
928 "Could not get small viewbox"
930 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
933 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
934 "Could not get large viewbox"
936 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
939 // Do we have anything that looks like a lat/lon pair?
941 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
942 $oNearPoint = $aLooksLike['pt'];
943 $sQuery = $aLooksLike['query'];
946 $aSearchResults = array();
947 if ($sQuery || $this->aStructuredQuery) {
948 // Start with a blank search
953 'sCountryCode' => false,
955 'aAddress' => array(),
956 'aFullNameAddress' => array(),
957 'aNameNonSearch' => array(),
958 'aAddressNonSearch' => array(),
960 'aFeatureName' => array(),
963 'sHouseNumber' => '',
970 // Do we have a radius search?
972 $aSearches[0]['fLat'] = $oNearPoint->lat();
973 $aSearches[0]['fLon'] = $oNearPoint->lon();
974 $aSearches[0]['fRadius'] = $oNearPoint->radius();
977 // Any 'special' terms in the search?
978 $bSpecialTerms = false;
979 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
980 $aSpecialTerms = array();
981 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
982 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
983 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
986 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
987 $aSpecialTerms = array();
988 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
989 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
990 unset($this->aStructuredQuery['amenity']);
993 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
994 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
995 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
998 $sSQL .= ' SELECT word_id, word_token, word, class, type, country_code, operator';
999 $sSQL .= ' FROM word ';
1000 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
1002 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1003 $sSQL .= ' OR country_code is not null';
1004 if (CONST_Debug) var_Dump($sSQL);
1005 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1006 $aNewSearches = array();
1007 foreach ($aSearches as $aSearch) {
1008 foreach ($aSearchWords as $aSearchTerm) {
1009 $aNewSearch = $aSearch;
1010 if ($aSearchTerm['country_code']) {
1011 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1012 $aNewSearches[] = $aNewSearch;
1013 $bSpecialTerms = true;
1015 if ($aSearchTerm['class']) {
1016 $aNewSearch['sClass'] = $aSearchTerm['class'];
1017 $aNewSearch['sType'] = $aSearchTerm['type'];
1018 $aNewSearches[] = $aNewSearch;
1019 $bSpecialTerms = true;
1023 $aSearches = $aNewSearches;
1026 // Split query into phrases
1027 // Commas are used to reduce the search space by indicating where phrases split
1028 if ($this->aStructuredQuery) {
1029 $aPhrases = $this->aStructuredQuery;
1030 $bStructuredPhrases = true;
1032 $aPhrases = explode(',', $sQuery);
1033 $bStructuredPhrases = false;
1036 // Convert each phrase to standard form
1037 // Create a list of standard words
1038 // Get all 'sets' of words
1039 // Generate a complete list of all
1041 foreach ($aPhrases as $iPhrase => $sPhrase) {
1043 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1044 "Cannot normalize query string (is it a UTF-8 string?)"
1046 if (trim($aPhrase['string'])) {
1047 $aPhrases[$iPhrase] = $aPhrase;
1048 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1049 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1050 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1052 unset($aPhrases[$iPhrase]);
1056 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1057 $aPhraseTypes = array_keys($aPhrases);
1058 $aPhrases = array_values($aPhrases);
1060 if (sizeof($aTokens)) {
1061 // Check which tokens we have, get the ID numbers
1062 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1063 $sSQL .= ' FROM word ';
1064 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1066 if (CONST_Debug) var_Dump($sSQL);
1068 $aValidTokens = array();
1069 if (sizeof($aTokens)) {
1070 $aDatabaseWords = chksql(
1071 $this->oDB->getAll($sSQL),
1072 "Could not get word tokens."
1075 $aDatabaseWords = array();
1077 $aPossibleMainWordIDs = array();
1078 $aWordFrequencyScores = array();
1079 foreach ($aDatabaseWords as $aToken) {
1080 // Very special case - require 2 letter country param to match the country code found
1081 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1082 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1087 if (isset($aValidTokens[$aToken['word_token']])) {
1088 $aValidTokens[$aToken['word_token']][] = $aToken;
1090 $aValidTokens[$aToken['word_token']] = array($aToken);
1092 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1093 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1095 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1097 // Try and calculate GB postcodes we might be missing
1098 foreach ($aTokens as $sToken) {
1099 // Source of gb postcodes is now definitive - always use
1100 if (preg_match('/^([A-Z][A-Z]?[0-9][0-9A-Z]? ?[0-9])([A-Z][A-Z])$/', strtoupper(trim($sToken)), $aData)) {
1101 if (substr($aData[1], -2, 1) != ' ') {
1102 $aData[0] = substr($aData[0], 0, strlen($aData[1])-1).' '.substr($aData[0], strlen($aData[1])-1);
1103 $aData[1] = substr($aData[1], 0, -1).' '.substr($aData[1], -1, 1);
1105 $aGBPostcodeLocation = gbPostcodeCalculate($aData[0], $aData[1], $aData[2], $this->oDB);
1106 if ($aGBPostcodeLocation) {
1107 $aValidTokens[$sToken] = $aGBPostcodeLocation;
1109 } elseif (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1110 // US ZIP+4 codes - if there is no token,
1111 // merge in the 5-digit ZIP code
1112 if (isset($aValidTokens[$aData[1]])) {
1113 foreach ($aValidTokens[$aData[1]] as $aToken) {
1114 if (!$aToken['class']) {
1115 if (isset($aValidTokens[$sToken])) {
1116 $aValidTokens[$sToken][] = $aToken;
1118 $aValidTokens[$sToken] = array($aToken);
1126 foreach ($aTokens as $sToken) {
1127 // Unknown single word token with a number - assume it is a house number
1128 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1129 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1133 // Any words that have failed completely?
1134 // TODO: suggestions
1136 // Start the search process
1137 // array with: placeid => -1 | tiger-housenumber
1138 $aResultPlaceIDs = array();
1140 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases);
1142 if ($this->bReverseInPlan) {
1143 // Reverse phrase array and also reverse the order of the wordsets in
1144 // the first and final phrase. Don't bother about phrases in the middle
1145 // because order in the address doesn't matter.
1146 $aPhrases = array_reverse($aPhrases);
1147 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1148 if (sizeof($aPhrases) > 1) {
1149 $aFinalPhrase = end($aPhrases);
1150 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1152 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false);
1154 foreach ($aGroupedSearches as $aSearches) {
1155 foreach ($aSearches as $aSearch) {
1156 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1157 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1158 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1163 $aGroupedSearches = $aReverseGroupedSearches;
1164 ksort($aGroupedSearches);
1167 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1168 $aGroupedSearches = array();
1169 foreach ($aSearches as $aSearch) {
1170 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1171 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1172 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1175 ksort($aGroupedSearches);
1178 if (CONST_Debug) var_Dump($aGroupedSearches);
1179 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1180 $aCopyGroupedSearches = $aGroupedSearches;
1181 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1182 foreach ($aSearches as $iSearch => $aSearch) {
1183 $aReductionsList = array($aSearch['aAddress']);
1184 $iSearchRank = $aSearch['iSearchRank'];
1185 while (sizeof($aReductionsList) > 0) {
1187 if ($iSearchRank > iMaxRank) break 3;
1188 $aNewReductionsList = array();
1189 foreach ($aReductionsList as $aReductionsWordList) {
1190 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1191 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1192 $aReverseSearch = $aSearch;
1193 $aSearch['aAddress'] = $aReductionsWordListResult;
1194 $aSearch['iSearchRank'] = $iSearchRank;
1195 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1196 if (sizeof($aReductionsWordListResult) > 0) {
1197 $aNewReductionsList[] = $aReductionsWordListResult;
1201 $aReductionsList = $aNewReductionsList;
1205 ksort($aGroupedSearches);
1208 // Filter out duplicate searches
1209 $aSearchHash = array();
1210 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1211 foreach ($aSearches as $iSearch => $aSearch) {
1212 $sHash = serialize($aSearch);
1213 if (isset($aSearchHash[$sHash])) {
1214 unset($aGroupedSearches[$iGroup][$iSearch]);
1215 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1217 $aSearchHash[$sHash] = 1;
1222 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1226 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1228 foreach ($aSearches as $aSearch) {
1230 $searchedHousenumber = -1;
1232 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1233 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1235 // No location term?
1236 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['fLon']) {
1237 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1238 // Just looking for a country by code - look it up
1239 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1240 $sSQL = "SELECT place_id FROM placex WHERE calculated_country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1241 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1242 if ($bBoundingBoxSearch)
1243 $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1244 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1245 if (CONST_Debug) var_dump($sSQL);
1246 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1248 $aPlaceIDs = array();
1251 if (!$bBoundingBoxSearch && !$aSearch['fLon']) continue;
1252 if (!$aSearch['sClass']) continue;
1254 $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1255 if (chksql($this->oDB->getOne($sSQL))) {
1256 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1257 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1258 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1259 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1260 if (sizeof($this->aExcludePlaceIDs)) {
1261 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1263 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1264 $sSQL .= " limit $this->iLimit";
1265 if (CONST_Debug) var_dump($sSQL);
1266 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1268 // If excluded place IDs are given, it is fair to assume that
1269 // there have been results in the small box, so no further
1270 // expansion in that case.
1271 // Also don't expand if bounded results were requested.
1272 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1273 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1274 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1275 $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1276 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1277 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1278 $sSQL .= " LIMIT $this->iLimit";
1279 if (CONST_Debug) var_dump($sSQL);
1280 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1283 $sSQL = "SELECT place_id ";
1284 $sSQL .= "FROM placex ";
1285 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1286 $sSQL .= " AND type='".$aSearch['sType']."'";
1287 $sSQL .= " AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1288 $sSQL .= " AND linked_place_id is null";
1289 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1290 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1291 $sSQL .= " LIMIT $this->iLimit";
1292 if (CONST_Debug) var_dump($sSQL);
1293 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1296 } elseif ($aSearch['fLon'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1297 // If a coordinate is given, the search must either
1298 // be for a name or a special search. Ignore everythin else.
1299 $aPlaceIDs = array();
1301 $aPlaceIDs = array();
1303 // First we need a position, either aName or fLat or both
1307 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1308 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1311 $aOrder[0] .= " EXISTS(";
1312 $aOrder[0] .= " SELECT place_id ";
1313 $aOrder[0] .= " FROM placex ";
1314 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1315 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1316 $aOrder[0] .= " LIMIT 1";
1317 $aOrder[0] .= " ) ";
1318 // also housenumbers from interpolation lines table are needed
1319 $aOrder[0] .= " OR EXISTS(";
1320 $aOrder[0] .= " SELECT place_id ";
1321 $aOrder[0] .= " FROM location_property_osmline ";
1322 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1323 $aOrder[0] .= " AND startnumber is not NULL";
1324 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1325 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1326 $aOrder[0] .= " LIMIT 1";
1329 $aOrder[0] .= " DESC";
1332 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1333 // they might be right - but they are just too darned expensive to run
1334 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1335 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1336 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1337 // For infrequent name terms disable index usage for address
1338 if (CONST_Search_NameOnlySearchFrequencyThreshold
1339 && sizeof($aSearch['aName']) == 1
1340 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1342 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1344 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1345 if (sizeof($aSearch['aAddressNonSearch'])) {
1346 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1350 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1351 if ($aSearch['sHouseNumber']) {
1352 $aTerms[] = "address_rank between 16 and 27";
1354 if ($this->iMinAddressRank > 0) {
1355 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1357 if ($this->iMaxAddressRank < 30) {
1358 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1361 if ($aSearch['fLon'] && $aSearch['fLat']) {
1362 $aTerms[] = sprintf(
1363 'ST_DWithin(centroid, ST_SetSRID(ST_Point(%F,%F),4326), %F)',
1369 $aOrder[] = "ST_Distance(centroid, ST_SetSRID(ST_Point(".$aSearch['fLon'].",".$aSearch['fLat']."),4326)) ASC";
1371 if (sizeof($this->aExcludePlaceIDs)) {
1372 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1374 if ($sCountryCodesSQL) {
1375 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1378 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1380 $aOrder[] = $oNearPoint->distanceSQL('centroid');
1383 if ($aSearch['sHouseNumber']) {
1384 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1386 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1388 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1389 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1391 $aOrder[] = "$sImportanceSQL DESC";
1392 if (sizeof($aSearch['aFullNameAddress'])) {
1393 $sExactMatchSQL = ' ( ';
1394 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
1395 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1396 $sExactMatchSQL .= ' INTERSECT ';
1397 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
1398 $sExactMatchSQL .= ' ) s';
1399 $sExactMatchSQL .= ') as exactmatch';
1400 $aOrder[] = 'exactmatch DESC';
1402 $sExactMatchSQL = '0::int as exactmatch';
1405 if (sizeof($aTerms)) {
1406 $sSQL = "SELECT place_id, ";
1407 $sSQL .= $sExactMatchSQL;
1408 $sSQL .= " FROM search_name";
1409 $sSQL .= " WHERE ".join(' and ', $aTerms);
1410 $sSQL .= " ORDER BY ".join(', ', $aOrder);
1411 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1412 $sSQL .= " LIMIT 20";
1413 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1414 $sSQL .= " LIMIT 1";
1416 $sSQL .= " LIMIT ".$this->iLimit;
1419 if (CONST_Debug) var_dump($sSQL);
1420 $aViewBoxPlaceIDs = chksql(
1421 $this->oDB->getAll($sSQL),
1422 "Could not get places for search terms."
1424 //var_dump($aViewBoxPlaceIDs);
1425 // Did we have an viewbox matches?
1426 $aPlaceIDs = array();
1427 $bViewBoxMatch = false;
1428 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1429 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1430 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1431 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1432 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1433 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1434 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1437 //var_Dump($aPlaceIDs);
1440 //now search for housenumber, if housenumber provided
1441 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1442 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1443 $aRoadPlaceIDs = $aPlaceIDs;
1444 $sPlaceIDs = join(',', $aPlaceIDs);
1446 // Now they are indexed, look for a house attached to a street we found
1447 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1448 $sSQL = "SELECT place_id FROM placex ";
1449 $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1450 if (sizeof($this->aExcludePlaceIDs)) {
1451 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1453 $sSQL .= " LIMIT $this->iLimit";
1454 if (CONST_Debug) var_dump($sSQL);
1455 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1457 // if nothing found, search in the interpolation line table
1458 if (!sizeof($aPlaceIDs)) {
1459 // do we need to use transliteration and the regex for housenumbers???
1460 //new query for lines, not housenumbers anymore
1461 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1462 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1463 if ($searchedHousenumber%2 == 0) {
1464 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1465 $sSQL .= "interpolationtype='even'";
1467 //look for housenumber in streets with interpolationtype odd or all
1468 $sSQL .= "interpolationtype='odd'";
1470 $sSQL .= " or interpolationtype='all') and ";
1471 $sSQL .= $searchedHousenumber.">=startnumber and ";
1472 $sSQL .= $searchedHousenumber."<=endnumber";
1474 if (sizeof($this->aExcludePlaceIDs)) {
1475 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1477 //$sSQL .= " limit $this->iLimit";
1478 if (CONST_Debug) var_dump($sSQL);
1480 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1483 // If nothing found try the aux fallback table
1484 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1485 $sSQL = "SELECT place_id FROM location_property_aux ";
1486 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1487 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1488 if (sizeof($this->aExcludePlaceIDs)) {
1489 $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1491 //$sSQL .= " limit $this->iLimit";
1492 if (CONST_Debug) var_dump($sSQL);
1493 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1496 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1497 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1498 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1499 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1500 if ($searchedHousenumber%2 == 0) {
1501 $sSQL .= "interpolationtype='even'";
1503 $sSQL .= "interpolationtype='odd'";
1505 $sSQL .= " or interpolationtype='all') and ";
1506 $sSQL .= $searchedHousenumber.">=startnumber and ";
1507 $sSQL .= $searchedHousenumber."<=endnumber";
1509 if (sizeof($this->aExcludePlaceIDs)) {
1510 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1512 //$sSQL .= " limit $this->iLimit";
1513 if (CONST_Debug) var_dump($sSQL);
1515 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1518 // Fallback to the road (if no housenumber was found)
1519 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1520 $aPlaceIDs = $aRoadPlaceIDs;
1521 //set to -1, if no housenumbers were found
1522 $searchedHousenumber = -1;
1524 //else: housenumber was found, remains saved in searchedHousenumber
1528 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1529 $sPlaceIDs = join(',', $aPlaceIDs);
1530 $aClassPlaceIDs = array();
1532 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1533 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1534 $sSQL = "SELECT place_id ";
1535 $sSQL .= " FROM placex ";
1536 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1537 $sSQL .= " AND class='".$aSearch['sClass']."' ";
1538 $sSQL .= " AND type='".$aSearch['sType']."'";
1539 $sSQL .= " AND linked_place_id is null";
1540 if ($sCountryCodesSQL) $sSQL .= " AND calculated_country_code in ($sCountryCodesSQL)";
1541 $sSQL .= " ORDER BY rank_search ASC ";
1542 $sSQL .= " LIMIT $this->iLimit";
1543 if (CONST_Debug) var_dump($sSQL);
1544 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1547 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1548 $sSQL = "SELECT count(*) FROM pg_tables ";
1549 $sSQL .= "WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1550 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1552 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1554 if (CONST_Debug) var_dump($sSQL);
1555 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1557 // For state / country level searches the normal radius search doesn't work very well
1558 $sPlaceGeom = false;
1559 if ($this->iMaxRank < 9 && $bCacheTable) {
1560 // Try and get a polygon to search in instead
1561 $sSQL = "SELECT geometry ";
1562 $sSQL .= " FROM placex";
1563 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1564 $sSQL .= " AND rank_search < $this->iMaxRank + 5";
1565 $sSQL .= " AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1566 $sSQL .= " ORDER BY rank_search ASC ";
1567 $sSQL .= " LIMIT 1";
1568 if (CONST_Debug) var_dump($sSQL);
1569 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1575 $this->iMaxRank += 5;
1576 $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1577 if (CONST_Debug) var_dump($sSQL);
1578 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1579 $sPlaceIDs = join(',', $aPlaceIDs);
1582 if ($sPlaceIDs || $sPlaceGeom) {
1585 // More efficient - can make the range bigger
1590 $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1591 } elseif ($sPlaceIDs) {
1592 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1593 } elseif ($sPlaceGeom) {
1594 $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1597 $sSQL = "select distinct l.place_id".($sOrderBySQL?','.$sOrderBySQL:'')." from place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." as l";
1598 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1600 $sSQL .= ",placex as f where ";
1601 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1605 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1607 if (sizeof($this->aExcludePlaceIDs)) {
1608 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1610 if ($sCountryCodesSQL) $sSQL .= " and lp.calculated_country_code in ($sCountryCodesSQL)";
1611 if ($sOrderBySQL) $sSQL .= "order by ".$sOrderBySQL." asc";
1612 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1613 $sSQL .= " limit $this->iLimit";
1614 if (CONST_Debug) var_dump($sSQL);
1615 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1617 if (isset($aSearch['fRadius']) && $aSearch['fRadius']) $fRange = $aSearch['fRadius'];
1621 $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1623 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1626 $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1627 $sSQL .= " FROM placex as l, placex as f ";
1628 $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1629 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1630 $sSQL .= " AND l.class='".$aSearch['sClass']."' ";
1631 $sSQL .= " AND l.type='".$aSearch['sType']."' ";
1632 if (sizeof($this->aExcludePlaceIDs)) {
1633 $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1635 if ($sCountryCodesSQL) $sSQL .= " AND l.calculated_country_code in ($sCountryCodesSQL)";
1636 if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1637 if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1638 $sSQL .= " limit $this->iLimit";
1639 if (CONST_Debug) var_dump($sSQL);
1640 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1644 $aPlaceIDs = $aClassPlaceIDs;
1649 echo "<br><b>Place IDs:</b> ";
1650 var_Dump($aPlaceIDs);
1653 foreach ($aPlaceIDs as $iPlaceID) {
1654 // array for placeID => -1 | Tiger housenumber
1655 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1657 if ($iQueryLoop > 20) break;
1660 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1661 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1662 // reduces the number of place ids, like a filter
1663 // rank_address is 30 for interpolated housenumbers
1664 $sSQL = "SELECT place_id ";
1665 $sSQL .= "FROM placex ";
1666 $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1668 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1669 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1670 $sSQL .= " OR (extratags->'place') = 'city'";
1672 if ($this->aAddressRankList) {
1673 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1675 if (CONST_Use_US_Tiger_Data) {
1678 $sSQL .= " SELECT place_id ";
1679 $sSQL .= " FROM location_property_tiger ";
1680 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1681 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1682 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1684 $sSQL .= ") UNION ";
1685 $sSQL .= " SELECT place_id ";
1686 $sSQL .= " FROM location_property_osmline ";
1687 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1688 $sSQL .= " AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1689 if (CONST_Debug) var_dump($sSQL);
1690 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1692 foreach ($aFilteredPlaceIDs as $placeID) {
1693 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1695 $aResultPlaceIDs = $tempIDs;
1699 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1700 if ($iGroupLoop > 4) break;
1701 if ($iQueryLoop > 30) break;
1704 // Did we find anything?
1705 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1706 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1709 // Just interpret as a reverse geocode
1710 $oReverse = new ReverseGeocode($this->oDB);
1711 $oReverse->setZoom(18);
1713 $aLookup = $oReverse->lookup(
1719 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1721 if ($aLookup['place_id']) {
1722 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1723 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1725 $aSearchResults = array();
1730 if (!sizeof($aSearchResults)) {
1731 if ($this->bFallback) {
1732 if ($this->fallbackStructuredQuery()) {
1733 return $this->lookup();
1740 $aClassType = getClassTypesWithImportance();
1741 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1742 foreach ($aRecheckWords as $i => $sWord) {
1743 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1747 echo '<i>Recheck words:<\i>';
1748 var_dump($aRecheckWords);
1751 $oPlaceLookup = new PlaceLookup($this->oDB);
1752 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1753 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1754 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1755 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1756 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1757 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1759 foreach ($aSearchResults as $iResNum => $aResult) {
1761 $fDiameter = getResultDiameter($aResult);
1763 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1764 if ($aOutlineResult) {
1765 $aResult = array_merge($aResult, $aOutlineResult);
1768 if ($aResult['extra_place'] == 'city') {
1769 $aResult['class'] = 'place';
1770 $aResult['type'] = 'city';
1771 $aResult['rank_search'] = 16;
1774 // Is there an icon set for this type of result?
1775 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1776 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1778 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1781 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1782 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1784 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1785 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1786 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1788 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1790 // if tag '&addressdetails=1' is set in query
1791 if ($this->bIncludeAddressDetails) {
1792 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1793 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1794 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1795 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1799 if ($this->bIncludeExtraTags) {
1800 if ($aResult['extra']) {
1801 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1803 $aResult['sExtraTags'] = (object) array();
1807 if ($this->bIncludeNameDetails) {
1808 if ($aResult['names']) {
1809 $aResult['sNameDetails'] = json_decode($aResult['names']);
1811 $aResult['sNameDetails'] = (object) array();
1815 // Adjust importance for the number of exact string matches in the result
1816 $aResult['importance'] = max(0.001, $aResult['importance']);
1818 $sAddress = $aResult['langaddress'];
1819 foreach ($aRecheckWords as $i => $sWord) {
1820 if (stripos($sAddress, $sWord)!==false) {
1822 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1826 $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
1828 $aResult['name'] = $aResult['langaddress'];
1829 // secondary ordering (for results with same importance (the smaller the better):
1830 // - approximate importance of address parts
1831 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1832 // - number of exact matches from the query
1833 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1834 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1835 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1836 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1838 // - importance of the class/type
1839 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1840 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1842 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1844 $aResult['foundorder'] += 0.01;
1846 if (CONST_Debug) var_dump($aResult);
1847 $aSearchResults[$iResNum] = $aResult;
1849 uasort($aSearchResults, 'byImportance');
1851 $aOSMIDDone = array();
1852 $aClassTypeNameDone = array();
1853 $aToFilter = $aSearchResults;
1854 $aSearchResults = array();
1857 foreach ($aToFilter as $iResNum => $aResult) {
1858 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1860 $fLat = $aResult['lat'];
1861 $fLon = $aResult['lon'];
1862 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1865 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1866 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1868 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1869 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1870 $aSearchResults[] = $aResult;
1873 // Absolute limit on number of results
1874 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1877 return $aSearchResults;