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;
182 $oSearch->iNamePhrase = -1;
184 $aNewSearches[] = $oSearch;
186 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
187 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
189 if (!$this->sPostcode) {
190 // If we have structured search or this is the first term,
191 // make the postcode the primary search element.
192 if ($this->iOperator == Operator::NONE && $bFirstToken) {
193 $oSearch = clone $this;
194 $oSearch->iSearchRank++;
195 $oSearch->iOperator = Operator::POSTCODE;
196 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
198 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
199 $aNewSearches[] = $oSearch;
202 // If we have a structured search or this is not the first term,
203 // add the postcode as an addendum.
204 if ($this->iOperator != Operator::POSTCODE
205 && ($sPhraseType == 'postalcode' || !empty($this->aName))
207 $oSearch = clone $this;
208 $oSearch->iSearchRank++;
209 $oSearch->iNamePhrase = -1;
210 if (strlen($oSearchTerm->sPostcode) < 4) {
211 $oSearch->iSearchRank += 4 - strlen($oSearchTerm->sPostcode);
213 $oSearch->sPostcode = $oSearchTerm->sPostcode;
214 $aNewSearches[] = $oSearch;
217 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
218 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
220 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
221 $oSearch = clone $this;
222 $oSearch->iSearchRank++;
223 $oSearch->iNamePhrase = -1;
224 $oSearch->sHouseNumber = $oSearchTerm->sToken;
225 if ($this->iOperator != Operator::NONE) {
226 $oSearch->iSearchRank++;
228 // sanity check: if the housenumber is not mainly made
229 // up of numbers, add a penalty
230 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
231 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
232 $oSearch->iSearchRank++;
234 if (empty($oSearchTerm->iId)) {
235 $oSearch->iSearchRank++;
237 // also must not appear in the middle of the address
238 if (!empty($this->aAddress)
239 || (!empty($this->aAddressNonSearch))
242 $oSearch->iSearchRank++;
244 $aNewSearches[] = $oSearch;
245 // Housenumbers may appear in the name when the place has its own
247 if ($oSearchTerm->iId !== null
248 && ($this->iNamePhrase >= 0 || empty($this->aName))
249 && empty($this->aAddress)
251 $oSearch = clone $this;
252 $oSearch->iSearchRank++;
253 $oSearch->aAddress = $this->aName;
254 $oSearch->bRareName = false;
255 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
256 $aNewSearches[] = $oSearch;
259 } elseif ($sPhraseType == ''
260 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
262 if ($this->iOperator == Operator::NONE) {
263 $oSearch = clone $this;
264 $oSearch->iSearchRank += 2;
265 $oSearch->iNamePhrase = -1;
267 $iOp = $oSearchTerm->iOperator;
268 if ($iOp == Operator::NONE) {
269 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
270 $iOp = Operator::NAME;
272 $iOp = Operator::NEAR;
274 $oSearch->iSearchRank += 2;
275 } elseif (!$bFirstToken && !$bLastToken) {
276 $oSearch->iSearchRank += 2;
278 if ($this->sHouseNumber) {
279 $oSearch->iSearchRank++;
282 $oSearch->setPoiSearch(
284 $oSearchTerm->sClass,
287 $aNewSearches[] = $oSearch;
289 } elseif ($sPhraseType != 'country'
290 && is_a($oSearchTerm, '\Nominatim\Token\Word')
292 $iWordID = $oSearchTerm->iId;
293 // Full words can only be a name if they appear at the beginning
294 // of the phrase. In structured search the name must forcably in
295 // the first phrase. In unstructured search it may be in a later
296 // phrase when the first phrase is a house number.
297 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
298 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
299 $oSearch = clone $this;
300 $oSearch->iNamePhrase = -1;
301 $oSearch->iSearchRank += 3 * $oSearchTerm->iTermCount;
302 $oSearch->aAddress[$iWordID] = $iWordID;
303 $aNewSearches[] = $oSearch;
305 } elseif (empty($this->aNameNonSearch)) {
306 $oSearch = clone $this;
307 $oSearch->iSearchRank++;
308 $oSearch->aName = array($iWordID => $iWordID);
309 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
310 $oSearch->bRareName =
311 $oSearchTerm->iSearchNameCount
312 < CONST_Search_NameOnlySearchFrequencyThreshold;
314 $aNewSearches[] = $oSearch;
318 return $aNewSearches;
322 * Derive new searches by adding a partial term to the existing search.
324 * @param string $sToken Term for the token.
325 * @param object $oSearchTerm Description of the token.
326 * @param bool $bStructuredPhrases True if the search is structured.
327 * @param integer $iPhrase Number of the phrase the token is in.
328 * @param array[] $aFullTokens List of full term tokens with the
331 * @return SearchDescription[] List of derived search descriptions.
333 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
335 // Only allow name terms.
336 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))
337 || strpos($sToken, ' ') !== false
342 $aNewSearches = array();
343 $iWordID = $oSearchTerm->iId;
345 if ((!$bStructuredPhrases || $iPhrase > 0)
346 && (!empty($this->aName))
348 $oSearch = clone $this;
349 $oSearch->iSearchRank++;
350 if (preg_match('#^[0-9 ]+$#', $sToken)) {
351 $oSearch->iSearchRank++;
353 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
354 $oSearch->aAddress[$iWordID] = $iWordID;
356 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
357 if (!empty($aFullTokens)) {
358 $oSearch->iSearchRank++;
361 $aNewSearches[] = $oSearch;
364 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
365 && ((empty($this->aName) && empty($this->aNameNonSearch)) || $this->iNamePhrase == $iPhrase)
367 $oSearch = clone $this;
368 $oSearch->iSearchRank++;
369 if (empty($this->aName) && empty($this->aNameNonSearch)) {
370 $oSearch->iSearchRank++;
372 if (preg_match('#^[0-9 ]+$#', $sToken)) {
373 $oSearch->iSearchRank++;
375 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
376 if (empty($this->aName)
377 && CONST_Search_NameOnlySearchFrequencyThreshold
379 $oSearch->bRareName =
380 $oSearchTerm->iSearchNameCount
381 < CONST_Search_NameOnlySearchFrequencyThreshold;
383 $oSearch->bRareName = false;
385 $oSearch->aName[$iWordID] = $iWordID;
387 if (!empty($aFullTokens)) {
388 $oSearch->iSearchRank++;
390 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
392 $oSearch->iNamePhrase = $iPhrase;
393 $aNewSearches[] = $oSearch;
396 return $aNewSearches;
399 /////////// Query functions
403 * Query database for places that match this search.
405 * @param object $oDB Nominatim::DB instance to use.
406 * @param integer $iMinRank Minimum address rank to restrict search to.
407 * @param integer $iMaxRank Maximum address rank to restrict search to.
408 * @param integer $iLimit Maximum number of results.
410 * @return mixed[] An array with two fields: IDs contains the list of
411 * matching place IDs and houseNumber the houseNumber
412 * if appicable or -1 if not.
414 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
419 if ($this->sCountryCode
420 && empty($this->aName)
423 && !$this->oContext->hasNearPoint()
425 // Just looking for a country - look it up
426 if (4 >= $iMinRank && 4 <= $iMaxRank) {
427 $aResults = $this->queryCountry($oDB);
429 } elseif (empty($this->aName) && empty($this->aAddress)) {
430 // Neither name nor address? Then we must be
431 // looking for a POI in a geographic area.
432 if ($this->oContext->isBoundedSearch()) {
433 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
435 } elseif ($this->iOperator == Operator::POSTCODE) {
436 // looking for postcode
437 $aResults = $this->queryPostcode($oDB, $iLimit);
440 // First search for places according to name and address.
441 $aResults = $this->queryNamedPlace(
448 // Now search for housenumber, if housenumber provided. Can be zero.
449 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
450 // Downgrade the rank of the street results, they are missing
452 foreach ($aResults as $oRes) {
453 if ($oRes->iAddressRank >= 26) {
454 $oRes->iResultRank++;
456 $oRes->iResultRank += 2;
460 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
462 if (!empty($aHnResults)) {
463 foreach ($aHnResults as $oRes) {
464 $aResults[$oRes->iId] = $oRes;
469 // finally get POIs if requested
470 if ($this->sClass && !empty($aResults)) {
471 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
475 Debug::printDebugTable('Place IDs', $aResults);
477 if (!empty($aResults) && $this->sPostcode) {
478 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
480 $sSQL = 'SELECT place_id FROM placex';
481 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
482 $sSQL .= " AND postcode != '".$this->sPostcode."'";
483 Debug::printSQL($sSQL);
484 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
485 if ($aFilteredPlaceIDs) {
486 foreach ($aFilteredPlaceIDs as $iPlaceId) {
487 $aResults[$iPlaceId]->iResultRank++;
497 private function queryCountry(&$oDB)
499 $sSQL = 'SELECT place_id FROM placex ';
500 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
501 $sSQL .= ' AND rank_search = 4';
502 if ($this->oContext->bViewboxBounded) {
503 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
505 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
507 Debug::printSQL($sSQL);
509 $iPlaceId = $oDB->getOne($sSQL);
513 $aResults[$iPlaceId] = new Result($iPlaceId);
519 private function queryNearbyPoi(&$oDB, $iLimit)
521 if (!$this->sClass) {
525 $aDBResults = array();
526 $sPoiTable = $this->poiTable();
528 if ($oDB->tableExists($sPoiTable)) {
529 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
530 if ($this->oContext->sqlCountryList) {
531 $sSQL .= ' JOIN placex USING (place_id)';
533 if ($this->oContext->hasNearPoint()) {
534 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
535 } elseif ($this->oContext->bViewboxBounded) {
536 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
538 if ($this->oContext->sqlCountryList) {
539 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
541 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
542 if ($this->oContext->sqlViewboxCentre) {
543 $sSQL .= ' ORDER BY ST_Distance(';
544 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
545 } elseif ($this->oContext->hasNearPoint()) {
546 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
548 $sSQL .= " LIMIT $iLimit";
549 Debug::printSQL($sSQL);
550 $aDBResults = $oDB->getCol($sSQL);
553 if ($this->oContext->hasNearPoint()) {
554 $sSQL = 'SELECT place_id FROM placex WHERE ';
555 $sSQL .= 'class = :class and type = :type';
556 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
557 $sSQL .= ' AND linked_place_id is null';
558 if ($this->oContext->sqlCountryList) {
559 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
561 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
562 $sSQL .= " LIMIT $iLimit";
563 Debug::printSQL($sSQL);
564 $aDBResults = $oDB->getCol(
566 array(':class' => $this->sClass, ':type' => $this->sType)
571 foreach ($aDBResults as $iPlaceId) {
572 $aResults[$iPlaceId] = new Result($iPlaceId);
578 private function queryPostcode(&$oDB, $iLimit)
580 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
582 if (!empty($this->aAddress)) {
583 $sSQL .= ', search_name s ';
584 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
585 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
586 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
591 $sSQL .= "p.postcode = '".reset($this->aName)."'";
592 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
593 if ($this->oContext->bViewboxBounded) {
594 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
596 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
597 $sSQL .= " LIMIT $iLimit";
599 Debug::printSQL($sSQL);
602 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
603 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
609 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
614 // Sort by existence of the requested house number but only if not
615 // too many results are expected for the street, i.e. if the result
616 // will be narrowed down by an address. Remeber that with ordering
617 // every single result has to be checked.
618 if ($this->sHouseNumber && ($this->bRareName || !empty($this->aAddress) || $this->sPostcode)) {
619 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
621 $aOrder[0] .= 'EXISTS(';
622 $aOrder[0] .= ' SELECT place_id';
623 $aOrder[0] .= ' FROM placex';
624 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
625 $aOrder[0] .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
626 $aOrder[0] .= ' LIMIT 1';
628 // also housenumbers from interpolation lines table are needed
629 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
630 $iHouseNumber = intval($this->sHouseNumber);
631 $aOrder[0] .= 'OR EXISTS(';
632 $aOrder[0] .= ' SELECT place_id ';
633 $aOrder[0] .= ' FROM location_property_osmline ';
634 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
635 $aOrder[0] .= ' AND startnumber is not NULL';
636 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
637 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
638 $aOrder[0] .= ' LIMIT 1';
641 $aOrder[0] .= ') DESC';
644 if (!empty($this->aName)) {
645 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
647 if (!empty($this->aAddress)) {
648 // For infrequent name terms disable index usage for address
649 if ($this->bRareName) {
650 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
652 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
656 $sCountryTerm = $this->countryCodeSQL('country_code');
658 $aTerms[] = $sCountryTerm;
661 if ($this->sHouseNumber) {
662 $aTerms[] = 'address_rank between 16 and 30';
663 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
664 if ($iMinAddressRank > 0) {
665 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
669 if ($this->oContext->hasNearPoint()) {
670 $aTerms[] = $this->oContext->withinSQL('centroid');
671 $aOrder[] = $this->oContext->distanceSQL('centroid');
672 } elseif ($this->sPostcode) {
673 if (empty($this->aAddress)) {
674 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
676 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
680 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
682 $aTerms[] = $sExcludeSQL;
685 if ($this->oContext->bViewboxBounded) {
686 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
689 if ($this->oContext->hasNearPoint()) {
690 $aOrder[] = $this->oContext->distanceSQL('centroid');
693 if ($this->sHouseNumber) {
694 $sImportanceSQL = '- abs(26 - address_rank) + 3';
696 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
698 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
699 $aOrder[] = "$sImportanceSQL DESC";
701 $aFullNameAddress = $this->oContext->getFullNameTerms();
702 if (!empty($aFullNameAddress)) {
703 $sExactMatchSQL = ' ( ';
704 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
705 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($aFullNameAddress).')';
706 $sExactMatchSQL .= ' INTERSECT ';
707 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
708 $sExactMatchSQL .= ' ) s';
709 $sExactMatchSQL .= ') as exactmatch';
710 $aOrder[] = 'exactmatch DESC';
712 $sExactMatchSQL = '0::int as exactmatch';
715 if ($this->sHouseNumber || $this->sClass) {
721 if (!empty($aTerms)) {
722 $sSQL = 'SELECT place_id, address_rank,'.$sExactMatchSQL;
723 $sSQL .= ' FROM search_name';
724 $sSQL .= ' WHERE '.join(' and ', $aTerms);
725 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
726 $sSQL .= ' LIMIT '.$iLimit;
728 Debug::printSQL($sSQL);
730 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
732 foreach ($aDBResults as $aResult) {
733 $oResult = new Result($aResult['place_id']);
734 $oResult->iExactMatches = $aResult['exactmatch'];
735 $oResult->iAddressRank = $aResult['address_rank'];
736 $aResults[$aResult['place_id']] = $oResult;
743 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
746 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
752 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
753 $sSQL = 'SELECT place_id FROM placex ';
754 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
755 $sSQL .= " AND housenumber ~* E'".$sHouseNumberRegex."'";
756 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
758 Debug::printSQL($sSQL);
760 // XXX should inherit the exactMatches from its parent
761 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
762 $aResults[$iPlaceId] = new Result($iPlaceId);
765 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
766 $iHousenumber = intval($this->sHouseNumber);
767 if ($bIsIntHouseNumber && empty($aResults)) {
768 // if nothing found, search in the interpolation line table
769 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
770 $sSQL .= ' WHERE startnumber is not NULL';
771 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
772 if ($iHousenumber % 2 == 0) {
773 // If housenumber is even, look for housenumber in streets
774 // with interpolationtype even or all.
775 $sSQL .= "interpolationtype='even'";
777 // Else look for housenumber with interpolationtype odd or all.
778 $sSQL .= "interpolationtype='odd'";
780 $sSQL .= " or interpolationtype='all') and ";
781 $sSQL .= $iHousenumber.'>=startnumber and ';
782 $sSQL .= $iHousenumber.'<=endnumber';
783 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
785 Debug::printSQL($sSQL);
787 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
788 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
789 $oResult->iHouseNumber = $iHousenumber;
790 $aResults[$iPlaceId] = $oResult;
794 // If nothing found then search in Tiger data (location_property_tiger)
795 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
796 $sSQL = 'SELECT place_id FROM location_property_tiger';
797 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
798 if ($iHousenumber % 2 == 0) {
799 $sSQL .= "interpolationtype='even'";
801 $sSQL .= "interpolationtype='odd'";
803 $sSQL .= " or interpolationtype='all') and ";
804 $sSQL .= $iHousenumber.'>=startnumber and ';
805 $sSQL .= $iHousenumber.'<=endnumber';
806 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
808 Debug::printSQL($sSQL);
810 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
811 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
812 $oResult->iHouseNumber = $iHousenumber;
813 $aResults[$iPlaceId] = $oResult;
821 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
824 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
830 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
831 // If they were searching for a named class (i.e. 'Kings Head pub')
832 // then we might have an extra match
833 $sSQL = 'SELECT place_id FROM placex ';
834 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
835 $sSQL .= " AND class='".$this->sClass."' ";
836 $sSQL .= " AND type='".$this->sType."'";
837 $sSQL .= ' AND linked_place_id is null';
838 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
839 $sSQL .= ' ORDER BY rank_search ASC ';
840 $sSQL .= " LIMIT $iLimit";
842 Debug::printSQL($sSQL);
844 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
845 $aResults[$iPlaceId] = new Result($iPlaceId);
849 // NEAR and IN are handled the same
850 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
851 $sClassTable = $this->poiTable();
852 $bCacheTable = $oDB->tableExists($sClassTable);
854 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
855 Debug::printSQL($sSQL);
856 $iMaxRank = (int) $oDB->getOne($sSQL);
858 // For state / country level searches the normal radius search doesn't work very well
860 if ($iMaxRank < 9 && $bCacheTable) {
861 // Try and get a polygon to search in instead
862 $sSQL = 'SELECT geometry FROM placex';
863 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
864 $sSQL .= " AND rank_search < $iMaxRank + 5";
865 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
866 $sSQL .= ' ORDER BY rank_search ASC ';
868 Debug::printSQL($sSQL);
869 $sPlaceGeom = $oDB->getOne($sSQL);
876 $sSQL = 'SELECT place_id FROM placex';
877 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
878 Debug::printSQL($sSQL);
879 $aPlaceIDs = $oDB->getCol($sSQL);
880 $sPlaceIDs = join(',', $aPlaceIDs);
883 if ($sPlaceIDs || $sPlaceGeom) {
886 // More efficient - can make the range bigger
890 if ($this->oContext->hasNearPoint()) {
891 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
892 } elseif ($sPlaceIDs) {
893 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
894 } elseif ($sPlaceGeom) {
895 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
898 $sSQL = 'SELECT distinct i.place_id';
900 $sSQL .= ', i.order_term';
902 $sSQL .= ' from (SELECT l.place_id';
904 $sSQL .= ','.$sOrderBySQL.' as order_term';
906 $sSQL .= ' from '.$sClassTable.' as l';
909 $sSQL .= ',placex as f WHERE ';
910 $sSQL .= "f.place_id in ($sPlaceIDs) ";
911 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
912 } elseif ($sPlaceGeom) {
913 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
916 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
917 $sSQL .= 'limit 300) i ';
919 $sSQL .= 'order by order_term asc';
921 $sSQL .= " limit $iLimit";
923 Debug::printSQL($sSQL);
925 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
926 $aResults[$iPlaceId] = new Result($iPlaceId);
929 if ($this->oContext->hasNearPoint()) {
930 $fRange = $this->oContext->nearRadius();
934 if ($this->oContext->hasNearPoint()) {
935 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
937 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
940 $sSQL = 'SELECT distinct l.place_id';
942 $sSQL .= ','.$sOrderBySQL.' as orderterm';
944 $sSQL .= ' FROM placex as l, placex as f';
945 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
946 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
947 $sSQL .= " AND l.class='".$this->sClass."'";
948 $sSQL .= " AND l.type='".$this->sType."'";
949 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
951 $sSQL .= 'ORDER BY orderterm ASC';
953 $sSQL .= " limit $iLimit";
955 Debug::printSQL($sSQL);
957 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
958 $aResults[$iPlaceId] = new Result($iPlaceId);
967 private function poiTable()
969 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
972 private function countryCodeSQL($sVar)
974 if ($this->sCountryCode) {
975 return $sVar.' = \''.$this->sCountryCode."'";
977 if ($this->oContext->sqlCountryList) {
978 return $sVar.' in '.$this->oContext->sqlCountryList;
984 /////////// Sort functions
987 public static function bySearchRank($a, $b)
989 if ($a->iSearchRank == $b->iSearchRank) {
990 return $a->iOperator + strlen($a->sHouseNumber)
991 - $b->iOperator - strlen($b->sHouseNumber);
994 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
997 //////////// Debugging functions
1000 public function debugInfo()
1003 'Search rank' => $this->iSearchRank,
1004 'Country code' => $this->sCountryCode,
1005 'Name terms' => $this->aName,
1006 'Name terms (stop words)' => $this->aNameNonSearch,
1007 'Address terms' => $this->aAddress,
1008 'Address terms (stop words)' => $this->aAddressNonSearch,
1009 'Address terms (full words)' => $this->aFullNameAddress ?? '',
1010 'Special search' => $this->iOperator,
1011 'Class' => $this->sClass,
1012 'Type' => $this->sType,
1013 'House number' => $this->sHouseNumber,
1014 'Postcode' => $this->sPostcode
1018 public function dumpAsHtmlTableRow(&$aWordIDs)
1020 $kf = function ($k) use (&$aWordIDs) {
1021 return $aWordIDs[$k] ?? '['.$k.']';
1025 echo "<td>$this->iSearchRank</td>";
1026 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1027 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1028 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1029 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1030 echo '<td>'.$this->sCountryCode.'</td>';
1031 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1032 echo '<td>'.$this->sClass.'</td>';
1033 echo '<td>'.$this->sType.'</td>';
1034 echo '<td>'.$this->sPostcode.'</td>';
1035 echo '<td>'.$this->sHouseNumber.'</td>';