5 require_once(CONST_BasePath.'/lib/NearPoint.php');
6 require_once(CONST_BasePath.'/lib/PlaceLookup.php');
7 require_once(CONST_BasePath.'/lib/ReverseGeocode.php');
13 protected $aLangPrefOrder = array();
15 protected $bIncludeAddressDetails = false;
16 protected $bIncludeExtraTags = false;
17 protected $bIncludeNameDetails = false;
19 protected $bIncludePolygonAsPoints = false;
20 protected $bIncludePolygonAsText = false;
21 protected $bIncludePolygonAsGeoJSON = false;
22 protected $bIncludePolygonAsKML = false;
23 protected $bIncludePolygonAsSVG = false;
24 protected $fPolygonSimplificationThreshold = 0.0;
26 protected $aExcludePlaceIDs = array();
27 protected $bDeDupe = true;
28 protected $bReverseInPlan = false;
30 protected $iLimit = 20;
31 protected $iFinalLimit = 10;
32 protected $iOffset = 0;
33 protected $bFallback = false;
35 protected $aCountryCodes = false;
37 protected $bBoundedSearch = false;
38 protected $aViewBox = false;
39 protected $sViewboxCentreSQL = false;
40 protected $sViewboxSmallSQL = false;
41 protected $sViewboxLargeSQL = false;
43 protected $iMaxRank = 20;
44 protected $iMinAddressRank = 0;
45 protected $iMaxAddressRank = 30;
46 protected $aAddressRankList = array();
47 protected $exactMatchCache = array();
49 protected $sAllowedTypesSQLList = false;
51 protected $sQuery = false;
52 protected $aStructuredQuery = false;
54 protected $oNormalizer = null;
57 public function __construct(&$oDB)
60 $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
63 private function normTerm($sTerm)
65 if ($this->oNormalizer === null) {
69 return $this->oNormalizer->transliterate($sTerm);
72 public function setReverseInPlan($bReverse)
74 $this->bReverseInPlan = $bReverse;
77 public function setLanguagePreference($aLangPref)
79 $this->aLangPrefOrder = $aLangPref;
82 public function getMoreUrlParams()
84 if ($this->aStructuredQuery) {
85 $aParams = $this->aStructuredQuery;
87 $aParams = array('q' => $this->sQuery);
90 if ($this->aExcludePlaceIDs) {
91 $aParams['exclude_place_ids'] = implode(',', $this->aExcludePlaceIDs);
94 if ($this->bIncludeAddressDetails) $aParams['addressdetails'] = '1';
95 if ($this->bIncludeExtraTags) $aParams['extratags'] = '1';
96 if ($this->bIncludeNameDetails) $aParams['namedetails'] = '1';
98 if ($this->bIncludePolygonAsPoints) $aParams['polygon'] = '1';
99 if ($this->bIncludePolygonAsText) $aParams['polygon_text'] = '1';
100 if ($this->bIncludePolygonAsGeoJSON) $aParams['polygon_geojson'] = '1';
101 if ($this->bIncludePolygonAsKML) $aParams['polygon_kml'] = '1';
102 if ($this->bIncludePolygonAsSVG) $aParams['polygon_svg'] = '1';
104 if ($this->fPolygonSimplificationThreshold > 0.0) {
105 $aParams['polygon_threshold'] = $this->fPolygonSimplificationThreshold;
108 if ($this->bBoundedSearch) $aParams['bounded'] = '1';
109 if (!$this->bDeDupe) $aParams['dedupe'] = '0';
111 if ($this->aCountryCodes) {
112 $aParams['countrycodes'] = implode(',', $this->aCountryCodes);
115 if ($this->aViewBox) {
116 $aParams['viewbox'] = $this->aViewBox[0].','.$this->aViewBox[3]
117 .','.$this->aViewBox[2].','.$this->aViewBox[1];
123 public function setIncludePolygonAsPoints($b = true)
125 $this->bIncludePolygonAsPoints = $b;
128 public function setIncludePolygonAsText($b = true)
130 $this->bIncludePolygonAsText = $b;
133 public function setIncludePolygonAsGeoJSON($b = true)
135 $this->bIncludePolygonAsGeoJSON = $b;
138 public function setIncludePolygonAsKML($b = true)
140 $this->bIncludePolygonAsKML = $b;
143 public function setIncludePolygonAsSVG($b = true)
145 $this->bIncludePolygonAsSVG = $b;
148 public function setPolygonSimplificationThreshold($f)
150 $this->fPolygonSimplificationThreshold = $f;
153 public function setLimit($iLimit = 10)
155 if ($iLimit > 50) $iLimit = 50;
156 if ($iLimit < 1) $iLimit = 1;
158 $this->iFinalLimit = $iLimit;
159 $this->iLimit = $iLimit + min($iLimit, 10);
162 public function setFeatureType($sFeatureType)
164 switch ($sFeatureType) {
166 $this->setRankRange(4, 4);
169 $this->setRankRange(8, 8);
172 $this->setRankRange(14, 16);
175 $this->setRankRange(8, 20);
180 public function setRankRange($iMin, $iMax)
182 $this->iMinAddressRank = $iMin;
183 $this->iMaxAddressRank = $iMax;
186 public function setRoute($aRoutePoints, $fRouteWidth)
188 $this->aViewBox = false;
190 $this->sViewboxCentreSQL = "ST_SetSRID('LINESTRING(";
192 foreach ($aRoutePoints as $aPoint) {
193 $fPoint = (float)$aPoint;
194 $this->sViewboxCentreSQL .= $sSep.$fPoint;
195 $sSep = ($sSep == ' ') ? ',' : ' ';
197 $this->sViewboxCentreSQL .= ")'::geometry,4326)";
199 $this->sViewboxSmallSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
200 $this->sViewboxSmallSQL .= ','.($fRouteWidth/69).')';
202 $this->sViewboxLargeSQL = 'ST_BUFFER('.$this->sViewboxCentreSQL;
203 $this->sViewboxLargeSQL .= ','.($fRouteWidth/30).')';
206 public function setViewbox($aViewbox)
208 $this->aViewBox = array_map('floatval', $aViewbox);
210 $this->aViewBox[0] = max(-180.0, min(180, $this->aViewBox[0]));
211 $this->aViewBox[1] = max(-90.0, min(90, $this->aViewBox[1]));
212 $this->aViewBox[2] = max(-180.0, min(180, $this->aViewBox[2]));
213 $this->aViewBox[3] = max(-90.0, min(90, $this->aViewBox[3]));
215 if (abs($this->aViewBox[0] - $this->aViewBox[2]) < 0.000000001
216 || abs($this->aViewBox[1] - $this->aViewBox[3]) < 0.000000001
218 userError("Bad parameter 'viewbox'. Not a box.");
221 $fHeight = $this->aViewBox[0] - $this->aViewBox[2];
222 $fWidth = $this->aViewBox[1] - $this->aViewBox[3];
223 $aBigViewBox[0] = $this->aViewBox[0] + $fHeight;
224 $aBigViewBox[2] = $this->aViewBox[2] - $fHeight;
225 $aBigViewBox[1] = $this->aViewBox[1] + $fWidth;
226 $aBigViewBox[3] = $this->aViewBox[3] - $fWidth;
228 $this->sViewboxCentreSQL = false;
229 $this->sViewboxSmallSQL = sprintf(
230 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
236 $this->sViewboxLargeSQL = sprintf(
237 'ST_SetSRID(ST_MakeBox2D(ST_Point(%F,%F),ST_Point(%F,%F)),4326)',
245 public function setQuery($sQueryString)
247 $this->sQuery = $sQueryString;
248 $this->aStructuredQuery = false;
251 public function getQueryString()
253 return $this->sQuery;
257 public function loadParamArray($oParams)
259 $this->bIncludeAddressDetails
260 = $oParams->getBool('addressdetails', $this->bIncludeAddressDetails);
261 $this->bIncludeExtraTags
262 = $oParams->getBool('extratags', $this->bIncludeExtraTags);
263 $this->bIncludeNameDetails
264 = $oParams->getBool('namedetails', $this->bIncludeNameDetails);
266 $this->bBoundedSearch = $oParams->getBool('bounded', $this->bBoundedSearch);
267 $this->bDeDupe = $oParams->getBool('dedupe', $this->bDeDupe);
269 $this->setLimit($oParams->getInt('limit', $this->iFinalLimit));
270 $this->iOffset = $oParams->getInt('offset', $this->iOffset);
272 $this->bFallback = $oParams->getBool('fallback', $this->bFallback);
274 // List of excluded Place IDs - used for more acurate pageing
275 $sExcluded = $oParams->getStringList('exclude_place_ids');
277 foreach ($sExcluded as $iExcludedPlaceID) {
278 $iExcludedPlaceID = (int)$iExcludedPlaceID;
279 if ($iExcludedPlaceID)
280 $aExcludePlaceIDs[$iExcludedPlaceID] = $iExcludedPlaceID;
283 if (isset($aExcludePlaceIDs))
284 $this->aExcludePlaceIDs = $aExcludePlaceIDs;
287 // Only certain ranks of feature
288 $sFeatureType = $oParams->getString('featureType');
289 if (!$sFeatureType) $sFeatureType = $oParams->getString('featuretype');
290 if ($sFeatureType) $this->setFeatureType($sFeatureType);
293 $sCountries = $oParams->getStringList('countrycodes');
295 foreach ($sCountries as $sCountryCode) {
296 if (preg_match('/^[a-zA-Z][a-zA-Z]$/', $sCountryCode)) {
297 $aCountries[] = strtolower($sCountryCode);
300 if (isset($aCountries))
301 $this->aCountryCodes = $aCountries;
304 $aViewbox = $oParams->getStringList('viewboxlbrt');
306 if (count($aViewbox) != 4) {
307 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
309 $this->setViewbox($aViewbox);
311 $aViewbox = $oParams->getStringList('viewbox');
313 if (count($aViewbox) != 4) {
314 userError("Bad parmater 'viewbox'. Expected 4 coordinates.");
316 $this->setViewBox(array(
323 $aRoute = $oParams->getStringList('route');
324 $fRouteWidth = $oParams->getFloat('routewidth');
325 if ($aRoute && $fRouteWidth) {
326 $this->setRoute($aRoute, $fRouteWidth);
332 public function setQueryFromParams($oParams)
335 $sQuery = $oParams->getString('q');
337 $this->setStructuredQuery(
338 $oParams->getString('amenity'),
339 $oParams->getString('street'),
340 $oParams->getString('city'),
341 $oParams->getString('county'),
342 $oParams->getString('state'),
343 $oParams->getString('country'),
344 $oParams->getString('postalcode')
346 $this->setReverseInPlan(false);
348 $this->setQuery($sQuery);
352 public function loadStructuredAddressElement($sValue, $sKey, $iNewMinAddressRank, $iNewMaxAddressRank, $aItemListValues)
354 $sValue = trim($sValue);
355 if (!$sValue) return false;
356 $this->aStructuredQuery[$sKey] = $sValue;
357 if ($this->iMinAddressRank == 0 && $this->iMaxAddressRank == 30) {
358 $this->iMinAddressRank = $iNewMinAddressRank;
359 $this->iMaxAddressRank = $iNewMaxAddressRank;
361 if ($aItemListValues) $this->aAddressRankList = array_merge($this->aAddressRankList, $aItemListValues);
365 public function setStructuredQuery($sAmenity = false, $sStreet = false, $sCity = false, $sCounty = false, $sState = false, $sCountry = false, $sPostalCode = false)
367 $this->sQuery = false;
370 $this->iMinAddressRank = 0;
371 $this->iMaxAddressRank = 30;
372 $this->aAddressRankList = array();
374 $this->aStructuredQuery = array();
375 $this->sAllowedTypesSQLList = '';
377 $this->loadStructuredAddressElement($sAmenity, 'amenity', 26, 30, false);
378 $this->loadStructuredAddressElement($sStreet, 'street', 26, 30, false);
379 $this->loadStructuredAddressElement($sCity, 'city', 14, 24, false);
380 $this->loadStructuredAddressElement($sCounty, 'county', 9, 13, false);
381 $this->loadStructuredAddressElement($sState, 'state', 8, 8, false);
382 $this->loadStructuredAddressElement($sPostalCode, 'postalcode', 5, 11, array(5, 11));
383 $this->loadStructuredAddressElement($sCountry, 'country', 4, 4, false);
385 if (sizeof($this->aStructuredQuery) > 0) {
386 $this->sQuery = join(', ', $this->aStructuredQuery);
387 if ($this->iMaxAddressRank < 30) {
388 $sAllowedTypesSQLList = '(\'place\',\'boundary\')';
393 public function fallbackStructuredQuery()
395 if (!$this->aStructuredQuery) return false;
397 $aParams = $this->aStructuredQuery;
399 if (sizeof($aParams) == 1) return false;
401 $aOrderToFallback = array('postalcode', 'street', 'city', 'county', 'state');
403 foreach ($aOrderToFallback as $sType) {
404 if (isset($aParams[$sType])) {
405 unset($aParams[$sType]);
406 $this->setStructuredQuery(@$aParams['amenity'], @$aParams['street'], @$aParams['city'], @$aParams['county'], @$aParams['state'], @$aParams['country'], @$aParams['postalcode']);
414 public function getDetails($aPlaceIDs)
416 //$aPlaceIDs is an array with key: placeID and value: tiger-housenumber, if found, else -1
417 if (sizeof($aPlaceIDs) == 0) return array();
419 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
421 // Get the details for display (is this a redundant extra step?)
422 $sPlaceIDs = join(',', array_keys($aPlaceIDs));
424 $sImportanceSQL = '';
425 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxSmallSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
426 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " CASE WHEN ST_Contains($this->sViewboxLargeSQL, ST_Collect(centroid)) THEN 1 ELSE 0.75 END * ";
429 $sSQL .= " osm_type,";
433 $sSQL .= " admin_level,";
434 $sSQL .= " rank_search,";
435 $sSQL .= " rank_address,";
436 $sSQL .= " min(place_id) AS place_id, ";
437 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
438 $sSQL .= " country_code, ";
439 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
440 $sSQL .= " get_name_by_language(name, $sLanguagePrefArraySQL) AS placename,";
441 $sSQL .= " get_name_by_language(name, ARRAY['ref']) AS ref,";
442 if ($this->bIncludeExtraTags) $sSQL .= "hstore_to_json(extratags)::text AS extra,";
443 if ($this->bIncludeNameDetails) $sSQL .= "hstore_to_json(name)::text AS names,";
444 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
445 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
446 $sSQL .= " ".$sImportanceSQL."COALESCE(importance,0.75-(rank_search::float/40)) AS importance, ";
448 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
450 $sSQL .= " place_addressline s, ";
451 $sSQL .= " placex p";
452 $sSQL .= " WHERE s.place_id = min(CASE WHEN placex.rank_search < 28 THEN placex.place_id ELSE placex.parent_place_id END)";
453 $sSQL .= " AND p.place_id = s.address_place_id ";
454 $sSQL .= " AND s.isaddress ";
455 $sSQL .= " AND p.importance is not null ";
456 $sSQL .= " ) AS addressimportance, ";
457 $sSQL .= " (extratags->'place') AS extra_place ";
458 $sSQL .= " FROM placex";
459 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
461 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
462 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
463 $sSQL .= " OR (extratags->'place') = 'city'";
465 if ($this->aAddressRankList) {
466 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
469 if ($this->sAllowedTypesSQLList) {
470 $sSQL .= "AND placex.class in $this->sAllowedTypesSQLList ";
472 $sSQL .= " AND linked_place_id is null ";
473 $sSQL .= " GROUP BY ";
474 $sSQL .= " osm_type, ";
475 $sSQL .= " osm_id, ";
478 $sSQL .= " admin_level, ";
479 $sSQL .= " rank_search, ";
480 $sSQL .= " rank_address, ";
481 $sSQL .= " country_code, ";
482 $sSQL .= " importance, ";
483 if (!$this->bDeDupe) $sSQL .= "place_id,";
484 $sSQL .= " langaddress, ";
485 $sSQL .= " placename, ";
487 if ($this->bIncludeExtraTags) $sSQL .= "extratags, ";
488 if ($this->bIncludeNameDetails) $sSQL .= "name, ";
489 $sSQL .= " extratags->'place' ";
494 $sSQL .= " 'P' as osm_type,";
495 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id = parent_place_id) as osm_id,";
496 $sSQL .= " 'place' as class, 'postcode' as type,";
497 $sSQL .= " null as admin_level, rank_search, rank_address,";
498 $sSQL .= " place_id, parent_place_id, country_code,";
499 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress,";
500 $sSQL .= " postcode as placename,";
501 $sSQL .= " postcode as ref,";
502 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra,";
503 if ($this->bIncludeNameDetails) $sSQL .= "null AS names,";
504 $sSQL .= " ST_x(st_centroid(geometry)) AS lon, ST_y(st_centroid(geometry)) AS lat,";
505 $sSQL .= $sImportanceSQL."(0.75-(rank_search::float/40)) AS importance, ";
507 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
509 $sSQL .= " place_addressline s, ";
510 $sSQL .= " placex p";
511 $sSQL .= " WHERE s.place_id = parent_place_id";
512 $sSQL .= " AND p.place_id = s.address_place_id ";
513 $sSQL .= " AND s.isaddress";
514 $sSQL .= " AND p.importance is not null";
515 $sSQL .= " ) AS addressimportance, ";
516 $sSQL .= " null AS extra_place ";
517 $sSQL .= "FROM location_postcode";
518 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
520 if (30 >= $this->iMinAddressRank && 30 <= $this->iMaxAddressRank) {
521 // only Tiger housenumbers and interpolation lines need to be interpolated, because they are saved as lines
522 // with start- and endnumber, the common osm housenumbers are usually saved as points
525 $length = count($aPlaceIDs);
526 foreach ($aPlaceIDs as $placeID => $housenumber) {
528 $sHousenumbers .= "(".$placeID.", ".$housenumber.")";
529 if ($i<$length) $sHousenumbers .= ", ";
532 if (CONST_Use_US_Tiger_Data) {
533 // Tiger search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
536 $sSQL .= " 'T' AS osm_type, ";
537 $sSQL .= " (SELECT osm_id from placex p WHERE p.place_id=min(blub.parent_place_id)) as 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 .= " 'us' 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."-1.15 AS importance, ";
555 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
557 $sSQL .= " place_addressline s, ";
558 $sSQL .= " placex p";
559 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id)";
560 $sSQL .= " AND p.place_id = s.address_place_id ";
561 $sSQL .= " AND s.isaddress";
562 $sSQL .= " AND p.importance is not null";
563 $sSQL .= " ) AS addressimportance, ";
564 $sSQL .= " null AS extra_place ";
566 $sSQL .= " SELECT place_id, "; // interpolate the Tiger housenumbers here
567 $sSQL .= " ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) AS centroid, ";
568 $sSQL .= " parent_place_id, ";
569 $sSQL .= " housenumber_for_place";
571 $sSQL .= " location_property_tiger ";
572 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)) ";
574 $sSQL .= " housenumber_for_place>=0";
575 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
576 $sSQL .= " ) AS blub"; //postgres wants an alias here
577 $sSQL .= " GROUP BY";
578 $sSQL .= " place_id, ";
579 $sSQL .= " housenumber_for_place"; //is this group by really needed?, place_id + housenumber (in combination) are unique
580 if (!$this->bDeDupe) $sSQL .= ", place_id ";
583 // interpolation line search only if a housenumber was searched and if it was found (i.e. aPlaceIDs[placeID] = housenumber != -1) (realized through a join)
586 $sSQL .= " 'W' AS osm_type, ";
587 $sSQL .= " osm_id, ";
588 $sSQL .= " 'place' AS class, ";
589 $sSQL .= " 'house' AS type, ";
590 $sSQL .= " null AS admin_level, ";
591 $sSQL .= " 30 AS rank_search, ";
592 $sSQL .= " 30 AS rank_address, ";
593 $sSQL .= " min(place_id) as place_id, ";
594 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
595 $sSQL .= " country_code, ";
596 $sSQL .= " get_address_by_language(place_id, housenumber_for_place, $sLanguagePrefArraySQL) AS langaddress, ";
597 $sSQL .= " null AS placename, ";
598 $sSQL .= " null AS ref, ";
599 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
600 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
601 $sSQL .= " AVG(st_x(centroid)) AS lon, ";
602 $sSQL .= " AVG(st_y(centroid)) AS lat, ";
603 $sSQL .= " ".$sImportanceSQL."-0.1 AS importance, "; // slightly smaller than the importance for normal houses with rank 30, which is 0
606 $sSQL .= " MAX(p.importance*(p.rank_address+2)) ";
608 $sSQL .= " place_addressline s, ";
609 $sSQL .= " placex p";
610 $sSQL .= " WHERE s.place_id = min(blub.parent_place_id) ";
611 $sSQL .= " AND p.place_id = s.address_place_id ";
612 $sSQL .= " AND s.isaddress ";
613 $sSQL .= " AND p.importance is not null";
614 $sSQL .= " ) AS addressimportance,";
615 $sSQL .= " null AS extra_place ";
618 $sSQL .= " osm_id, ";
619 $sSQL .= " place_id, ";
620 $sSQL .= " country_code, ";
621 $sSQL .= " CASE "; // interpolate the housenumbers here
622 $sSQL .= " WHEN startnumber != endnumber ";
623 $sSQL .= " THEN ST_LineInterpolatePoint(linegeo, (housenumber_for_place-startnumber::float)/(endnumber-startnumber)::float) ";
624 $sSQL .= " ELSE ST_LineInterpolatePoint(linegeo, 0.5) ";
625 $sSQL .= " END as centroid, ";
626 $sSQL .= " parent_place_id, ";
627 $sSQL .= " housenumber_for_place ";
629 $sSQL .= " location_property_osmline ";
630 $sSQL .= " JOIN (values ".$sHousenumbers.") AS housenumbers(place_id, housenumber_for_place) USING(place_id)";
632 $sSQL .= " WHERE housenumber_for_place>=0 ";
633 $sSQL .= " AND 30 between $this->iMinAddressRank AND $this->iMaxAddressRank";
634 $sSQL .= " ) as blub"; //postgres wants an alias here
635 $sSQL .= " GROUP BY ";
636 $sSQL .= " osm_id, ";
637 $sSQL .= " place_id, ";
638 $sSQL .= " housenumber_for_place, ";
639 $sSQL .= " country_code "; //is this group by really needed?, place_id + housenumber (in combination) are unique
640 if (!$this->bDeDupe) $sSQL .= ", place_id ";
642 if (CONST_Use_Aux_Location_data) {
645 $sSQL .= " 'L' AS osm_type, ";
646 $sSQL .= " place_id AS osm_id, ";
647 $sSQL .= " 'place' AS class,";
648 $sSQL .= " 'house' AS type, ";
649 $sSQL .= " null AS admin_level, ";
650 $sSQL .= " 0 AS rank_search,";
651 $sSQL .= " 0 AS rank_address, ";
652 $sSQL .= " min(place_id) AS place_id,";
653 $sSQL .= " min(parent_place_id) AS parent_place_id, ";
654 $sSQL .= " 'us' AS country_code, ";
655 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) AS langaddress, ";
656 $sSQL .= " null AS placename, ";
657 $sSQL .= " null AS ref, ";
658 if ($this->bIncludeExtraTags) $sSQL .= "null AS extra, ";
659 if ($this->bIncludeNameDetails) $sSQL .= "null AS names, ";
660 $sSQL .= " avg(ST_X(centroid)) AS lon, ";
661 $sSQL .= " avg(ST_Y(centroid)) AS lat, ";
662 $sSQL .= " ".$sImportanceSQL."-1.10 AS importance, ";
664 $sSQL .= " SELECT max(p.importance*(p.rank_address+2))";
666 $sSQL .= " place_addressline s, ";
667 $sSQL .= " placex p";
668 $sSQL .= " WHERE s.place_id = min(location_property_aux.parent_place_id)";
669 $sSQL .= " AND p.place_id = s.address_place_id ";
670 $sSQL .= " AND s.isaddress";
671 $sSQL .= " AND p.importance is not null";
672 $sSQL .= " ) AS addressimportance, ";
673 $sSQL .= " null AS extra_place ";
674 $sSQL .= " FROM location_property_aux ";
675 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
676 $sSQL .= " AND 30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
677 $sSQL .= " GROUP BY ";
678 $sSQL .= " place_id, ";
679 if (!$this->bDeDupe) $sSQL .= "place_id, ";
680 $sSQL .= " get_address_by_language(place_id, -1, $sLanguagePrefArraySQL) ";
684 $sSQL .= " order by importance desc";
689 $aSearchResults = chksql(
690 $this->oDB->getAll($sSQL),
691 "Could not get details for place."
694 return $aSearchResults;
697 public function getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery)
700 Calculate all searches using aValidTokens i.e.
701 'Wodsworth Road, Sheffield' =>
705 0 1 (wodsworth)(road)
708 Score how good the search is so they can be ordered
710 foreach ($aPhrases as $iPhrase => $aPhrase) {
711 $aNewPhraseSearches = array();
712 if ($bStructuredPhrases) $sPhraseType = $aPhraseTypes[$iPhrase];
713 else $sPhraseType = '';
715 foreach ($aPhrase['wordsets'] as $iWordSet => $aWordset) {
716 // Too many permutations - too expensive
717 if ($iWordSet > 120) break;
719 $aWordsetSearches = $aSearches;
721 // Add all words from this wordset
722 foreach ($aWordset as $iToken => $sToken) {
723 //echo "<br><b>$sToken</b>";
724 $aNewWordsetSearches = array();
726 foreach ($aWordsetSearches as $aCurrentSearch) {
728 //var_dump($aCurrentSearch);
731 // If the token is valid
732 if (isset($aValidTokens[' '.$sToken])) {
733 foreach ($aValidTokens[' '.$sToken] as $aSearchTerm) {
734 $aSearch = $aCurrentSearch;
735 $aSearch['iSearchRank']++;
736 if (($sPhraseType == '' || $sPhraseType == 'country') && !empty($aSearchTerm['country_code']) && $aSearchTerm['country_code'] != '0') {
737 if ($aSearch['sCountryCode'] === false) {
738 $aSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
739 // Country is almost always at the end of the string - increase score for finding it anywhere else (optimisation)
740 if (($iToken+1 != sizeof($aWordset) || $iPhrase+1 != sizeof($aPhrases))) {
741 $aSearch['iSearchRank'] += 5;
743 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
745 } elseif (isset($aSearchTerm['lat']) && $aSearchTerm['lat'] !== '' && $aSearchTerm['lat'] !== null) {
746 if ($aSearch['oNear'] === false) {
747 $aSearch['oNear'] = new NearPoint(
750 $aSearchTerm['radius']
752 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
754 } elseif ($sPhraseType == 'postalcode' || ($aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode')) {
755 // 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
756 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'] && strpos($sNormQuery, $this->normTerm($aSearchTerm['word'])) !== false) {
757 // If we have structured search or this is the first term,
758 // make the postcode the primary search element.
759 if ($aSearchTerm['operator'] == '' && ($sPhraseType == 'postalcode' || sizeof($aSearch['aName']) == 0)) {
760 $aNewSearch = $aSearch;
761 $aNewSearch['sOperator'] = 'postcode';
762 $aNewSearch['aAddress'] = array_merge($aNewSearch['aAddress'], $aNewSearch['aName']);
763 $aNewSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word'];
764 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aNewSearch;
767 // If we have a structured search or this is not the first term,
768 // add the postcode as an addendum.
769 if ($sPhraseType == 'postalcode' || sizeof($aSearch['aName'])) {
770 $aSearch['sPostcode'] = $aSearchTerm['word'];
771 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
774 } elseif (($sPhraseType == '' || $sPhraseType == 'street') && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house') {
775 if ($aSearch['sHouseNumber'] === '') {
776 $aSearch['sHouseNumber'] = $sToken;
777 // sanity check: if the housenumber is not mainly made
778 // up of numbers, add a penalty
779 if (preg_match_all("/[^0-9]/", $sToken, $aMatches) > 2) $aSearch['iSearchRank']++;
780 // also housenumbers should appear in the first or second phrase
781 if ($iPhrase > 1) $aSearch['iSearchRank'] += 1;
782 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
784 // Fall back to not searching for this item (better than nothing)
785 $aSearch = $aCurrentSearch;
786 $aSearch['iSearchRank'] += 1;
787 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
790 } elseif ($sPhraseType == '' && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null) {
791 // require a normalized exact match of the term
792 // if we have the normalizer version of the query
794 if ($aSearch['sClass'] === ''
795 && ($sNormQuery === null || !($aSearchTerm['word'] && strpos($sNormQuery, $aSearchTerm['word']) === false))) {
796 $aSearch['sClass'] = $aSearchTerm['class'];
797 $aSearch['sType'] = $aSearchTerm['type'];
798 if ($aSearchTerm['operator'] == '') {
799 $aSearch['sOperator'] = sizeof($aSearch['aName']) ? 'name' : 'near';
800 $aSearch['iSearchRank'] += 2;
802 $aSearch['sOperator'] = 'near'; // near = in for the moment
805 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
807 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
808 if (sizeof($aSearch['aName'])) {
809 if ((!$bStructuredPhrases || $iPhrase > 0) && $sPhraseType != 'country' && (!isset($aValidTokens[$sToken]) || strpos($sToken, ' ') !== false)) {
810 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
812 $aCurrentSearch['aFullNameAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
813 $aSearch['iSearchRank'] += 1000; // skip;
816 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
817 //$aSearch['iNamePhrase'] = $iPhrase;
819 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
823 // Look for partial matches.
824 // Note that there is no point in adding country terms here
825 // because country are omitted in the address.
826 if (isset($aValidTokens[$sToken]) && $sPhraseType != 'country') {
827 // Allow searching for a word - but at extra cost
828 foreach ($aValidTokens[$sToken] as $aSearchTerm) {
829 if (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
830 if ((!$bStructuredPhrases || $iPhrase > 0) && sizeof($aCurrentSearch['aName']) && strpos($sToken, ' ') === false) {
831 $aSearch = $aCurrentSearch;
832 $aSearch['iSearchRank'] += 1;
833 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
834 $aSearch['aAddress'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
835 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
836 } elseif (isset($aValidTokens[' '.$sToken])) { // revert to the token version?
837 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
838 $aSearch['iSearchRank'] += 1;
839 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
840 foreach ($aValidTokens[' '.$sToken] as $aSearchTermToken) {
841 if (empty($aSearchTermToken['country_code'])
842 && empty($aSearchTermToken['lat'])
843 && empty($aSearchTermToken['class'])
845 $aSearch = $aCurrentSearch;
846 $aSearch['iSearchRank'] += 1;
847 $aSearch['aAddress'][$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
848 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
852 $aSearch['aAddressNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
853 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
854 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
858 if (!sizeof($aCurrentSearch['aName']) || $aCurrentSearch['iNamePhrase'] == $iPhrase) {
859 $aSearch = $aCurrentSearch;
860 $aSearch['iSearchRank'] += 1;
861 if (!sizeof($aCurrentSearch['aName'])) $aSearch['iSearchRank'] += 1;
862 if (preg_match('#^[0-9]+$#', $sToken)) $aSearch['iSearchRank'] += 2;
863 if ($aWordFrequencyScores[$aSearchTerm['word_id']] < CONST_Max_Word_Frequency) {
864 $aSearch['aName'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
866 $aSearch['aNameNonSearch'][$aSearchTerm['word_id']] = $aSearchTerm['word_id'];
868 $aSearch['iNamePhrase'] = $iPhrase;
869 if ($aSearch['iSearchRank'] < $this->iMaxRank) $aNewWordsetSearches[] = $aSearch;
874 // Allow skipping a word - but at EXTREAM cost
875 //$aSearch = $aCurrentSearch;
876 //$aSearch['iSearchRank']+=100;
877 //$aNewWordsetSearches[] = $aSearch;
881 usort($aNewWordsetSearches, 'bySearchRank');
882 $aWordsetSearches = array_slice($aNewWordsetSearches, 0, 50);
884 //var_Dump('<hr>',sizeof($aWordsetSearches)); exit;
886 $aNewPhraseSearches = array_merge($aNewPhraseSearches, $aNewWordsetSearches);
887 usort($aNewPhraseSearches, 'bySearchRank');
889 $aSearchHash = array();
890 foreach ($aNewPhraseSearches as $iSearch => $aSearch) {
891 $sHash = serialize($aSearch);
892 if (isset($aSearchHash[$sHash])) unset($aNewPhraseSearches[$iSearch]);
893 else $aSearchHash[$sHash] = 1;
896 $aNewPhraseSearches = array_slice($aNewPhraseSearches, 0, 50);
899 // Re-group the searches by their score, junk anything over 20 as just not worth trying
900 $aGroupedSearches = array();
901 foreach ($aNewPhraseSearches as $aSearch) {
902 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
903 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
904 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
907 ksort($aGroupedSearches);
910 $aSearches = array();
911 foreach ($aGroupedSearches as $iScore => $aNewSearches) {
912 $iSearchCount += sizeof($aNewSearches);
913 $aSearches = array_merge($aSearches, $aNewSearches);
914 if ($iSearchCount > 50) break;
917 //if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
919 return $aGroupedSearches;
922 /* Perform the actual query lookup.
924 Returns an ordered list of results, each with the following fields:
925 osm_type: type of corresponding OSM object
929 P - postcode (internally computed)
930 osm_id: id of corresponding OSM object
931 class: general object class (corresponds to tag key of primary OSM tag)
932 type: subclass of object (corresponds to tag value of primary OSM tag)
933 admin_level: see http://wiki.openstreetmap.org/wiki/Admin_level
934 rank_search: rank in search hierarchy
935 (see also http://wiki.openstreetmap.org/wiki/Nominatim/Development_overview#Country_to_street_level)
936 rank_address: rank in address hierarchy (determines orer in address)
937 place_id: internal key (may differ between different instances)
938 country_code: ISO country code
939 langaddress: localized full address
940 placename: localized name of object
941 ref: content of ref tag (if available)
944 importance: importance of place based on Wikipedia link count
945 addressimportance: cumulated importance of address elements
946 extra_place: type of place (for admin boundaries, if there is a place tag)
947 aBoundingBox: bounding Box
948 label: short description of the object class/type (English only)
949 name: full name (currently the same as langaddress)
950 foundorder: secondary ordering for places with same importance
954 public function lookup()
956 if (!$this->sQuery && !$this->aStructuredQuery) return array();
958 $sNormQuery = $this->normTerm($this->sQuery);
959 $sLanguagePrefArraySQL = "ARRAY[".join(',', array_map("getDBQuoted", $this->aLangPrefOrder))."]";
960 $sCountryCodesSQL = false;
961 if ($this->aCountryCodes) {
962 $sCountryCodesSQL = join(',', array_map('addQuotes', $this->aCountryCodes));
965 $sQuery = $this->sQuery;
966 if (!preg_match('//u', $sQuery)) {
967 userError("Query string is not UTF-8 encoded.");
970 // Conflicts between US state abreviations and various words for 'the' in different languages
971 if (isset($this->aLangPrefOrder['name:en'])) {
972 $sQuery = preg_replace('/(^|,)\s*il\s*(,|$)/', '\1illinois\2', $sQuery);
973 $sQuery = preg_replace('/(^|,)\s*al\s*(,|$)/', '\1alabama\2', $sQuery);
974 $sQuery = preg_replace('/(^|,)\s*la\s*(,|$)/', '\1louisiana\2', $sQuery);
977 $bBoundingBoxSearch = $this->bBoundedSearch && $this->sViewboxSmallSQL;
978 if ($this->sViewboxCentreSQL) {
979 // For complex viewboxes (routes) precompute the bounding geometry
981 $this->oDB->getOne("select ".$this->sViewboxSmallSQL),
982 "Could not get small viewbox"
984 $this->sViewboxSmallSQL = "'".$sGeom."'::geometry";
987 $this->oDB->getOne("select ".$this->sViewboxLargeSQL),
988 "Could not get large viewbox"
990 $this->sViewboxLargeSQL = "'".$sGeom."'::geometry";
993 // Do we have anything that looks like a lat/lon pair?
995 if ($aLooksLike = NearPoint::extractFromQuery($sQuery)) {
996 $oNearPoint = $aLooksLike['pt'];
997 $sQuery = $aLooksLike['query'];
1000 $aSearchResults = array();
1001 if ($sQuery || $this->aStructuredQuery) {
1002 // Start with a blank search
1006 'iNamePhrase' => -1,
1007 'sCountryCode' => false,
1009 'aAddress' => array(),
1010 'aFullNameAddress' => array(),
1011 'aNameNonSearch' => array(),
1012 'aAddressNonSearch' => array(),
1014 'aFeatureName' => array(),
1017 'sHouseNumber' => '',
1019 'oNear' => $oNearPoint
1023 // Any 'special' terms in the search?
1024 $bSpecialTerms = false;
1025 preg_match_all('/\\[(.*)=(.*)\\]/', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1026 $aSpecialTerms = array();
1027 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1028 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1029 $aSpecialTerms[strtolower($aSpecialTerm[1])] = $aSpecialTerm[2];
1032 preg_match_all('/\\[([\\w ]*)\\]/u', $sQuery, $aSpecialTermsRaw, PREG_SET_ORDER);
1033 $aSpecialTerms = array();
1034 if (isset($this->aStructuredQuery['amenity']) && $this->aStructuredQuery['amenity']) {
1035 $aSpecialTermsRaw[] = array('['.$this->aStructuredQuery['amenity'].']', $this->aStructuredQuery['amenity']);
1036 unset($this->aStructuredQuery['amenity']);
1039 foreach ($aSpecialTermsRaw as $aSpecialTerm) {
1040 $sQuery = str_replace($aSpecialTerm[0], ' ', $sQuery);
1041 $sToken = chksql($this->oDB->getOne("SELECT make_standard_name('".$aSpecialTerm[1]."') AS string"));
1042 $sSQL = 'SELECT * ';
1044 $sSQL .= ' SELECT word_id, word_token, word, class, type, country_code, operator';
1045 $sSQL .= ' FROM word ';
1046 $sSQL .= ' WHERE word_token in (\' '.$sToken.'\')';
1048 $sSQL .= ' WHERE (class is not null AND class not in (\'place\')) ';
1049 $sSQL .= ' OR country_code is not null';
1050 if (CONST_Debug) var_Dump($sSQL);
1051 $aSearchWords = chksql($this->oDB->getAll($sSQL));
1052 $aNewSearches = array();
1053 foreach ($aSearches as $aSearch) {
1054 foreach ($aSearchWords as $aSearchTerm) {
1055 $aNewSearch = $aSearch;
1056 if ($aSearchTerm['country_code']) {
1057 $aNewSearch['sCountryCode'] = strtolower($aSearchTerm['country_code']);
1058 $aNewSearches[] = $aNewSearch;
1059 $bSpecialTerms = true;
1061 if ($aSearchTerm['class']) {
1062 $aNewSearch['sClass'] = $aSearchTerm['class'];
1063 $aNewSearch['sType'] = $aSearchTerm['type'];
1064 $aNewSearches[] = $aNewSearch;
1065 $bSpecialTerms = true;
1069 $aSearches = $aNewSearches;
1072 // Split query into phrases
1073 // Commas are used to reduce the search space by indicating where phrases split
1074 if ($this->aStructuredQuery) {
1075 $aPhrases = $this->aStructuredQuery;
1076 $bStructuredPhrases = true;
1078 $aPhrases = explode(',', $sQuery);
1079 $bStructuredPhrases = false;
1082 // Convert each phrase to standard form
1083 // Create a list of standard words
1084 // Get all 'sets' of words
1085 // Generate a complete list of all
1087 foreach ($aPhrases as $iPhrase => $sPhrase) {
1089 $this->oDB->getRow("SELECT make_standard_name('".pg_escape_string($sPhrase)."') as string"),
1090 "Cannot normalize query string (is it a UTF-8 string?)"
1092 if (trim($aPhrase['string'])) {
1093 $aPhrases[$iPhrase] = $aPhrase;
1094 $aPhrases[$iPhrase]['words'] = explode(' ', $aPhrases[$iPhrase]['string']);
1095 $aPhrases[$iPhrase]['wordsets'] = getWordSets($aPhrases[$iPhrase]['words'], 0);
1096 $aTokens = array_merge($aTokens, getTokensFromSets($aPhrases[$iPhrase]['wordsets']));
1098 unset($aPhrases[$iPhrase]);
1102 // Reindex phrases - we make assumptions later on that they are numerically keyed in order
1103 $aPhraseTypes = array_keys($aPhrases);
1104 $aPhrases = array_values($aPhrases);
1106 if (sizeof($aTokens)) {
1107 // Check which tokens we have, get the ID numbers
1108 $sSQL = 'SELECT word_id, word_token, word, class, type, country_code, operator, search_name_count';
1109 $sSQL .= ' FROM word ';
1110 $sSQL .= ' WHERE word_token in ('.join(',', array_map("getDBQuoted", $aTokens)).')';
1112 if (CONST_Debug) var_Dump($sSQL);
1114 $aValidTokens = array();
1115 if (sizeof($aTokens)) {
1116 $aDatabaseWords = chksql(
1117 $this->oDB->getAll($sSQL),
1118 "Could not get word tokens."
1121 $aDatabaseWords = array();
1123 $aPossibleMainWordIDs = array();
1124 $aWordFrequencyScores = array();
1125 foreach ($aDatabaseWords as $aToken) {
1126 // Very special case - require 2 letter country param to match the country code found
1127 if ($bStructuredPhrases && $aToken['country_code'] && !empty($this->aStructuredQuery['country'])
1128 && strlen($this->aStructuredQuery['country']) == 2 && strtolower($this->aStructuredQuery['country']) != $aToken['country_code']
1133 if (isset($aValidTokens[$aToken['word_token']])) {
1134 $aValidTokens[$aToken['word_token']][] = $aToken;
1136 $aValidTokens[$aToken['word_token']] = array($aToken);
1138 if (!$aToken['class'] && !$aToken['country_code']) $aPossibleMainWordIDs[$aToken['word_id']] = 1;
1139 $aWordFrequencyScores[$aToken['word_id']] = $aToken['search_name_count'] + 1;
1141 if (CONST_Debug) var_Dump($aPhrases, $aValidTokens);
1143 // US ZIP+4 codes - if there is no token, merge in the 5-digit ZIP code
1144 foreach ($aTokens as $sToken) {
1145 if (!isset($aValidTokens[$sToken]) && preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
1146 if (isset($aValidTokens[$aData[1]])) {
1147 foreach ($aValidTokens[$aData[1]] as $aToken) {
1148 if (!$aToken['class']) {
1149 if (isset($aValidTokens[$sToken])) {
1150 $aValidTokens[$sToken][] = $aToken;
1152 $aValidTokens[$sToken] = array($aToken);
1160 foreach ($aTokens as $sToken) {
1161 // Unknown single word token with a number - assume it is a house number
1162 if (!isset($aValidTokens[' '.$sToken]) && strpos($sToken, ' ') === false && preg_match('/[0-9]/', $sToken)) {
1163 $aValidTokens[' '.$sToken] = array(array('class' => 'place', 'type' => 'house'));
1167 // Any words that have failed completely?
1168 // TODO: suggestions
1170 // Start the search process
1171 // array with: placeid => -1 | tiger-housenumber
1172 $aResultPlaceIDs = array();
1174 $aGroupedSearches = $this->getGroupedSearches($aSearches, $aPhraseTypes, $aPhrases, $aValidTokens, $aWordFrequencyScores, $bStructuredPhrases, $sNormQuery);
1176 if ($this->bReverseInPlan) {
1177 // Reverse phrase array and also reverse the order of the wordsets in
1178 // the first and final phrase. Don't bother about phrases in the middle
1179 // because order in the address doesn't matter.
1180 $aPhrases = array_reverse($aPhrases);
1181 $aPhrases[0]['wordsets'] = getInverseWordSets($aPhrases[0]['words'], 0);
1182 if (sizeof($aPhrases) > 1) {
1183 $aFinalPhrase = end($aPhrases);
1184 $aPhrases[sizeof($aPhrases)-1]['wordsets'] = getInverseWordSets($aFinalPhrase['words'], 0);
1186 $aReverseGroupedSearches = $this->getGroupedSearches($aSearches, null, $aPhrases, $aValidTokens, $aWordFrequencyScores, false, $sNormQuery);
1188 foreach ($aGroupedSearches as $aSearches) {
1189 foreach ($aSearches as $aSearch) {
1190 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1191 if (!isset($aReverseGroupedSearches[$aSearch['iSearchRank']])) $aReverseGroupedSearches[$aSearch['iSearchRank']] = array();
1192 $aReverseGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1197 $aGroupedSearches = $aReverseGroupedSearches;
1198 ksort($aGroupedSearches);
1201 // Re-group the searches by their score, junk anything over 20 as just not worth trying
1202 $aGroupedSearches = array();
1203 foreach ($aSearches as $aSearch) {
1204 if ($aSearch['iSearchRank'] < $this->iMaxRank) {
1205 if (!isset($aGroupedSearches[$aSearch['iSearchRank']])) $aGroupedSearches[$aSearch['iSearchRank']] = array();
1206 $aGroupedSearches[$aSearch['iSearchRank']][] = $aSearch;
1209 ksort($aGroupedSearches);
1212 if (CONST_Debug) var_Dump($aGroupedSearches);
1213 if (CONST_Search_TryDroppedAddressTerms && sizeof($this->aStructuredQuery) > 0) {
1214 $aCopyGroupedSearches = $aGroupedSearches;
1215 foreach ($aCopyGroupedSearches as $iGroup => $aSearches) {
1216 foreach ($aSearches as $iSearch => $aSearch) {
1217 $aReductionsList = array($aSearch['aAddress']);
1218 $iSearchRank = $aSearch['iSearchRank'];
1219 while (sizeof($aReductionsList) > 0) {
1221 if ($iSearchRank > iMaxRank) break 3;
1222 $aNewReductionsList = array();
1223 foreach ($aReductionsList as $aReductionsWordList) {
1224 for ($iReductionWord = 0; $iReductionWord < sizeof($aReductionsWordList); $iReductionWord++) {
1225 $aReductionsWordListResult = array_merge(array_slice($aReductionsWordList, 0, $iReductionWord), array_slice($aReductionsWordList, $iReductionWord+1));
1226 $aReverseSearch = $aSearch;
1227 $aSearch['aAddress'] = $aReductionsWordListResult;
1228 $aSearch['iSearchRank'] = $iSearchRank;
1229 $aGroupedSearches[$iSearchRank][] = $aReverseSearch;
1230 if (sizeof($aReductionsWordListResult) > 0) {
1231 $aNewReductionsList[] = $aReductionsWordListResult;
1235 $aReductionsList = $aNewReductionsList;
1239 ksort($aGroupedSearches);
1242 // Filter out duplicate searches
1243 $aSearchHash = array();
1244 foreach ($aGroupedSearches as $iGroup => $aSearches) {
1245 foreach ($aSearches as $iSearch => $aSearch) {
1246 $sHash = serialize($aSearch);
1247 if (isset($aSearchHash[$sHash])) {
1248 unset($aGroupedSearches[$iGroup][$iSearch]);
1249 if (sizeof($aGroupedSearches[$iGroup]) == 0) unset($aGroupedSearches[$iGroup]);
1251 $aSearchHash[$sHash] = 1;
1256 if (CONST_Debug) _debugDumpGroupedSearches($aGroupedSearches, $aValidTokens);
1260 foreach ($aGroupedSearches as $iGroupedRank => $aSearches) {
1262 foreach ($aSearches as $aSearch) {
1264 $searchedHousenumber = -1;
1266 if (CONST_Debug) echo "<hr><b>Search Loop, group $iGroupLoop, loop $iQueryLoop</b>";
1267 if (CONST_Debug) _debugDumpGroupedSearches(array($iGroupedRank => array($aSearch)), $aValidTokens);
1269 if ($sCountryCodesSQL && $aSearch['sCountryCode'] && !in_array($aSearch['sCountryCode'], $this->aCountryCodes)) {
1273 // No location term?
1274 if (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['oNear']) {
1275 if ($aSearch['sCountryCode'] && !$aSearch['sClass'] && !$aSearch['sHouseNumber']) {
1276 // Just looking for a country by code - look it up
1277 if (4 >= $this->iMinAddressRank && 4 <= $this->iMaxAddressRank) {
1278 $sSQL = "SELECT place_id FROM placex WHERE country_code='".$aSearch['sCountryCode']."' AND rank_search = 4";
1279 if ($bBoundingBoxSearch)
1280 $sSQL .= " AND _st_intersects($this->sViewboxSmallSQL, geometry)";
1281 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
1282 if (CONST_Debug) var_dump($sSQL);
1283 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1285 $aPlaceIDs = array();
1288 if (!$bBoundingBoxSearch && !$aSearch['oNear']) continue;
1289 if (!$aSearch['sClass']) continue;
1291 $sSQL = "SELECT COUNT(*) FROM pg_tables WHERE tablename = 'place_classtype_".$aSearch['sClass']."_".$aSearch['sType']."'";
1292 if (chksql($this->oDB->getOne($sSQL))) {
1293 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1294 if ($sCountryCodesSQL) $sSQL .= " JOIN placex USING (place_id)";
1295 $sSQL .= " WHERE st_contains($this->sViewboxSmallSQL, ct.centroid)";
1296 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1297 if (sizeof($this->aExcludePlaceIDs)) {
1298 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1300 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1301 $sSQL .= " limit $this->iLimit";
1302 if (CONST_Debug) var_dump($sSQL);
1303 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1305 // If excluded place IDs are given, it is fair to assume that
1306 // there have been results in the small box, so no further
1307 // expansion in that case.
1308 // Also don't expand if bounded results were requested.
1309 if (!sizeof($aPlaceIDs) && !sizeof($this->aExcludePlaceIDs) && !$this->bBoundedSearch) {
1310 $sSQL = "SELECT place_id FROM place_classtype_".$aSearch['sClass']."_".$aSearch['sType']." ct";
1311 if ($sCountryCodesSQL) $sSQL .= " join placex using (place_id)";
1312 $sSQL .= " WHERE ST_Contains($this->sViewboxLargeSQL, ct.centroid)";
1313 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1314 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, ct.centroid) ASC";
1315 $sSQL .= " LIMIT $this->iLimit";
1316 if (CONST_Debug) var_dump($sSQL);
1317 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1320 $sSQL = "SELECT place_id ";
1321 $sSQL .= "FROM placex ";
1322 $sSQL .= "WHERE class='".$aSearch['sClass']."' ";
1323 $sSQL .= " AND type='".$aSearch['sType']."'";
1324 $sSQL .= " AND ST_Contains($this->sViewboxSmallSQL, geometry) ";
1325 $sSQL .= " AND linked_place_id is null";
1326 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1327 if ($this->sViewboxCentreSQL) $sSQL .= " ORDER BY ST_Distance($this->sViewboxCentreSQL, centroid) ASC";
1328 $sSQL .= " LIMIT $this->iLimit";
1329 if (CONST_Debug) var_dump($sSQL);
1330 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1333 } elseif ($aSearch['oNear'] && !sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && !$aSearch['sClass']) {
1334 // If a coordinate is given, the search must either
1335 // be for a name or a special search. Ignore everythin else.
1336 $aPlaceIDs = array();
1337 } elseif ($aSearch['sOperator'] == 'postcode') {
1338 $sSQL = "SELECT p.place_id FROM location_postcode p ";
1339 if (sizeof($aSearch['aAddress'])) {
1340 $sSQL .= ", search_name s ";
1341 $sSQL .= "WHERE s.place_id = p.parent_place_id ";
1342 $sSQL .= "AND array_cat(s.nameaddress_vector, s.name_vector) @> ARRAY[".join($aSearch['aAddress'], ",")."] AND ";
1346 $sSQL .= "p.postcode = '".pg_escape_string(reset($aSearch['aName']))."'";
1347 if ($aSearch['sCountryCode']) {
1348 $sSQL .= " AND p.country_code = '".$aSearch['sCountryCode']."'";
1349 } elseif ($sCountryCodesSQL) {
1350 $sSQL .= " AND p.country_code in ($sCountryCodesSQL)";
1352 $sSQL .= " LIMIT $this->iLimit";
1353 if (CONST_Debug) var_dump($sSQL);
1354 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1356 $aPlaceIDs = array();
1358 // First we need a position, either aName or fLat or both
1362 if ($aSearch['sHouseNumber'] && sizeof($aSearch['aAddress'])) {
1363 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1366 $aOrder[0] .= " EXISTS(";
1367 $aOrder[0] .= " SELECT place_id ";
1368 $aOrder[0] .= " FROM placex ";
1369 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1370 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."' ";
1371 $aOrder[0] .= " LIMIT 1";
1372 $aOrder[0] .= " ) ";
1373 // also housenumbers from interpolation lines table are needed
1374 $aOrder[0] .= " OR EXISTS(";
1375 $aOrder[0] .= " SELECT place_id ";
1376 $aOrder[0] .= " FROM location_property_osmline ";
1377 $aOrder[0] .= " WHERE parent_place_id = search_name.place_id";
1378 $aOrder[0] .= " AND startnumber is not NULL";
1379 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber']).">=startnumber ";
1380 $aOrder[0] .= " AND ".intval($aSearch['sHouseNumber'])."<=endnumber ";
1381 $aOrder[0] .= " LIMIT 1";
1384 $aOrder[0] .= " DESC";
1387 // TODO: filter out the pointless search terms (2 letter name tokens and less)
1388 // they might be right - but they are just too darned expensive to run
1389 if (sizeof($aSearch['aName'])) $aTerms[] = "name_vector @> ARRAY[".join($aSearch['aName'], ",")."]";
1390 if (sizeof($aSearch['aNameNonSearch'])) $aTerms[] = "array_cat(name_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aNameNonSearch'], ",")."]";
1391 if (sizeof($aSearch['aAddress']) && $aSearch['aName'] != $aSearch['aAddress']) {
1392 // For infrequent name terms disable index usage for address
1393 if (CONST_Search_NameOnlySearchFrequencyThreshold
1394 && sizeof($aSearch['aName']) == 1
1395 && $aWordFrequencyScores[$aSearch['aName'][reset($aSearch['aName'])]] < CONST_Search_NameOnlySearchFrequencyThreshold
1397 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join(array_merge($aSearch['aAddress'], $aSearch['aAddressNonSearch']), ",")."]";
1399 $aTerms[] = "nameaddress_vector @> ARRAY[".join($aSearch['aAddress'], ",")."]";
1400 if (sizeof($aSearch['aAddressNonSearch'])) {
1401 $aTerms[] = "array_cat(nameaddress_vector,ARRAY[]::integer[]) @> ARRAY[".join($aSearch['aAddressNonSearch'], ",")."]";
1405 if ($aSearch['sCountryCode']) $aTerms[] = "country_code = '".pg_escape_string($aSearch['sCountryCode'])."'";
1406 if ($aSearch['sHouseNumber']) {
1407 $aTerms[] = "address_rank between 16 and 27";
1409 if ($this->iMinAddressRank > 0) {
1410 $aTerms[] = "address_rank >= ".$this->iMinAddressRank;
1412 if ($this->iMaxAddressRank < 30) {
1413 $aTerms[] = "address_rank <= ".$this->iMaxAddressRank;
1416 if ($aSearch['oNear']) {
1417 $aTerms[] = $aSearch['oNear']->withinSQL('centroid');
1419 $aOrder[] = $aSearch['oNear']->distanceSQL('centroid');
1420 } elseif ($aSearch['sPostcode']) {
1421 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$aSearch['sPostcode']."')";
1423 if (sizeof($this->aExcludePlaceIDs)) {
1424 $aTerms[] = "place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1426 if ($sCountryCodesSQL) {
1427 $aTerms[] = "country_code in ($sCountryCodesSQL)";
1430 if ($bBoundingBoxSearch) $aTerms[] = "centroid && $this->sViewboxSmallSQL";
1432 $aOrder[] = $oNearPoint->distanceSQL('centroid');
1435 if ($aSearch['sHouseNumber']) {
1436 $sImportanceSQL = '- abs(26 - address_rank) + 3';
1438 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
1440 if ($this->sViewboxSmallSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxSmallSQL, centroid) THEN 1 ELSE 0.5 END";
1441 if ($this->sViewboxLargeSQL) $sImportanceSQL .= " * CASE WHEN ST_Contains($this->sViewboxLargeSQL, centroid) THEN 1 ELSE 0.5 END";
1443 $aOrder[] = "$sImportanceSQL DESC";
1444 if (sizeof($aSearch['aFullNameAddress'])) {
1445 $sExactMatchSQL = ' ( ';
1446 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
1447 $sExactMatchSQL .= ' SELECT unnest(ARRAY['.join($aSearch['aFullNameAddress'], ",").']) ';
1448 $sExactMatchSQL .= ' INTERSECT ';
1449 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
1450 $sExactMatchSQL .= ' ) s';
1451 $sExactMatchSQL .= ') as exactmatch';
1452 $aOrder[] = 'exactmatch DESC';
1454 $sExactMatchSQL = '0::int as exactmatch';
1457 if (sizeof($aTerms)) {
1458 $sSQL = "SELECT place_id, ";
1459 $sSQL .= $sExactMatchSQL;
1460 $sSQL .= " FROM search_name";
1461 $sSQL .= " WHERE ".join(' and ', $aTerms);
1462 $sSQL .= " ORDER BY ".join(', ', $aOrder);
1463 if ($aSearch['sHouseNumber'] || $aSearch['sClass']) {
1464 $sSQL .= " LIMIT 20";
1465 } elseif (!sizeof($aSearch['aName']) && !sizeof($aSearch['aAddress']) && $aSearch['sClass']) {
1466 $sSQL .= " LIMIT 1";
1468 $sSQL .= " LIMIT ".$this->iLimit;
1471 if (CONST_Debug) var_dump($sSQL);
1472 $aViewBoxPlaceIDs = chksql(
1473 $this->oDB->getAll($sSQL),
1474 "Could not get places for search terms."
1476 //var_dump($aViewBoxPlaceIDs);
1477 // Did we have an viewbox matches?
1478 $aPlaceIDs = array();
1479 $bViewBoxMatch = false;
1480 foreach ($aViewBoxPlaceIDs as $aViewBoxRow) {
1481 //if ($bViewBoxMatch == 1 && $aViewBoxRow['in_small'] == 'f') break;
1482 //if ($bViewBoxMatch == 2 && $aViewBoxRow['in_large'] == 'f') break;
1483 //if ($aViewBoxRow['in_small'] == 't') $bViewBoxMatch = 1;
1484 //else if ($aViewBoxRow['in_large'] == 't') $bViewBoxMatch = 2;
1485 $aPlaceIDs[] = $aViewBoxRow['place_id'];
1486 $this->exactMatchCache[$aViewBoxRow['place_id']] = $aViewBoxRow['exactmatch'];
1489 //var_Dump($aPlaceIDs);
1492 //now search for housenumber, if housenumber provided
1493 if ($aSearch['sHouseNumber'] && sizeof($aPlaceIDs)) {
1494 $searchedHousenumber = intval($aSearch['sHouseNumber']);
1495 $aRoadPlaceIDs = $aPlaceIDs;
1496 $sPlaceIDs = join(',', $aPlaceIDs);
1498 // Now they are indexed, look for a house attached to a street we found
1499 $sHouseNumberRegex = '\\\\m'.$aSearch['sHouseNumber'].'\\\\M';
1500 $sSQL = "SELECT place_id FROM placex ";
1501 $sSQL .= "WHERE parent_place_id in (".$sPlaceIDs.") and transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
1502 if (sizeof($this->aExcludePlaceIDs)) {
1503 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1505 $sSQL .= " LIMIT $this->iLimit";
1506 if (CONST_Debug) var_dump($sSQL);
1507 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1509 // if nothing found, search in the interpolation line table
1510 if (!sizeof($aPlaceIDs)) {
1511 // do we need to use transliteration and the regex for housenumbers???
1512 //new query for lines, not housenumbers anymore
1513 $sSQL = "SELECT distinct place_id FROM location_property_osmline";
1514 $sSQL .= " WHERE startnumber is not NULL and parent_place_id in (".$sPlaceIDs.") and (";
1515 if ($searchedHousenumber%2 == 0) {
1516 //if housenumber is even, look for housenumber in streets with interpolationtype even or all
1517 $sSQL .= "interpolationtype='even'";
1519 //look for housenumber in streets with interpolationtype odd or all
1520 $sSQL .= "interpolationtype='odd'";
1522 $sSQL .= " or interpolationtype='all') and ";
1523 $sSQL .= $searchedHousenumber.">=startnumber and ";
1524 $sSQL .= $searchedHousenumber."<=endnumber";
1526 if (sizeof($this->aExcludePlaceIDs)) {
1527 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1529 //$sSQL .= " limit $this->iLimit";
1530 if (CONST_Debug) var_dump($sSQL);
1532 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1535 // If nothing found try the aux fallback table
1536 if (CONST_Use_Aux_Location_data && !sizeof($aPlaceIDs)) {
1537 $sSQL = "SELECT place_id FROM location_property_aux ";
1538 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") ";
1539 $sSQL .= " AND housenumber = '".pg_escape_string($aSearch['sHouseNumber'])."'";
1540 if (sizeof($this->aExcludePlaceIDs)) {
1541 $sSQL .= " AND parent_place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1543 //$sSQL .= " limit $this->iLimit";
1544 if (CONST_Debug) var_dump($sSQL);
1545 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1548 //if nothing was found in placex or location_property_aux, then search in Tiger data for this housenumber(location_property_tiger)
1549 if (CONST_Use_US_Tiger_Data && !sizeof($aPlaceIDs)) {
1550 $sSQL = "SELECT distinct place_id FROM location_property_tiger";
1551 $sSQL .= " WHERE parent_place_id in (".$sPlaceIDs.") and (";
1552 if ($searchedHousenumber%2 == 0) {
1553 $sSQL .= "interpolationtype='even'";
1555 $sSQL .= "interpolationtype='odd'";
1557 $sSQL .= " or interpolationtype='all') and ";
1558 $sSQL .= $searchedHousenumber.">=startnumber and ";
1559 $sSQL .= $searchedHousenumber."<=endnumber";
1561 if (sizeof($this->aExcludePlaceIDs)) {
1562 $sSQL .= " AND place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1564 //$sSQL .= " limit $this->iLimit";
1565 if (CONST_Debug) var_dump($sSQL);
1567 $aPlaceIDs = chksql($this->oDB->getCol($sSQL, 0));
1570 // Fallback to the road (if no housenumber was found)
1571 if (!sizeof($aPlaceIDs) && preg_match('/[0-9]+/', $aSearch['sHouseNumber'])) {
1572 $aPlaceIDs = $aRoadPlaceIDs;
1573 //set to -1, if no housenumbers were found
1574 $searchedHousenumber = -1;
1576 //else: housenumber was found, remains saved in searchedHousenumber
1580 if ($aSearch['sClass'] && sizeof($aPlaceIDs)) {
1581 $sPlaceIDs = join(',', $aPlaceIDs);
1582 $aClassPlaceIDs = array();
1584 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'name') {
1585 // If they were searching for a named class (i.e. 'Kings Head pub') then we might have an extra match
1586 $sSQL = "SELECT place_id ";
1587 $sSQL .= " FROM placex ";
1588 $sSQL .= " WHERE place_id in ($sPlaceIDs) ";
1589 $sSQL .= " AND class='".$aSearch['sClass']."' ";
1590 $sSQL .= " AND type='".$aSearch['sType']."'";
1591 $sSQL .= " AND linked_place_id is null";
1592 if ($sCountryCodesSQL) $sSQL .= " AND country_code in ($sCountryCodesSQL)";
1593 $sSQL .= " ORDER BY rank_search ASC ";
1594 $sSQL .= " LIMIT $this->iLimit";
1595 if (CONST_Debug) var_dump($sSQL);
1596 $aClassPlaceIDs = chksql($this->oDB->getCol($sSQL));
1599 if (!$aSearch['sOperator'] || $aSearch['sOperator'] == 'near') { // & in
1600 $sClassTable = 'place_classtype_'.$aSearch['sClass'].'_'.$aSearch['sType'];
1601 $sSQL = "SELECT count(*) FROM pg_tables ";
1602 $sSQL .= "WHERE tablename = '$sClassTable'";
1603 $bCacheTable = chksql($this->oDB->getOne($sSQL));
1605 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
1607 if (CONST_Debug) var_dump($sSQL);
1608 $this->iMaxRank = ((int)chksql($this->oDB->getOne($sSQL)));
1610 // For state / country level searches the normal radius search doesn't work very well
1611 $sPlaceGeom = false;
1612 if ($this->iMaxRank < 9 && $bCacheTable) {
1613 // Try and get a polygon to search in instead
1614 $sSQL = "SELECT geometry ";
1615 $sSQL .= " FROM placex";
1616 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
1617 $sSQL .= " AND rank_search < $this->iMaxRank + 5";
1618 $sSQL .= " AND ST_Geometrytype(geometry) in ('ST_Polygon','ST_MultiPolygon')";
1619 $sSQL .= " ORDER BY rank_search ASC ";
1620 $sSQL .= " LIMIT 1";
1621 if (CONST_Debug) var_dump($sSQL);
1622 $sPlaceGeom = chksql($this->oDB->getOne($sSQL));
1628 $this->iMaxRank += 5;
1629 $sSQL = "SELECT place_id FROM placex WHERE place_id in ($sPlaceIDs) and rank_search < $this->iMaxRank";
1630 if (CONST_Debug) var_dump($sSQL);
1631 $aPlaceIDs = chksql($this->oDB->getCol($sSQL));
1632 $sPlaceIDs = join(',', $aPlaceIDs);
1635 if ($sPlaceIDs || $sPlaceGeom) {
1638 // More efficient - can make the range bigger
1643 $sOrderBySQL = $oNearPoint->distanceSQL('l.centroid');
1644 } elseif ($sPlaceIDs) {
1645 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
1646 } elseif ($sPlaceGeom) {
1647 $sOrderBysSQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
1650 $sSQL = "select distinct i.place_id".($sOrderBySQL?', i.order_term':'')." from (";
1651 $sSQL .= "select l.place_id".($sOrderBySQL?','.$sOrderBySQL.' as order_term':'')." from ".$sClassTable." as l";
1652 if ($sCountryCodesSQL) $sSQL .= " join placex as lp using (place_id)";
1654 $sSQL .= ",placex as f where ";
1655 $sSQL .= "f.place_id in ($sPlaceIDs) and ST_DWithin(l.centroid, f.centroid, $fRange) ";
1659 $sSQL .= "ST_Contains('".$sPlaceGeom."', l.centroid) ";
1661 if (sizeof($this->aExcludePlaceIDs)) {
1662 $sSQL .= " and l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1664 if ($sCountryCodesSQL) $sSQL .= " and lp.country_code in ($sCountryCodesSQL)";
1665 $sSQL .= 'limit 300) i ';
1666 if ($sOrderBySQL) $sSQL .= "order by order_term asc";
1667 if ($this->iOffset) $sSQL .= " offset $this->iOffset";
1668 $sSQL .= " limit $this->iLimit";
1669 if (CONST_Debug) var_dump($sSQL);
1670 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1672 if ($aSearch['oNear']) {
1673 $fRange = $aSearch['oNear']->radius();
1678 $sOrderBySQL = $oNearPoint->distanceSQL('l.geometry');
1680 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
1683 $sSQL = "SELECT distinct l.place_id".($sOrderBysSQL?','.$sOrderBysSQL:'');
1684 $sSQL .= " FROM placex as l, placex as f ";
1685 $sSQL .= " WHERE f.place_id in ($sPlaceIDs) ";
1686 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange) ";
1687 $sSQL .= " AND l.class='".$aSearch['sClass']."' ";
1688 $sSQL .= " AND l.type='".$aSearch['sType']."' ";
1689 if (sizeof($this->aExcludePlaceIDs)) {
1690 $sSQL .= " AND l.place_id not in (".join(',', $this->aExcludePlaceIDs).")";
1692 if ($sCountryCodesSQL) $sSQL .= " AND l.country_code in ($sCountryCodesSQL)";
1693 if ($sOrderBy) $sSQL .= "ORDER BY ".$OrderBysSQL." ASC";
1694 if ($this->iOffset) $sSQL .= " OFFSET $this->iOffset";
1695 $sSQL .= " limit $this->iLimit";
1696 if (CONST_Debug) var_dump($sSQL);
1697 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($this->oDB->getCol($sSQL)));
1701 $aPlaceIDs = $aClassPlaceIDs;
1706 echo "<br><b>Place IDs:</b> ";
1707 var_Dump($aPlaceIDs);
1710 if ($aSearch['sPostcode']) {
1711 $sSQL = 'SELECT place_id FROM placex';
1712 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
1713 $sSQL .= " AND postcode = '".pg_escape_string($aSearch['sPostcode'])."'";
1714 if (CONST_Debug) var_dump($sSQL);
1715 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1716 if ($aFilteredPlaceIDs) {
1717 $aPlaceIDs = $aFilteredPlaceIDs;
1719 echo "<br><b>Place IDs after postcode filtering:</b> ";
1720 var_Dump($aPlaceIDs);
1725 foreach ($aPlaceIDs as $iPlaceID) {
1726 // array for placeID => -1 | Tiger housenumber
1727 $aResultPlaceIDs[$iPlaceID] = $searchedHousenumber;
1729 if ($iQueryLoop > 20) break;
1732 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs) && ($this->iMinAddressRank != 0 || $this->iMaxAddressRank != 30)) {
1733 // Need to verify passes rank limits before dropping out of the loop (yuk!)
1734 // reduces the number of place ids, like a filter
1735 // rank_address is 30 for interpolated housenumbers
1736 $sSQL = "SELECT place_id ";
1737 $sSQL .= "FROM placex ";
1738 $sSQL .= "WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1740 $sSQL .= " placex.rank_address between $this->iMinAddressRank and $this->iMaxAddressRank ";
1741 if (14 >= $this->iMinAddressRank && 14 <= $this->iMaxAddressRank) {
1742 $sSQL .= " OR (extratags->'place') = 'city'";
1744 if ($this->aAddressRankList) {
1745 $sSQL .= " OR placex.rank_address in (".join(',', $this->aAddressRankList).")";
1747 if (CONST_Use_US_Tiger_Data) {
1750 $sSQL .= " SELECT place_id ";
1751 $sSQL .= " FROM location_property_tiger ";
1752 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).") ";
1753 $sSQL .= " AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank ";
1754 if ($this->aAddressRankList) $sSQL .= " OR 30 in (".join(',', $this->aAddressRankList).")";
1756 $sSQL .= ") UNION ";
1757 $sSQL .= " SELECT place_id ";
1758 $sSQL .= " FROM location_property_osmline ";
1759 $sSQL .= " WHERE place_id in (".join(',', array_keys($aResultPlaceIDs)).")";
1760 $sSQL .= " AND startnumber is not NULL AND (30 between $this->iMinAddressRank and $this->iMaxAddressRank)";
1761 if (CONST_Debug) var_dump($sSQL);
1762 $aFilteredPlaceIDs = chksql($this->oDB->getCol($sSQL));
1764 foreach ($aFilteredPlaceIDs as $placeID) {
1765 $tempIDs[$placeID] = $aResultPlaceIDs[$placeID]; //assign housenumber to placeID
1767 $aResultPlaceIDs = $tempIDs;
1771 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) break;
1772 if ($iGroupLoop > 4) break;
1773 if ($iQueryLoop > 30) break;
1776 // Did we find anything?
1777 if (isset($aResultPlaceIDs) && sizeof($aResultPlaceIDs)) {
1778 $aSearchResults = $this->getDetails($aResultPlaceIDs);
1781 // Just interpret as a reverse geocode
1782 $oReverse = new ReverseGeocode($this->oDB);
1783 $oReverse->setZoom(18);
1785 $aLookup = $oReverse->lookup(
1791 if (CONST_Debug) var_dump("Reverse search", $aLookup);
1793 if ($aLookup['place_id']) {
1794 $aSearchResults = $this->getDetails(array($aLookup['place_id'] => -1));
1795 $aResultPlaceIDs[$aLookup['place_id']] = -1;
1797 $aSearchResults = array();
1802 if (!sizeof($aSearchResults)) {
1803 if ($this->bFallback) {
1804 if ($this->fallbackStructuredQuery()) {
1805 return $this->lookup();
1812 $aClassType = getClassTypesWithImportance();
1813 $aRecheckWords = preg_split('/\b[\s,\\-]*/u', $sQuery);
1814 foreach ($aRecheckWords as $i => $sWord) {
1815 if (!preg_match('/[\pL\pN]/', $sWord)) unset($aRecheckWords[$i]);
1819 echo '<i>Recheck words:<\i>';
1820 var_dump($aRecheckWords);
1823 $oPlaceLookup = new PlaceLookup($this->oDB);
1824 $oPlaceLookup->setIncludePolygonAsPoints($this->bIncludePolygonAsPoints);
1825 $oPlaceLookup->setIncludePolygonAsText($this->bIncludePolygonAsText);
1826 $oPlaceLookup->setIncludePolygonAsGeoJSON($this->bIncludePolygonAsGeoJSON);
1827 $oPlaceLookup->setIncludePolygonAsKML($this->bIncludePolygonAsKML);
1828 $oPlaceLookup->setIncludePolygonAsSVG($this->bIncludePolygonAsSVG);
1829 $oPlaceLookup->setPolygonSimplificationThreshold($this->fPolygonSimplificationThreshold);
1831 foreach ($aSearchResults as $iResNum => $aResult) {
1833 $fDiameter = getResultDiameter($aResult);
1835 $aOutlineResult = $oPlaceLookup->getOutlines($aResult['place_id'], $aResult['lon'], $aResult['lat'], $fDiameter/2);
1836 if ($aOutlineResult) {
1837 $aResult = array_merge($aResult, $aOutlineResult);
1840 if ($aResult['extra_place'] == 'city') {
1841 $aResult['class'] = 'place';
1842 $aResult['type'] = 'city';
1843 $aResult['rank_search'] = 16;
1846 // Is there an icon set for this type of result?
1847 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['icon'])
1848 && $aClassType[$aResult['class'].':'.$aResult['type']]['icon']
1850 $aResult['icon'] = CONST_Website_BaseURL.'images/mapicons/'.$aClassType[$aResult['class'].':'.$aResult['type']]['icon'].'.p.20.png';
1853 if (isset($aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'])
1854 && $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label']
1856 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type'].':'.$aResult['admin_level']]['label'];
1857 } elseif (isset($aClassType[$aResult['class'].':'.$aResult['type']]['label'])
1858 && $aClassType[$aResult['class'].':'.$aResult['type']]['label']
1860 $aResult['label'] = $aClassType[$aResult['class'].':'.$aResult['type']]['label'];
1862 // if tag '&addressdetails=1' is set in query
1863 if ($this->bIncludeAddressDetails) {
1864 // getAddressDetails() is defined in lib.php and uses the SQL function get_addressdata in functions.sql
1865 $aResult['address'] = getAddressDetails($this->oDB, $sLanguagePrefArraySQL, $aResult['place_id'], $aResult['country_code'], $aResultPlaceIDs[$aResult['place_id']]);
1866 if ($aResult['extra_place'] == 'city' && !isset($aResult['address']['city'])) {
1867 $aResult['address'] = array_merge(array('city' => array_values($aResult['address'])[0]), $aResult['address']);
1871 if ($this->bIncludeExtraTags) {
1872 if ($aResult['extra']) {
1873 $aResult['sExtraTags'] = json_decode($aResult['extra']);
1875 $aResult['sExtraTags'] = (object) array();
1879 if ($this->bIncludeNameDetails) {
1880 if ($aResult['names']) {
1881 $aResult['sNameDetails'] = json_decode($aResult['names']);
1883 $aResult['sNameDetails'] = (object) array();
1887 // Adjust importance for the number of exact string matches in the result
1888 $aResult['importance'] = max(0.001, $aResult['importance']);
1890 $sAddress = $aResult['langaddress'];
1891 foreach ($aRecheckWords as $i => $sWord) {
1892 if (stripos($sAddress, $sWord)!==false) {
1894 if (preg_match("/(^|,)\s*".preg_quote($sWord, '/')."\s*(,|$)/", $sAddress)) $iCountWords += 0.1;
1898 $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
1900 $aResult['name'] = $aResult['langaddress'];
1901 // secondary ordering (for results with same importance (the smaller the better):
1902 // - approximate importance of address parts
1903 $aResult['foundorder'] = -$aResult['addressimportance']/10;
1904 // - number of exact matches from the query
1905 if (isset($this->exactMatchCache[$aResult['place_id']])) {
1906 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['place_id']];
1907 } elseif (isset($this->exactMatchCache[$aResult['parent_place_id']])) {
1908 $aResult['foundorder'] -= $this->exactMatchCache[$aResult['parent_place_id']];
1910 // - importance of the class/type
1911 if (isset($aClassType[$aResult['class'].':'.$aResult['type']]['importance'])
1912 && $aClassType[$aResult['class'].':'.$aResult['type']]['importance']
1914 $aResult['foundorder'] += 0.0001 * $aClassType[$aResult['class'].':'.$aResult['type']]['importance'];
1916 $aResult['foundorder'] += 0.01;
1918 if (CONST_Debug) var_dump($aResult);
1919 $aSearchResults[$iResNum] = $aResult;
1921 uasort($aSearchResults, 'byImportance');
1923 $aOSMIDDone = array();
1924 $aClassTypeNameDone = array();
1925 $aToFilter = $aSearchResults;
1926 $aSearchResults = array();
1929 foreach ($aToFilter as $iResNum => $aResult) {
1930 $this->aExcludePlaceIDs[$aResult['place_id']] = $aResult['place_id'];
1932 $fLat = $aResult['lat'];
1933 $fLon = $aResult['lon'];
1934 if (isset($aResult['zoom'])) $iZoom = $aResult['zoom'];
1937 if (!$this->bDeDupe || (!isset($aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']])
1938 && !isset($aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']]))
1940 $aOSMIDDone[$aResult['osm_type'].$aResult['osm_id']] = true;
1941 $aClassTypeNameDone[$aResult['osm_type'].$aResult['class'].$aResult['type'].$aResult['name'].$aResult['admin_level']] = true;
1942 $aSearchResults[] = $aResult;
1945 // Absolute limit on number of results
1946 if (sizeof($aSearchResults) >= $this->iFinalLimit) break;
1949 return $aSearchResults;