5 require_once(CONST_LibDir.'/SpecialSearchOperator.php');
6 require_once(CONST_LibDir.'/SearchContext.php');
7 require_once(CONST_LibDir.'/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 /// List of word ids that appear in the name but should be ignored.
25 private $aNameNonSearch = array();
26 /// List of word ids that appear in the address but should be ignored.
27 private $aAddressNonSearch = array();
28 /// Kind of search for special searches, see Nominatim::Operator.
29 private $iOperator = Operator::NONE;
30 /// Class of special feature to search for.
32 /// Type of special feature to search for.
34 /// Housenumber of the object.
35 private $sHouseNumber = '';
36 /// Postcode for the object.
37 private $sPostcode = '';
38 /// Global search constraints.
41 // Temporary values used while creating the search description.
43 /// Index of phrase currently processed.
44 private $iNamePhrase = -1;
47 * Create an empty search description.
49 * @param object $oContext Global context to use. Will be inherited by
50 * all derived search objects.
52 public function __construct($oContext)
54 $this->oContext = $oContext;
58 * Get current search rank.
60 * The higher the search rank the lower the likelihood that the
61 * search is a correct interpretation of the search query.
63 * @return integer Search rank.
65 public function getRank()
67 return $this->iSearchRank;
71 * Make this search a POI search.
73 * In a POI search, objects are not (only) searched by their name
74 * but also by the primary OSM key/value pair (class and type in Nominatim).
76 * @param integer $iOperator Type of POI search
77 * @param string $sClass Class (or OSM tag key) of POI.
78 * @param string $sType Type (or OSM tag value) of POI.
82 public function setPoiSearch($iOperator, $sClass, $sType)
84 $this->iOperator = $iOperator;
85 $this->sClass = $sClass;
86 $this->sType = $sType;
90 * Check if any operator is set.
92 * @return bool True, if this is a special search operation.
94 public function hasOperator()
96 return $this->iOperator != Operator::NONE;
100 * Extract key/value pairs from a query.
102 * Key/value pairs are recognised if they are of the form [<key>=<value>].
103 * If multiple terms of this kind are found then all terms are removed
104 * but only the first is used for search.
106 * @param string $sQuery Original query string.
108 * @return string The query string with the special search patterns removed.
110 public function extractKeyValuePairs($sQuery)
112 // Search for terms of kind [<key>=<value>].
114 '/\\[([\\w_]*)=([\\w_]*)\\]/',
120 foreach ($aSpecialTermsRaw as $aTerm) {
121 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
122 if (!$this->hasOperator()) {
123 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
131 * Check if the combination of parameters is sensible.
133 * @return bool True, if the search looks valid.
135 public function isValidSearch()
137 if (empty($this->aName)) {
138 if ($this->sHouseNumber) {
141 if (!$this->sClass && !$this->sCountryCode) {
149 /////////// Search building functions
153 * Derive new searches by adding a full term to the existing search.
155 * @param object $oSearchTerm Description of the token.
156 * @param bool $bHasPartial True if there are also tokens of partial terms
157 * with the same name.
158 * @param string $sPhraseType Type of phrase the token is contained in.
159 * @param bool $bFirstToken True if the token is at the beginning of the
161 * @param bool $bFirstPhrase True if the token is in the first phrase of
163 * @param bool $bLastToken True if the token is at the end of the query.
165 * @return SearchDescription[] List of derived search descriptions.
167 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
169 $aNewSearches = array();
171 if (($sPhraseType == '' || $sPhraseType == 'country')
172 && is_a($oSearchTerm, '\Nominatim\Token\Country')
174 if (!$this->sCountryCode) {
175 $oSearch = clone $this;
176 $oSearch->iSearchRank++;
177 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
178 // Country is almost always at the end of the string
179 // - increase score for finding it anywhere else (optimisation)
181 $oSearch->iSearchRank += 5;
183 $aNewSearches[] = $oSearch;
185 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
186 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
188 if (!$this->sPostcode) {
189 // If we have structured search or this is the first term,
190 // make the postcode the primary search element.
191 if ($this->iOperator == Operator::NONE && $bFirstToken) {
192 $oSearch = clone $this;
193 $oSearch->iSearchRank++;
194 $oSearch->iOperator = Operator::POSTCODE;
195 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
197 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
198 $aNewSearches[] = $oSearch;
201 // If we have a structured search or this is not the first term,
202 // add the postcode as an addendum.
203 if ($this->iOperator != Operator::POSTCODE
204 && ($sPhraseType == 'postalcode' || !empty($this->aName))
206 $oSearch = clone $this;
207 $oSearch->iSearchRank++;
208 if (strlen($oSearchTerm->sPostcode) < 4) {
209 $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
211 $oSearch->sPostcode = $oSearchTerm->sPostcode;
212 $aNewSearches[] = $oSearch;
215 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
216 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
218 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
219 $oSearch = clone $this;
220 $oSearch->iSearchRank++;
221 $oSearch->sHouseNumber = $oSearchTerm->sToken;
222 if ($this->iOperator != Operator::NONE) {
223 $oSearch->iSearchRank++;
225 // sanity check: if the housenumber is not mainly made
226 // up of numbers, add a penalty
227 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
228 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
229 $oSearch->iSearchRank++;
231 if (empty($oSearchTerm->iId)) {
232 $oSearch->iSearchRank++;
234 // also must not appear in the middle of the address
235 if (!empty($this->aAddress)
236 || (!empty($this->aAddressNonSearch))
239 $oSearch->iSearchRank++;
241 $aNewSearches[] = $oSearch;
242 // Housenumbers may appear in the name when the place has its own
244 if ($oSearchTerm->iId !== null
245 && ($this->iNamePhrase >= 0 || empty($this->aName))
246 && empty($this->aAddress)
248 $oSearch = clone $this;
249 $oSearch->iSearchRank++;
250 $oSearch->aAddress = $this->aName;
251 $oSearch->bRareName = false;
252 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
253 $aNewSearches[] = $oSearch;
256 } elseif ($sPhraseType == ''
257 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
259 if ($this->iOperator == Operator::NONE) {
260 $oSearch = clone $this;
261 $oSearch->iSearchRank += 2;
263 $iOp = $oSearchTerm->iOperator;
264 if ($iOp == Operator::NONE) {
265 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
266 $iOp = Operator::NAME;
268 $iOp = Operator::NEAR;
270 $oSearch->iSearchRank += 2;
271 } else if (!$bFirstToken && !$bLastToken) {
272 $oSearch->iSearchRank += 2;
274 if ($this->sHouseNumber) {
275 $oSearch->iSearchRank++;
278 $oSearch->setPoiSearch(
280 $oSearchTerm->sClass,
283 $aNewSearches[] = $oSearch;
285 } elseif ($sPhraseType != 'country'
286 && is_a($oSearchTerm, '\Nominatim\Token\Word')
288 $iWordID = $oSearchTerm->iId;
289 // Full words can only be a name if they appear at the beginning
290 // of the phrase. In structured search the name must forcably in
291 // the first phrase. In unstructured search it may be in a later
292 // phrase when the first phrase is a house number.
293 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
294 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
295 $oSearch = clone $this;
296 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
297 $oSearch->aAddress[$iWordID] = $iWordID;
298 $aNewSearches[] = $oSearch;
300 } else if (empty($this->aNameNonSearch)) {
301 $oSearch = clone $this;
302 $oSearch->iSearchRank++;
303 $oSearch->aName = array($iWordID => $iWordID);
304 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
305 $oSearch->bRareName =
306 $oSearchTerm->iSearchNameCount
307 < CONST_Search_NameOnlySearchFrequencyThreshold;
309 $aNewSearches[] = $oSearch;
313 return $aNewSearches;
317 * Derive new searches by adding a partial term to the existing search.
319 * @param string $sToken Term for the token.
320 * @param object $oSearchTerm Description of the token.
321 * @param bool $bStructuredPhrases True if the search is structured.
322 * @param integer $iPhrase Number of the phrase the token is in.
323 * @param array[] $aFullTokens List of full term tokens with the
326 * @return SearchDescription[] List of derived search descriptions.
328 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
330 // Only allow name terms.
331 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
335 $aNewSearches = array();
336 $iWordID = $oSearchTerm->iId;
338 if ((!$bStructuredPhrases || $iPhrase > 0)
339 && (!empty($this->aName))
341 $oSearch = clone $this;
342 $oSearch->iSearchRank++;
343 if (preg_match('#^[0-9 ]+$#', $sToken)) {
344 $oSearch->iSearchRank++;
346 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
347 $oSearch->aAddress[$iWordID] = $iWordID;
349 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
350 if (!empty($aFullTokens)) {
351 $oSearch->iSearchRank++;
354 $aNewSearches[] = $oSearch;
357 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
358 && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
360 $oSearch = clone $this;
361 $oSearch->iSearchRank++;
362 if (empty($this->aName) && empty($this->aNameNonSearch)) {
363 $oSearch->iSearchRank++;
365 if (preg_match('#^[0-9 ]+$#', $sToken)) {
366 $oSearch->iSearchRank++;
368 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
369 if (empty($this->aName)
370 && CONST_Search_NameOnlySearchFrequencyThreshold
372 $oSearch->bRareName =
373 $oSearchTerm->iSearchNameCount
374 < CONST_Search_NameOnlySearchFrequencyThreshold;
376 $oSearch->bRareName = false;
378 $oSearch->aName[$iWordID] = $iWordID;
380 if (!empty($aFullTokens)) {
381 $oSearch->iSearchRank++;
383 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
385 $oSearch->iNamePhrase = $iPhrase;
386 $aNewSearches[] = $oSearch;
389 return $aNewSearches;
392 /////////// Query functions
396 * Query database for places that match this search.
398 * @param object $oDB Nominatim::DB instance to use.
399 * @param integer $iMinRank Minimum address rank to restrict search to.
400 * @param integer $iMaxRank Maximum address rank to restrict search to.
401 * @param integer $iLimit Maximum number of results.
403 * @return mixed[] An array with two fields: IDs contains the list of
404 * matching place IDs and houseNumber the houseNumber
405 * if appicable or -1 if not.
407 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
412 if ($this->sCountryCode
413 && empty($this->aName)
416 && !$this->oContext->hasNearPoint()
418 // Just looking for a country - look it up
419 if (4 >= $iMinRank && 4 <= $iMaxRank) {
420 $aResults = $this->queryCountry($oDB);
422 } elseif (empty($this->aName) && empty($this->aAddress)) {
423 // Neither name nor address? Then we must be
424 // looking for a POI in a geographic area.
425 if ($this->oContext->isBoundedSearch()) {
426 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
428 } elseif ($this->iOperator == Operator::POSTCODE) {
429 // looking for postcode
430 $aResults = $this->queryPostcode($oDB, $iLimit);
433 // First search for places according to name and address.
434 $aResults = $this->queryNamedPlace(
441 // Now search for housenumber, if housenumber provided. Can be zero.
442 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
443 // Downgrade the rank of the street results, they are missing
445 foreach ($aResults as $oRes) {
446 if ($oRes->iAddressRank >= 26) {
447 $oRes->iResultRank++;
449 $oRes->iResultRank += 2;
453 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
455 if (!empty($aHnResults)) {
456 foreach ($aHnResults as $oRes) {
457 $aResults[$oRes->iId] = $oRes;
462 // finally get POIs if requested
463 if ($this->sClass && !empty($aResults)) {
464 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
468 Debug::printDebugTable('Place IDs', $aResults);
470 if (!empty($aResults) && $this->sPostcode) {
471 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
473 $sSQL = 'SELECT place_id FROM placex';
474 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
475 $sSQL .= " AND postcode != '".$this->sPostcode."'";
476 Debug::printSQL($sSQL);
477 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
478 if ($aFilteredPlaceIDs) {
479 foreach ($aFilteredPlaceIDs as $iPlaceId) {
480 $aResults[$iPlaceId]->iResultRank++;
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);
502 $iPlaceId = $oDB->getOne($sSQL);
506 $aResults[$iPlaceId] = new Result($iPlaceId);
512 private function queryNearbyPoi(&$oDB, $iLimit)
514 if (!$this->sClass) {
518 $aDBResults = array();
519 $sPoiTable = $this->poiTable();
521 if ($oDB->tableExists($sPoiTable)) {
522 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
523 if ($this->oContext->sqlCountryList) {
524 $sSQL .= ' JOIN placex USING (place_id)';
526 if ($this->oContext->hasNearPoint()) {
527 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
528 } elseif ($this->oContext->bViewboxBounded) {
529 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
531 if ($this->oContext->sqlCountryList) {
532 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
534 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
535 if ($this->oContext->sqlViewboxCentre) {
536 $sSQL .= ' ORDER BY ST_Distance(';
537 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
538 } elseif ($this->oContext->hasNearPoint()) {
539 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
541 $sSQL .= " LIMIT $iLimit";
542 Debug::printSQL($sSQL);
543 $aDBResults = $oDB->getCol($sSQL);
546 if ($this->oContext->hasNearPoint()) {
547 $sSQL = 'SELECT place_id FROM placex WHERE ';
548 $sSQL .= 'class = :class and type = :type';
549 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
550 $sSQL .= ' AND linked_place_id is null';
551 if ($this->oContext->sqlCountryList) {
552 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
554 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
555 $sSQL .= " LIMIT $iLimit";
556 Debug::printSQL($sSQL);
557 $aDBResults = $oDB->getCol(
559 array(':class' => $this->sClass, ':type' => $this->sType)
564 foreach ($aDBResults as $iPlaceId) {
565 $aResults[$iPlaceId] = new Result($iPlaceId);
571 private function queryPostcode(&$oDB, $iLimit)
573 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
575 if (!empty($this->aAddress)) {
576 $sSQL .= ', search_name s ';
577 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
578 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
579 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
584 $sSQL .= "p.postcode = '".reset($this->aName)."'";
585 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
586 if ($this->oContext->bViewboxBounded) {
587 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
589 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
590 $sSQL .= " LIMIT $iLimit";
592 Debug::printSQL($sSQL);
595 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
596 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
602 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
607 // Sort by existence of the requested house number but only if not
608 // too many results are expected for the street, i.e. if the result
609 // will be narrowed down by an address. Remeber that with ordering
610 // every single result has to be checked.
611 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
612 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
614 $aOrder[0] .= 'EXISTS(';
615 $aOrder[0] .= ' SELECT place_id';
616 $aOrder[0] .= ' FROM placex';
617 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
618 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
619 $aOrder[0] .= ' LIMIT 1';
621 // also housenumbers from interpolation lines table are needed
622 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
623 $iHouseNumber = intval($this->sHouseNumber);
624 $aOrder[0] .= 'OR EXISTS(';
625 $aOrder[0] .= ' SELECT place_id ';
626 $aOrder[0] .= ' FROM location_property_osmline ';
627 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
628 $aOrder[0] .= ' AND startnumber is not NULL';
629 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
630 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
631 $aOrder[0] .= ' LIMIT 1';
634 $aOrder[0] .= ') DESC';
637 if (!empty($this->aName)) {
638 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
640 if (!empty($this->aAddress)) {
641 // For infrequent name terms disable index usage for address
642 if ($this->bRareName) {
643 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
645 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
649 $sCountryTerm = $this->countryCodeSQL('country_code');
651 $aTerms[] = $sCountryTerm;
654 if ($this->sHouseNumber) {
655 $aTerms[] = 'address_rank between 16 and 30';
656 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
657 if ($iMinAddressRank > 0) {
658 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
662 if ($this->oContext->hasNearPoint()) {
663 $aTerms[] = $this->oContext->withinSQL('centroid');
664 $aOrder[] = $this->oContext->distanceSQL('centroid');
665 } elseif ($this->sPostcode) {
666 if (empty($this->aAddress)) {
667 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
669 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
673 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
675 $aTerms[] = $sExcludeSQL;
678 if ($this->oContext->bViewboxBounded) {
679 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
682 if ($this->oContext->hasNearPoint()) {
683 $aOrder[] = $this->oContext->distanceSQL('centroid');
686 if ($this->sHouseNumber) {
687 $sImportanceSQL = '- abs(26 - address_rank) + 3';
689 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
691 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
692 $aOrder[] = "$sImportanceSQL DESC";
694 $aFullNameAddress = $this->oContext->getFullNameTerms();
695 if (!empty($aFullNameAddress)) {
696 $sExactMatchSQL = ' ( ';
697 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
698 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
699 $sExactMatchSQL .= ' INTERSECT ';
700 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
701 $sExactMatchSQL .= ' ) s';
702 $sExactMatchSQL .= ') as exactmatch';
703 $aOrder[] = 'exactmatch DESC';
705 $sExactMatchSQL = '0::int as exactmatch';
708 if ($this->sHouseNumber || $this->sClass) {
714 if (!empty($aTerms)) {
715 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
716 $sSQL .= ' FROM search_name';
717 $sSQL .= ' WHERE '.join(' and ', $aTerms);
718 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
719 $sSQL .= ' LIMIT '.$iLimit;
721 Debug::printSQL($sSQL);
723 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
725 foreach ($aDBResults as $aResult) {
726 $oResult = new Result($aResult['place_id']);
727 $oResult->iExactMatches = $aResult['exactmatch'];
728 $oResult->iAddressRank = $aResult['address_rank'];
729 $aResults[$aResult['place_id']] = $oResult;
736 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
739 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
745 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
746 $sSQL = 'SELECT place_id FROM placex ';
747 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
748 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
749 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
751 Debug::printSQL($sSQL);
753 // XXX should inherit the exactMatches from its parent
754 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
755 $aResults[$iPlaceId] = new Result($iPlaceId);
758 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
759 $iHousenumber = intval($this->sHouseNumber);
760 if ($bIsIntHouseNumber && empty($aResults)) {
761 // if nothing found, search in the interpolation line table
762 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
763 $sSQL .= ' WHERE startnumber is not NULL';
764 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
765 if ($iHousenumber % 2 == 0) {
766 // If housenumber is even, look for housenumber in streets
767 // with interpolationtype even or all.
768 $sSQL .= "interpolationtype='even'";
770 // Else look for housenumber with interpolationtype odd or all.
771 $sSQL .= "interpolationtype='odd'";
773 $sSQL .= " or interpolationtype='all') and ";
774 $sSQL .= $iHousenumber.'>=startnumber and ';
775 $sSQL .= $iHousenumber.'<=endnumber';
776 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
778 Debug::printSQL($sSQL);
780 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
781 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
782 $oResult->iHouseNumber = $iHousenumber;
783 $aResults[$iPlaceId] = $oResult;
787 // If nothing found try the aux fallback table
788 if (CONST_Use_Aux_Location_data && empty($aResults)) {
789 $sSQL = 'SELECT place_id FROM location_property_aux';
790 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
791 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
792 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
794 Debug::printSQL($sSQL);
796 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
797 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
801 // If nothing found then search in Tiger data (location_property_tiger)
802 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
803 $sSQL = 'SELECT place_id FROM location_property_tiger';
804 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
805 if ($iHousenumber % 2 == 0) {
806 $sSQL .= "interpolationtype='even'";
808 $sSQL .= "interpolationtype='odd'";
810 $sSQL .= " or interpolationtype='all') and ";
811 $sSQL .= $iHousenumber.'>=startnumber and ';
812 $sSQL .= $iHousenumber.'<=endnumber';
813 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
815 Debug::printSQL($sSQL);
817 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
818 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
819 $oResult->iHouseNumber = $iHousenumber;
820 $aResults[$iPlaceId] = $oResult;
828 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
831 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
837 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
838 // If they were searching for a named class (i.e. 'Kings Head pub')
839 // then we might have an extra match
840 $sSQL = 'SELECT place_id FROM placex ';
841 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
842 $sSQL .= " AND class='".$this->sClass."' ";
843 $sSQL .= " AND type='".$this->sType."'";
844 $sSQL .= ' AND linked_place_id is null';
845 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
846 $sSQL .= ' ORDER BY rank_search ASC ';
847 $sSQL .= " LIMIT $iLimit";
849 Debug::printSQL($sSQL);
851 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
852 $aResults[$iPlaceId] = new Result($iPlaceId);
856 // NEAR and IN are handled the same
857 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
858 $sClassTable = $this->poiTable();
859 $bCacheTable = $oDB->tableExists($sClassTable);
861 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
862 Debug::printSQL($sSQL);
863 $iMaxRank = (int) $oDB->getOne($sSQL);
865 // For state / country level searches the normal radius search doesn't work very well
867 if ($iMaxRank < 9 && $bCacheTable) {
868 // Try and get a polygon to search in instead
869 $sSQL = 'SELECT geometry FROM placex';
870 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
871 $sSQL .= " AND rank_search < $iMaxRank + 5";
872 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
873 $sSQL .= ' ORDER BY rank_search ASC ';
875 Debug::printSQL($sSQL);
876 $sPlaceGeom = $oDB->getOne($sSQL);
883 $sSQL = 'SELECT place_id FROM placex';
884 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
885 Debug::printSQL($sSQL);
886 $aPlaceIDs = $oDB->getCol($sSQL);
887 $sPlaceIDs = join(',', $aPlaceIDs);
890 if ($sPlaceIDs || $sPlaceGeom) {
893 // More efficient - can make the range bigger
897 if ($this->oContext->hasNearPoint()) {
898 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
899 } elseif ($sPlaceIDs) {
900 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
901 } elseif ($sPlaceGeom) {
902 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
905 $sSQL = 'SELECT distinct i.place_id';
907 $sSQL .= ', i.order_term';
909 $sSQL .= ' from (SELECT l.place_id';
911 $sSQL .= ','.$sOrderBySQL.' as order_term';
913 $sSQL .= ' from '.$sClassTable.' as l';
916 $sSQL .= ',placex as f WHERE ';
917 $sSQL .= "f.place_id in ($sPlaceIDs) ";
918 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
919 } elseif ($sPlaceGeom) {
920 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
923 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
924 $sSQL .= 'limit 300) i ';
926 $sSQL .= 'order by order_term asc';
928 $sSQL .= " limit $iLimit";
930 Debug::printSQL($sSQL);
932 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
933 $aResults[$iPlaceId] = new Result($iPlaceId);
936 if ($this->oContext->hasNearPoint()) {
937 $fRange = $this->oContext->nearRadius();
941 if ($this->oContext->hasNearPoint()) {
942 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
944 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
947 $sSQL = 'SELECT distinct l.place_id';
949 $sSQL .= ','.$sOrderBySQL.' as orderterm';
951 $sSQL .= ' FROM placex as l, placex as f';
952 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
953 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
954 $sSQL .= " AND l.class='".$this->sClass."'";
955 $sSQL .= " AND l.type='".$this->sType."'";
956 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
958 $sSQL .= 'ORDER BY orderterm ASC';
960 $sSQL .= " limit $iLimit";
962 Debug::printSQL($sSQL);
964 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
965 $aResults[$iPlaceId] = new Result($iPlaceId);
974 private function poiTable()
976 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
979 private function countryCodeSQL($sVar)
981 if ($this->sCountryCode) {
982 return $sVar.' = \''.$this->sCountryCode."'";
984 if ($this->oContext->sqlCountryList) {
985 return $sVar.' in '.$this->oContext->sqlCountryList;
991 /////////// Sort functions
994 public static function bySearchRank($a, $b)
996 if ($a->iSearchRank == $b->iSearchRank) {
997 return $a->iOperator + strlen($a->sHouseNumber)
998 - $b->iOperator - strlen($b->sHouseNumber);
1001 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1004 //////////// Debugging functions
1007 public function debugInfo()
1010 'Search rank' => $this->iSearchRank,
1011 'Country code' => $this->sCountryCode,
1012 'Name terms' => $this->aName,
1013 'Name terms (stop words)' => $this->aNameNonSearch,
1014 'Address terms' => $this->aAddress,
1015 'Address terms (stop words)' => $this->aAddressNonSearch,
1016 'Address terms (full words)' => $this->aFullNameAddress ?? '',
1017 'Special search' => $this->iOperator,
1018 'Class' => $this->sClass,
1019 'Type' => $this->sType,
1020 'House number' => $this->sHouseNumber,
1021 'Postcode' => $this->sPostcode
1025 public function dumpAsHtmlTableRow(&$aWordIDs)
1027 $kf = function ($k) use (&$aWordIDs) {
1028 return $aWordIDs[$k] ?? '['.$k.']';
1032 echo "<td>$this->iSearchRank</td>";
1033 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1034 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1035 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1036 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1037 echo '<td>'.$this->sCountryCode.'</td>';
1038 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1039 echo '<td>'.$this->sClass.'</td>';
1040 echo '<td>'.$this->sType.'</td>';
1041 echo '<td>'.$this->sPostcode.'</td>';
1042 echo '<td>'.$this->sHouseNumber.'</td>';