5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
6 require_once(CONST_BasePath.'/lib/SearchContext.php');
7 require_once(CONST_BasePath.'/lib/Result.php');
10 * Description of a single interpretation of a search query.
12 class SearchDescription
14 /// Ranking how well the description fits the query.
15 private $iSearchRank = 0;
16 /// Country code of country the result must belong to.
17 private $sCountryCode = '';
18 /// List of word ids making up the name of the object.
19 private $aName = array();
20 /// True if the name is rare enough to force index use on name.
21 private $bRareName = false;
22 /// List of word ids making up the address of the object.
23 private $aAddress = array();
24 /// Subset of word ids of full words making up the address.
25 private $aFullNameAddress = array();
26 /// List of word ids that appear in the name but should be ignored.
27 private $aNameNonSearch = array();
28 /// List of word ids that appear in the address but should be ignored.
29 private $aAddressNonSearch = array();
30 /// Kind of search for special searches, see Nominatim::Operator.
31 private $iOperator = Operator::NONE;
32 /// Class of special feature to search for.
34 /// Type of special feature to search for.
36 /// Housenumber of the object.
37 private $sHouseNumber = '';
38 /// Postcode for the object.
39 private $sPostcode = '';
40 /// Global search constraints.
43 // Temporary values used while creating the search description.
45 /// Index of phrase currently processed.
46 private $iNamePhrase = -1;
49 * Create an empty search description.
51 * @param object $oContext Global context to use. Will be inherited by
52 * all derived search objects.
54 public function __construct($oContext)
56 $this->oContext = $oContext;
60 * Get current search rank.
62 * The higher the search rank the lower the likelihood that the
63 * search is a correct interpretation of the search query.
65 * @return integer Search rank.
67 public function getRank()
69 return $this->iSearchRank;
73 * Make this search a POI search.
75 * In a POI search, objects are not (only) searched by their name
76 * but also by the primary OSM key/value pair (class and type in Nominatim).
78 * @param integer $iOperator Type of POI search
79 * @param string $sClass Class (or OSM tag key) of POI.
80 * @param string $sType Type (or OSM tag value) of POI.
84 public function setPoiSearch($iOperator, $sClass, $sType)
86 $this->iOperator = $iOperator;
87 $this->sClass = $sClass;
88 $this->sType = $sType;
92 * Check if this might be a full address search.
94 * @return bool True if the search contains name, address and housenumber.
96 public function looksLikeFullAddress()
98 return (!empty($this->aName))
99 && (!empty($this->aAddress) || $this->sCountryCode)
100 && preg_match('/[0-9]+/', $this->sHouseNumber);
104 * Check if any operator is set.
106 * @return bool True, if this is a special search operation.
108 public function hasOperator()
110 return $this->iOperator != Operator::NONE;
114 * Extract key/value pairs from a query.
116 * Key/value pairs are recognised if they are of the form [<key>=<value>].
117 * If multiple terms of this kind are found then all terms are removed
118 * but only the first is used for search.
120 * @param string $sQuery Original query string.
122 * @return string The query string with the special search patterns removed.
124 public function extractKeyValuePairs($sQuery)
126 // Search for terms of kind [<key>=<value>].
128 '/\\[([\\w_]*)=([\\w_]*)\\]/',
134 foreach ($aSpecialTermsRaw as $aTerm) {
135 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
136 if (!$this->hasOperator()) {
137 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
145 * Check if the combination of parameters is sensible.
147 * @return bool True, if the search looks valid.
149 public function isValidSearch()
151 if (empty($this->aName)) {
152 if ($this->sHouseNumber) {
155 if (!$this->sClass && !$this->sCountryCode) {
163 /////////// Search building functions
167 * Derive new searches by adding a full term to the existing search.
169 * @param object $oSearchTerm Description of the token.
170 * @param bool $bHasPartial True if there are also tokens of partial terms
171 * with the same name.
172 * @param string $sPhraseType Type of phrase the token is contained in.
173 * @param bool $bFirstToken True if the token is at the beginning of the
175 * @param bool $bFirstPhrase True if the token is in the first phrase of
177 * @param bool $bLastToken True if the token is at the end of the query.
179 * @return SearchDescription[] List of derived search descriptions.
181 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
183 $aNewSearches = array();
185 if (($sPhraseType == '' || $sPhraseType == 'country')
186 && is_a($oSearchTerm, '\Nominatim\Token\Country')
188 if (!$this->sCountryCode) {
189 $oSearch = clone $this;
190 $oSearch->iSearchRank++;
191 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
192 // Country is almost always at the end of the string
193 // - increase score for finding it anywhere else (optimisation)
195 $oSearch->iSearchRank += 5;
197 $aNewSearches[] = $oSearch;
199 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
200 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
202 // We need to try the case where the postal code is the primary element
203 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
205 if (!$this->sPostcode) {
206 // If we have structured search or this is the first term,
207 // make the postcode the primary search element.
208 if ($this->iOperator == Operator::NONE
209 && ($sPhraseType == 'postalcode' || $bFirstToken)
211 $oSearch = clone $this;
212 $oSearch->iSearchRank++;
213 $oSearch->iOperator = Operator::POSTCODE;
214 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
216 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
217 $aNewSearches[] = $oSearch;
220 // If we have a structured search or this is not the first term,
221 // add the postcode as an addendum.
222 if ($this->iOperator != Operator::POSTCODE
223 && ($sPhraseType == 'postalcode' || !empty($this->aName))
225 $oSearch = clone $this;
226 $oSearch->iSearchRank++;
227 $oSearch->sPostcode = $oSearchTerm->sPostcode;
228 $aNewSearches[] = $oSearch;
231 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
232 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
234 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
235 $oSearch = clone $this;
236 $oSearch->iSearchRank++;
237 $oSearch->sHouseNumber = $oSearchTerm->sToken;
238 // sanity check: if the housenumber is not mainly made
239 // up of numbers, add a penalty
240 if (preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
241 $oSearch->iSearchRank++;
243 if (empty($oSearchTerm->iId)) {
244 $oSearch->iSearchRank++;
246 // also must not appear in the middle of the address
247 if (!empty($this->aAddress)
248 || (!empty($this->aAddressNonSearch))
251 $oSearch->iSearchRank++;
253 $aNewSearches[] = $oSearch;
255 } elseif ($sPhraseType == ''
256 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
258 if ($this->iOperator == Operator::NONE) {
259 $oSearch = clone $this;
260 $oSearch->iSearchRank++;
262 $iOp = $oSearchTerm->iOperator;
263 if ($iOp == Operator::NONE) {
264 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
265 $iOp = Operator::NAME;
267 $iOp = Operator::NEAR;
269 $oSearch->iSearchRank += 2;
272 $oSearch->setPoiSearch(
274 $oSearchTerm->sClass,
277 $aNewSearches[] = $oSearch;
279 } elseif ($sPhraseType != 'country'
280 && is_a($oSearchTerm, '\Nominatim\Token\Word')
282 $iWordID = $oSearchTerm->iId;
283 // Full words can only be a name if they appear at the beginning
284 // of the phrase. In structured search the name must forcably in
285 // the first phrase. In unstructured search it may be in a later
286 // phrase when the first phrase is a house number.
287 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
288 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
289 $oSearch = clone $this;
290 $oSearch->iSearchRank += 2;
291 $oSearch->aAddress[$iWordID] = $iWordID;
292 $aNewSearches[] = $oSearch;
294 $this->aFullNameAddress[$iWordID] = $iWordID;
297 $oSearch = clone $this;
298 $oSearch->iSearchRank++;
299 $oSearch->aName = array($iWordID => $iWordID);
300 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
301 $oSearch->bRareName =
302 $oSearchTerm->iSearchNameCount
303 < CONST_Search_NameOnlySearchFrequencyThreshold;
305 $aNewSearches[] = $oSearch;
309 return $aNewSearches;
313 * Derive new searches by adding a partial term to the existing search.
315 * @param string $sToken Term for the token.
316 * @param object $oSearchTerm Description of the token.
317 * @param bool $bStructuredPhrases True if the search is structured.
318 * @param integer $iPhrase Number of the phrase the token is in.
319 * @param array[] $aFullTokens List of full term tokens with the
322 * @return SearchDescription[] List of derived search descriptions.
324 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
326 // Only allow name terms.
327 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
331 $aNewSearches = array();
332 $iWordID = $oSearchTerm->iId;
334 if ((!$bStructuredPhrases || $iPhrase > 0)
335 && (!empty($this->aName))
336 && strpos($sToken, ' ') === false
338 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
339 $oSearch = clone $this;
340 $oSearch->iSearchRank += 2;
341 $oSearch->aAddress[$iWordID] = $iWordID;
342 $aNewSearches[] = $oSearch;
344 $oSearch = clone $this;
345 $oSearch->iSearchRank++;
346 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
347 if (preg_match('#^[0-9]+$#', $sToken)) {
348 $oSearch->iSearchRank += 2;
350 if (!empty($aFullTokens)) {
351 $oSearch->iSearchRank++;
353 $aNewSearches[] = $oSearch;
355 // revert to the token version?
356 foreach ($aFullTokens as $oSearchTermToken) {
357 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
358 $oSearch = clone $this;
359 $oSearch->iSearchRank++;
360 $oSearch->aAddress[$oSearchTermToken->iId]
361 = $oSearchTermToken->iId;
362 $aNewSearches[] = $oSearch;
368 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
369 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
371 $oSearch = clone $this;
372 $oSearch->iSearchRank += 2;
373 if (empty($this->aName)) {
374 $oSearch->iSearchRank += 1;
376 if (preg_match('#^[0-9]+$#', $sToken)) {
377 $oSearch->iSearchRank += 2;
379 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
380 if (empty($this->aName)
381 && CONST_Search_NameOnlySearchFrequencyThreshold
383 $oSearch->bRareName =
384 $oSearchTerm->iSearchNameCount
385 < CONST_Search_NameOnlySearchFrequencyThreshold;
387 $oSearch->bRareName = false;
389 $oSearch->aName[$iWordID] = $iWordID;
391 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
393 $oSearch->iNamePhrase = $iPhrase;
394 $aNewSearches[] = $oSearch;
397 return $aNewSearches;
400 /////////// Query functions
404 * Query database for places that match this search.
406 * @param object $oDB Database connection to use.
407 * @param integer $iMinRank Minimum address rank to restrict search to.
408 * @param integer $iMaxRank Maximum address rank to restrict search to.
409 * @param integer $iLimit Maximum number of results.
411 * @return mixed[] An array with two fields: IDs contains the list of
412 * matching place IDs and houseNumber the houseNumber
413 * if appicable or -1 if not.
415 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
420 if ($this->sCountryCode
421 && empty($this->aName)
424 && !$this->oContext->hasNearPoint()
426 // Just looking for a country - look it up
427 if (4 >= $iMinRank && 4 <= $iMaxRank) {
428 $aResults = $this->queryCountry($oDB);
430 } elseif (empty($this->aName) && empty($this->aAddress)) {
431 // Neither name nor address? Then we must be
432 // looking for a POI in a geographic area.
433 if ($this->oContext->isBoundedSearch()) {
434 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
436 } elseif ($this->iOperator == Operator::POSTCODE) {
437 // looking for postcode
438 $aResults = $this->queryPostcode($oDB, $iLimit);
441 // First search for places according to name and address.
442 $aResults = $this->queryNamedPlace(
449 //now search for housenumber, if housenumber provided
450 if ($this->sHouseNumber && !empty($aResults)) {
451 $aNamedPlaceIDs = $aResults;
452 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs);
454 if (empty($aResults) && $this->looksLikeFullAddress()) {
455 $aResults = $aNamedPlaceIDs;
459 // finally get POIs if requested
460 if ($this->sClass && !empty($aResults)) {
461 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
465 Debug::printDebugTable('Place IDs', $aResults);
467 if (!empty($aResults) && $this->sPostcode) {
468 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
470 $sSQL = 'SELECT place_id FROM placex';
471 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
472 $sSQL .= " AND postcode = '".$this->sPostcode."'";
473 Debug::printSQL($sSQL);
474 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
475 if ($aFilteredPlaceIDs) {
476 $aNewResults = array();
477 foreach ($aFilteredPlaceIDs as $iPlaceId) {
478 $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
480 $aResults = $aNewResults;
481 Debug::printVar('Place IDs after postcode filtering', $aResults);
490 private function queryCountry(&$oDB)
492 $sSQL = 'SELECT place_id FROM placex ';
493 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
494 $sSQL .= ' AND rank_search = 4';
495 if ($this->oContext->bViewboxBounded) {
496 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
498 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
500 Debug::printSQL($sSQL);
503 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
504 $aResults[$iPlaceId] = new Result($iPlaceId);
510 private function queryNearbyPoi(&$oDB, $iLimit)
512 if (!$this->sClass) {
516 $aDBResults = array();
517 $sPoiTable = $this->poiTable();
519 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
520 if (chksql($oDB->getOne($sSQL))) {
521 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
522 if ($this->oContext->sqlCountryList) {
523 $sSQL .= ' JOIN placex USING (place_id)';
525 if ($this->oContext->hasNearPoint()) {
526 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
527 } elseif ($this->oContext->bViewboxBounded) {
528 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
530 if ($this->oContext->sqlCountryList) {
531 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
533 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
534 if ($this->oContext->sqlViewboxCentre) {
535 $sSQL .= ' ORDER BY ST_Distance(';
536 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
537 } elseif ($this->oContext->hasNearPoint()) {
538 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
540 $sSQL .= " limit $iLimit";
541 Debug::printSQL($sSQL);
542 $aDBResults = chksql($oDB->getCol($sSQL));
545 if ($this->oContext->hasNearPoint()) {
546 $sSQL = 'SELECT place_id FROM placex WHERE ';
547 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
548 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
549 $sSQL .= ' AND linked_place_id is null';
550 if ($this->oContext->sqlCountryList) {
551 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
553 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
554 $sSQL .= " LIMIT $iLimit";
555 Debug::printSQL($sSQL);
556 $aDBResults = chksql($oDB->getCol($sSQL));
560 foreach ($aDBResults as $iPlaceId) {
561 $aResults[$iPlaceId] = new Result($iPlaceId);
567 private function queryPostcode(&$oDB, $iLimit)
569 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
571 if (!empty($this->aAddress)) {
572 $sSQL .= ', search_name s ';
573 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
574 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
575 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
580 $sSQL .= "p.postcode = '".reset($this->aName)."'";
581 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
582 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
583 $sSQL .= " LIMIT $iLimit";
585 Debug::printSQL($sSQL);
588 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
589 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
595 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
600 // Sort by existence of the requested house number but only if not
601 // too many results are expected for the street, i.e. if the result
602 // will be narrowed down by an address. Remeber that with ordering
603 // every single result has to be checked.
604 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
605 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
607 $aOrder[0] .= 'EXISTS(';
608 $aOrder[0] .= ' SELECT place_id';
609 $aOrder[0] .= ' FROM placex';
610 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
611 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
612 $aOrder[0] .= ' LIMIT 1';
614 // also housenumbers from interpolation lines table are needed
615 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
616 $iHouseNumber = intval($this->sHouseNumber);
617 $aOrder[0] .= 'OR EXISTS(';
618 $aOrder[0] .= ' SELECT place_id ';
619 $aOrder[0] .= ' FROM location_property_osmline ';
620 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
621 $aOrder[0] .= ' AND startnumber is not NULL';
622 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
623 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
624 $aOrder[0] .= ' LIMIT 1';
627 $aOrder[0] .= ') DESC';
630 if (!empty($this->aName)) {
631 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
633 if (!empty($this->aAddress)) {
634 // For infrequent name terms disable index usage for address
635 if ($this->bRareName) {
636 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
638 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
642 $sCountryTerm = $this->countryCodeSQL('country_code');
644 $aTerms[] = $sCountryTerm;
647 if ($this->sHouseNumber) {
648 $aTerms[] = 'address_rank between 16 and 27';
649 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
650 if ($iMinAddressRank > 0) {
651 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
653 if ($iMaxAddressRank < 30) {
654 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
658 if ($this->oContext->hasNearPoint()) {
659 $aTerms[] = $this->oContext->withinSQL('centroid');
660 $aOrder[] = $this->oContext->distanceSQL('centroid');
661 } elseif ($this->sPostcode) {
662 if (empty($this->aAddress)) {
663 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
665 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
669 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
671 $aTerms[] = $sExcludeSQL;
674 if ($this->oContext->bViewboxBounded) {
675 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
678 if ($this->oContext->hasNearPoint()) {
679 $aOrder[] = $this->oContext->distanceSQL('centroid');
682 if ($this->sHouseNumber) {
683 $sImportanceSQL = '- abs(26 - address_rank) + 3';
685 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
687 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
688 $aOrder[] = "$sImportanceSQL DESC";
690 if (!empty($this->aFullNameAddress)) {
691 $sExactMatchSQL = ' ( ';
692 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
693 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
694 $sExactMatchSQL .= ' INTERSECT ';
695 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
696 $sExactMatchSQL .= ' ) s';
697 $sExactMatchSQL .= ') as exactmatch';
698 $aOrder[] = 'exactmatch DESC';
700 $sExactMatchSQL = '0::int as exactmatch';
703 if ($this->sHouseNumber || $this->sClass) {
709 if (!empty($aTerms)) {
710 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
711 $sSQL .= ' FROM search_name';
712 $sSQL .= ' WHERE '.join(' and ', $aTerms);
713 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
714 $sSQL .= ' LIMIT '.$iLimit;
716 Debug::printSQL($sSQL);
718 $aDBResults = chksql(
720 'Could not get places for search terms.'
723 foreach ($aDBResults as $aResult) {
724 $oResult = new Result($aResult['place_id']);
725 $oResult->iExactMatches = $aResult['exactmatch'];
726 $aResults[$aResult['place_id']] = $oResult;
733 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
736 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
742 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
743 $sSQL = 'SELECT place_id FROM placex ';
744 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
745 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
746 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
748 Debug::printSQL($sSQL);
750 // XXX should inherit the exactMatches from its parent
751 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
752 $aResults[$iPlaceId] = new Result($iPlaceId);
755 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
756 $iHousenumber = intval($this->sHouseNumber);
757 if ($bIsIntHouseNumber && empty($aResults)) {
758 // if nothing found, search in the interpolation line table
759 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
760 $sSQL .= ' WHERE startnumber is not NULL';
761 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
762 if ($iHousenumber % 2 == 0) {
763 // If housenumber is even, look for housenumber in streets
764 // with interpolationtype even or all.
765 $sSQL .= "interpolationtype='even'";
767 // Else look for housenumber with interpolationtype odd or all.
768 $sSQL .= "interpolationtype='odd'";
770 $sSQL .= " or interpolationtype='all') and ";
771 $sSQL .= $iHousenumber.'>=startnumber and ';
772 $sSQL .= $iHousenumber.'<=endnumber';
773 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
775 Debug::printSQL($sSQL);
777 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
778 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
779 $oResult->iHouseNumber = $iHousenumber;
780 $aResults[$iPlaceId] = $oResult;
784 // If nothing found try the aux fallback table
785 if (CONST_Use_Aux_Location_data && empty($aResults)) {
786 $sSQL = 'SELECT place_id FROM location_property_aux';
787 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
788 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
789 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
791 Debug::printSQL($sSQL);
793 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
794 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
798 // If nothing found then search in Tiger data (location_property_tiger)
799 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
800 $sSQL = 'SELECT place_id FROM location_property_tiger';
801 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
802 if ($iHousenumber % 2 == 0) {
803 $sSQL .= "interpolationtype='even'";
805 $sSQL .= "interpolationtype='odd'";
807 $sSQL .= " or interpolationtype='all') and ";
808 $sSQL .= $iHousenumber.'>=startnumber and ';
809 $sSQL .= $iHousenumber.'<=endnumber';
810 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
812 Debug::printSQL($sSQL);
814 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
815 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
816 $oResult->iHouseNumber = $iHousenumber;
817 $aResults[$iPlaceId] = $oResult;
825 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
828 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
834 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
835 // If they were searching for a named class (i.e. 'Kings Head pub')
836 // then we might have an extra match
837 $sSQL = 'SELECT place_id FROM placex ';
838 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
839 $sSQL .= " AND class='".$this->sClass."' ";
840 $sSQL .= " AND type='".$this->sType."'";
841 $sSQL .= ' AND linked_place_id is null';
842 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
843 $sSQL .= ' ORDER BY rank_search ASC ';
844 $sSQL .= " LIMIT $iLimit";
846 Debug::printSQL($sSQL);
848 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
849 $aResults[$iPlaceId] = new Result($iPlaceId);
853 // NEAR and IN are handled the same
854 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
855 $sClassTable = $this->poiTable();
856 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
857 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
859 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
860 Debug::printSQL($sSQL);
861 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
863 // For state / country level searches the normal radius search doesn't work very well
865 if ($iMaxRank < 9 && $bCacheTable) {
866 // Try and get a polygon to search in instead
867 $sSQL = 'SELECT geometry FROM placex';
868 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
869 $sSQL .= " AND rank_search < $iMaxRank + 5";
870 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
871 $sSQL .= ' ORDER BY rank_search ASC ';
873 Debug::printSQL($sSQL);
874 $sPlaceGeom = chksql($oDB->getOne($sSQL));
881 $sSQL = 'SELECT place_id FROM placex';
882 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
883 Debug::printSQL($sSQL);
884 $aPlaceIDs = chksql($oDB->getCol($sSQL));
885 $sPlaceIDs = join(',', $aPlaceIDs);
888 if ($sPlaceIDs || $sPlaceGeom) {
891 // More efficient - can make the range bigger
895 if ($this->oContext->hasNearPoint()) {
896 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
897 } elseif ($sPlaceIDs) {
898 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
899 } elseif ($sPlaceGeom) {
900 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
903 $sSQL = 'SELECT distinct i.place_id';
905 $sSQL .= ', i.order_term';
907 $sSQL .= ' from (SELECT l.place_id';
909 $sSQL .= ','.$sOrderBySQL.' as order_term';
911 $sSQL .= ' from '.$sClassTable.' as l';
914 $sSQL .= ',placex as f WHERE ';
915 $sSQL .= "f.place_id in ($sPlaceIDs) ";
916 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
917 } elseif ($sPlaceGeom) {
918 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
921 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
922 $sSQL .= 'limit 300) i ';
924 $sSQL .= 'order by order_term asc';
926 $sSQL .= " limit $iLimit";
928 Debug::printSQL($sSQL);
930 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
931 $aResults[$iPlaceId] = new Result($iPlaceId);
934 if ($this->oContext->hasNearPoint()) {
935 $fRange = $this->oContext->nearRadius();
939 if ($this->oContext->hasNearPoint()) {
940 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
942 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
945 $sSQL = 'SELECT distinct l.place_id';
947 $sSQL .= ','.$sOrderBySQL.' as orderterm';
949 $sSQL .= ' FROM placex as l, placex as f';
950 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
951 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
952 $sSQL .= " AND l.class='".$this->sClass."'";
953 $sSQL .= " AND l.type='".$this->sType."'";
954 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
956 $sSQL .= 'ORDER BY orderterm ASC';
958 $sSQL .= " limit $iLimit";
960 Debug::printSQL($sSQL);
962 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
963 $aResults[$iPlaceId] = new Result($iPlaceId);
972 private function poiTable()
974 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
977 private function countryCodeSQL($sVar)
979 if ($this->sCountryCode) {
980 return $sVar.' = \''.$this->sCountryCode."'";
982 if ($this->oContext->sqlCountryList) {
983 return $sVar.' in '.$this->oContext->sqlCountryList;
989 /////////// Sort functions
992 public static function bySearchRank($a, $b)
994 if ($a->iSearchRank == $b->iSearchRank) {
995 return $a->iOperator + strlen($a->sHouseNumber)
996 - $b->iOperator - strlen($b->sHouseNumber);
999 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1002 //////////// Debugging functions
1005 public function debugInfo()
1008 'Search rank' => $this->iSearchRank,
1009 'Country code' => $this->sCountryCode,
1010 'Name terms' => $this->aName,
1011 'Name terms (stop words)' => $this->aNameNonSearch,
1012 'Address terms' => $this->aAddress,
1013 'Address terms (stop words)' => $this->aAddressNonSearch,
1014 'Address terms (full words)' => $this->aFullNameAddress,
1015 'Special search' => $this->iOperator,
1016 'Class' => $this->sClass,
1017 'Type' => $this->sType,
1018 'House number' => $this->sHouseNumber,
1019 'Postcode' => $this->sPostcode
1023 public function dumpAsHtmlTableRow(&$aWordIDs)
1025 $kf = function ($k) use (&$aWordIDs) {
1026 return $aWordIDs[$k];
1030 echo "<td>$this->iSearchRank</td>";
1031 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1032 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1033 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1034 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1035 echo '<td>'.$this->sCountryCode.'</td>';
1036 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1037 echo '<td>'.$this->sClass.'</td>';
1038 echo '<td>'.$this->sType.'</td>';
1039 echo '<td>'.$this->sPostcode.'</td>';
1040 echo '<td>'.$this->sHouseNumber.'</td>';