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 if (!$this->sPostcode) {
203 // If we have structured search or this is the first term,
204 // make the postcode the primary search element.
205 if ($this->iOperator == Operator::NONE && $bFirstToken) {
206 $oSearch = clone $this;
207 $oSearch->iSearchRank++;
208 $oSearch->iOperator = Operator::POSTCODE;
209 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
211 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
212 $aNewSearches[] = $oSearch;
215 // If we have a structured search or this is not the first term,
216 // add the postcode as an addendum.
217 if ($this->iOperator != Operator::POSTCODE
218 && ($sPhraseType == 'postalcode' || !empty($this->aName))
220 $oSearch = clone $this;
221 $oSearch->iSearchRank++;
222 $oSearch->sPostcode = $oSearchTerm->sPostcode;
223 $aNewSearches[] = $oSearch;
226 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
227 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
229 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
230 $oSearch = clone $this;
231 $oSearch->iSearchRank++;
232 $oSearch->sHouseNumber = $oSearchTerm->sToken;
233 // sanity check: if the housenumber is not mainly made
234 // up of numbers, add a penalty
235 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
236 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
237 $oSearch->iSearchRank++;
239 if (empty($oSearchTerm->iId)) {
240 $oSearch->iSearchRank++;
242 // also must not appear in the middle of the address
243 if (!empty($this->aAddress)
244 || (!empty($this->aAddressNonSearch))
247 $oSearch->iSearchRank++;
249 $aNewSearches[] = $oSearch;
250 // Housenumbers may appear in the name when the place has its own
252 if ($oSearchTerm->iId !== null
253 && ($this->iNamePhrase >= 0 || empty($this->aName))
254 && empty($this->aAddress)
256 $oSearch = clone $this;
257 $oSearch->iSearchRank++;
258 $oSearch->aAddress = $this->aName;
259 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
260 $aNewSearches[] = $oSearch;
263 } elseif ($sPhraseType == ''
264 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
266 if ($this->iOperator == Operator::NONE) {
267 $oSearch = clone $this;
268 $oSearch->iSearchRank++;
270 $iOp = $oSearchTerm->iOperator;
271 if ($iOp == Operator::NONE) {
272 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
273 $iOp = Operator::NAME;
275 $iOp = Operator::NEAR;
277 $oSearch->iSearchRank += 2;
280 $oSearch->setPoiSearch(
282 $oSearchTerm->sClass,
285 $aNewSearches[] = $oSearch;
287 } elseif ($sPhraseType != 'country'
288 && is_a($oSearchTerm, '\Nominatim\Token\Word')
290 $iWordID = $oSearchTerm->iId;
291 // Full words can only be a name if they appear at the beginning
292 // of the phrase. In structured search the name must forcably in
293 // the first phrase. In unstructured search it may be in a later
294 // phrase when the first phrase is a house number.
295 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
296 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
297 $oSearch = clone $this;
298 $oSearch->iSearchRank += 2;
299 $oSearch->aAddress[$iWordID] = $iWordID;
300 $aNewSearches[] = $oSearch;
302 $this->aFullNameAddress[$iWordID] = $iWordID;
305 $oSearch = clone $this;
306 $oSearch->iSearchRank++;
307 $oSearch->aName = array($iWordID => $iWordID);
308 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
309 $oSearch->bRareName =
310 $oSearchTerm->iSearchNameCount
311 < CONST_Search_NameOnlySearchFrequencyThreshold;
313 $aNewSearches[] = $oSearch;
317 return $aNewSearches;
321 * Derive new searches by adding a partial term to the existing search.
323 * @param string $sToken Term for the token.
324 * @param object $oSearchTerm Description of the token.
325 * @param bool $bStructuredPhrases True if the search is structured.
326 * @param integer $iPhrase Number of the phrase the token is in.
327 * @param array[] $aFullTokens List of full term tokens with the
330 * @return SearchDescription[] List of derived search descriptions.
332 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
334 // Only allow name terms.
335 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
339 $aNewSearches = array();
340 $iWordID = $oSearchTerm->iId;
342 if ((!$bStructuredPhrases || $iPhrase > 0)
343 && (!empty($this->aName))
344 && strpos($sToken, ' ') === false
346 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
347 $oSearch = clone $this;
348 $oSearch->iSearchRank += 2;
349 $oSearch->aAddress[$iWordID] = $iWordID;
350 $aNewSearches[] = $oSearch;
352 $oSearch = clone $this;
353 $oSearch->iSearchRank++;
354 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
355 if (preg_match('#^[0-9]+$#', $sToken)) {
356 $oSearch->iSearchRank += 2;
358 if (!empty($aFullTokens)) {
359 $oSearch->iSearchRank++;
361 $aNewSearches[] = $oSearch;
363 // revert to the token version?
364 foreach ($aFullTokens as $oSearchTermToken) {
365 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
366 $oSearch = clone $this;
367 $oSearch->iSearchRank++;
368 $oSearch->aAddress[$oSearchTermToken->iId]
369 = $oSearchTermToken->iId;
370 $aNewSearches[] = $oSearch;
376 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
377 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
379 $oSearch = clone $this;
380 $oSearch->iSearchRank += 2;
381 if (empty($this->aName)) {
382 $oSearch->iSearchRank += 1;
384 if (preg_match('#^[0-9]+$#', $sToken)) {
385 $oSearch->iSearchRank += 2;
387 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
388 if (empty($this->aName)
389 && CONST_Search_NameOnlySearchFrequencyThreshold
391 $oSearch->bRareName =
392 $oSearchTerm->iSearchNameCount
393 < CONST_Search_NameOnlySearchFrequencyThreshold;
395 $oSearch->bRareName = false;
397 $oSearch->aName[$iWordID] = $iWordID;
399 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
401 $oSearch->iNamePhrase = $iPhrase;
402 $aNewSearches[] = $oSearch;
405 return $aNewSearches;
408 /////////// Query functions
412 * Query database for places that match this search.
414 * @param object $oDB Nominatim::DB instance to use.
415 * @param integer $iMinRank Minimum address rank to restrict search to.
416 * @param integer $iMaxRank Maximum address rank to restrict search to.
417 * @param integer $iLimit Maximum number of results.
419 * @return mixed[] An array with two fields: IDs contains the list of
420 * matching place IDs and houseNumber the houseNumber
421 * if appicable or -1 if not.
423 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
428 if ($this->sCountryCode
429 && empty($this->aName)
432 && !$this->oContext->hasNearPoint()
434 // Just looking for a country - look it up
435 if (4 >= $iMinRank && 4 <= $iMaxRank) {
436 $aResults = $this->queryCountry($oDB);
438 } elseif (empty($this->aName) && empty($this->aAddress)) {
439 // Neither name nor address? Then we must be
440 // looking for a POI in a geographic area.
441 if ($this->oContext->isBoundedSearch()) {
442 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
444 } elseif ($this->iOperator == Operator::POSTCODE) {
445 // looking for postcode
446 $aResults = $this->queryPostcode($oDB, $iLimit);
449 // First search for places according to name and address.
450 $aResults = $this->queryNamedPlace(
457 // Now search for housenumber, if housenumber provided. Can be zero.
458 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
459 // Downgrade the rank of the street results, they are missing
461 foreach ($aResults as $oRes) {
462 $oRes->iResultRank++;
465 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
467 if (!empty($aHnResults)) {
468 foreach ($aHnResults as $oRes) {
469 $aResults[$oRes->iId] = $oRes;
474 // finally get POIs if requested
475 if ($this->sClass && !empty($aResults)) {
476 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
480 Debug::printDebugTable('Place IDs', $aResults);
482 if (!empty($aResults) && $this->sPostcode) {
483 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
485 $sSQL = 'SELECT place_id FROM placex';
486 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
487 $sSQL .= " AND postcode != '".$this->sPostcode."'";
488 Debug::printSQL($sSQL);
489 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
490 if ($aFilteredPlaceIDs) {
491 foreach ($aFilteredPlaceIDs as $iPlaceId) {
492 $aResults[$iPlaceId]->iResultRank++;
502 private function queryCountry(&$oDB)
504 $sSQL = 'SELECT place_id FROM placex ';
505 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
506 $sSQL .= ' AND rank_search = 4';
507 if ($this->oContext->bViewboxBounded) {
508 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
510 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
512 Debug::printSQL($sSQL);
514 $iPlaceId = $oDB->getOne($sSQL);
518 $aResults[$iPlaceId] = new Result($iPlaceId);
524 private function queryNearbyPoi(&$oDB, $iLimit)
526 if (!$this->sClass) {
530 $aDBResults = array();
531 $sPoiTable = $this->poiTable();
533 if ($oDB->tableExists($sPoiTable)) {
534 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
535 if ($this->oContext->sqlCountryList) {
536 $sSQL .= ' JOIN placex USING (place_id)';
538 if ($this->oContext->hasNearPoint()) {
539 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
540 } elseif ($this->oContext->bViewboxBounded) {
541 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
543 if ($this->oContext->sqlCountryList) {
544 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
546 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
547 if ($this->oContext->sqlViewboxCentre) {
548 $sSQL .= ' ORDER BY ST_Distance(';
549 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
550 } elseif ($this->oContext->hasNearPoint()) {
551 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
553 $sSQL .= " LIMIT $iLimit";
554 Debug::printSQL($sSQL);
555 $aDBResults = $oDB->getCol($sSQL);
558 if ($this->oContext->hasNearPoint()) {
559 $sSQL = 'SELECT place_id FROM placex WHERE ';
560 $sSQL .= 'class = :class and type = :type';
561 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
562 $sSQL .= ' AND linked_place_id is null';
563 if ($this->oContext->sqlCountryList) {
564 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
566 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
567 $sSQL .= " LIMIT $iLimit";
568 Debug::printSQL($sSQL);
569 $aDBResults = $oDB->getCol(
571 array(':class' => $this->sClass, ':type' => $this->sType)
576 foreach ($aDBResults as $iPlaceId) {
577 $aResults[$iPlaceId] = new Result($iPlaceId);
583 private function queryPostcode(&$oDB, $iLimit)
585 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
587 if (!empty($this->aAddress)) {
588 $sSQL .= ', search_name s ';
589 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
590 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
591 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
596 $sSQL .= "p.postcode = '".reset($this->aName)."'";
597 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
598 if ($this->oContext->bViewboxBounded) {
599 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
601 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
602 $sSQL .= " LIMIT $iLimit";
604 Debug::printSQL($sSQL);
607 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
608 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
614 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
619 // Sort by existence of the requested house number but only if not
620 // too many results are expected for the street, i.e. if the result
621 // will be narrowed down by an address. Remeber that with ordering
622 // every single result has to be checked.
623 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
624 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
626 $aOrder[0] .= 'EXISTS(';
627 $aOrder[0] .= ' SELECT place_id';
628 $aOrder[0] .= ' FROM placex';
629 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
630 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
631 $aOrder[0] .= ' LIMIT 1';
633 // also housenumbers from interpolation lines table are needed
634 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
635 $iHouseNumber = intval($this->sHouseNumber);
636 $aOrder[0] .= 'OR EXISTS(';
637 $aOrder[0] .= ' SELECT place_id ';
638 $aOrder[0] .= ' FROM location_property_osmline ';
639 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
640 $aOrder[0] .= ' AND startnumber is not NULL';
641 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
642 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
643 $aOrder[0] .= ' LIMIT 1';
646 $aOrder[0] .= ') DESC';
649 if (!empty($this->aName)) {
650 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
652 if (!empty($this->aAddress)) {
653 // For infrequent name terms disable index usage for address
654 if ($this->bRareName) {
655 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
657 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
661 $sCountryTerm = $this->countryCodeSQL('country_code');
663 $aTerms[] = $sCountryTerm;
666 if ($this->sHouseNumber) {
667 $aTerms[] = 'address_rank between 16 and 30';
668 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
669 if ($iMinAddressRank > 0) {
670 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
674 if ($this->oContext->hasNearPoint()) {
675 $aTerms[] = $this->oContext->withinSQL('centroid');
676 $aOrder[] = $this->oContext->distanceSQL('centroid');
677 } elseif ($this->sPostcode) {
678 if (empty($this->aAddress)) {
679 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
681 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
685 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
687 $aTerms[] = $sExcludeSQL;
690 if ($this->oContext->bViewboxBounded) {
691 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
694 if ($this->oContext->hasNearPoint()) {
695 $aOrder[] = $this->oContext->distanceSQL('centroid');
698 if ($this->sHouseNumber) {
699 $sImportanceSQL = '- abs(26 - address_rank) + 3';
701 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
703 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
704 $aOrder[] = "$sImportanceSQL DESC";
706 if (!empty($this->aFullNameAddress)) {
707 $sExactMatchSQL = ' ( ';
708 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
709 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($this->aFullNameAddress).')';
710 $sExactMatchSQL .= ' INTERSECT ';
711 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
712 $sExactMatchSQL .= ' ) s';
713 $sExactMatchSQL .= ') as exactmatch';
714 $aOrder[] = 'exactmatch DESC';
716 $sExactMatchSQL = '0::int as exactmatch';
719 if ($this->sHouseNumber || $this->sClass) {
725 if (!empty($aTerms)) {
726 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
727 $sSQL .= ' FROM search_name';
728 $sSQL .= ' WHERE '.join(' and ', $aTerms);
729 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
730 $sSQL .= ' LIMIT '.$iLimit;
732 Debug::printSQL($sSQL);
734 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
736 foreach ($aDBResults as $aResult) {
737 $oResult = new Result($aResult['place_id']);
738 $oResult->iExactMatches = $aResult['exactmatch'];
739 $aResults[$aResult['place_id']] = $oResult;
746 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
749 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
755 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
756 $sSQL = 'SELECT place_id FROM placex ';
757 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
758 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
759 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
761 Debug::printSQL($sSQL);
763 // XXX should inherit the exactMatches from its parent
764 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
765 $aResults[$iPlaceId] = new Result($iPlaceId);
768 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
769 $iHousenumber = intval($this->sHouseNumber);
770 if ($bIsIntHouseNumber && empty($aResults)) {
771 // if nothing found, search in the interpolation line table
772 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
773 $sSQL .= ' WHERE startnumber is not NULL';
774 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
775 if ($iHousenumber % 2 == 0) {
776 // If housenumber is even, look for housenumber in streets
777 // with interpolationtype even or all.
778 $sSQL .= "interpolationtype='even'";
780 // Else look for housenumber with interpolationtype odd or all.
781 $sSQL .= "interpolationtype='odd'";
783 $sSQL .= " or interpolationtype='all') and ";
784 $sSQL .= $iHousenumber.'>=startnumber and ';
785 $sSQL .= $iHousenumber.'<=endnumber';
786 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
788 Debug::printSQL($sSQL);
790 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
791 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
792 $oResult->iHouseNumber = $iHousenumber;
793 $aResults[$iPlaceId] = $oResult;
797 // If nothing found try the aux fallback table
798 if (CONST_Use_Aux_Location_data && empty($aResults)) {
799 $sSQL = 'SELECT place_id FROM location_property_aux';
800 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
801 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
802 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
804 Debug::printSQL($sSQL);
806 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
807 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
811 // If nothing found then search in Tiger data (location_property_tiger)
812 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
813 $sSQL = 'SELECT place_id FROM location_property_tiger';
814 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
815 if ($iHousenumber % 2 == 0) {
816 $sSQL .= "interpolationtype='even'";
818 $sSQL .= "interpolationtype='odd'";
820 $sSQL .= " or interpolationtype='all') and ";
821 $sSQL .= $iHousenumber.'>=startnumber and ';
822 $sSQL .= $iHousenumber.'<=endnumber';
823 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
825 Debug::printSQL($sSQL);
827 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
828 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
829 $oResult->iHouseNumber = $iHousenumber;
830 $aResults[$iPlaceId] = $oResult;
838 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
841 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
847 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
848 // If they were searching for a named class (i.e. 'Kings Head pub')
849 // then we might have an extra match
850 $sSQL = 'SELECT place_id FROM placex ';
851 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
852 $sSQL .= " AND class='".$this->sClass."' ";
853 $sSQL .= " AND type='".$this->sType."'";
854 $sSQL .= ' AND linked_place_id is null';
855 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
856 $sSQL .= ' ORDER BY rank_search ASC ';
857 $sSQL .= " LIMIT $iLimit";
859 Debug::printSQL($sSQL);
861 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
862 $aResults[$iPlaceId] = new Result($iPlaceId);
866 // NEAR and IN are handled the same
867 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
868 $sClassTable = $this->poiTable();
869 $bCacheTable = $oDB->tableExists($sClassTable);
871 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
872 Debug::printSQL($sSQL);
873 $iMaxRank = (int) $oDB->getOne($sSQL);
875 // For state / country level searches the normal radius search doesn't work very well
877 if ($iMaxRank < 9 && $bCacheTable) {
878 // Try and get a polygon to search in instead
879 $sSQL = 'SELECT geometry FROM placex';
880 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
881 $sSQL .= " AND rank_search < $iMaxRank + 5";
882 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
883 $sSQL .= ' ORDER BY rank_search ASC ';
885 Debug::printSQL($sSQL);
886 $sPlaceGeom = $oDB->getOne($sSQL);
893 $sSQL = 'SELECT place_id FROM placex';
894 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
895 Debug::printSQL($sSQL);
896 $aPlaceIDs = $oDB->getCol($sSQL);
897 $sPlaceIDs = join(',', $aPlaceIDs);
900 if ($sPlaceIDs || $sPlaceGeom) {
903 // More efficient - can make the range bigger
907 if ($this->oContext->hasNearPoint()) {
908 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
909 } elseif ($sPlaceIDs) {
910 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
911 } elseif ($sPlaceGeom) {
912 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
915 $sSQL = 'SELECT distinct i.place_id';
917 $sSQL .= ', i.order_term';
919 $sSQL .= ' from (SELECT l.place_id';
921 $sSQL .= ','.$sOrderBySQL.' as order_term';
923 $sSQL .= ' from '.$sClassTable.' as l';
926 $sSQL .= ',placex as f WHERE ';
927 $sSQL .= "f.place_id in ($sPlaceIDs) ";
928 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
929 } elseif ($sPlaceGeom) {
930 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
933 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
934 $sSQL .= 'limit 300) i ';
936 $sSQL .= 'order by order_term asc';
938 $sSQL .= " limit $iLimit";
940 Debug::printSQL($sSQL);
942 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
943 $aResults[$iPlaceId] = new Result($iPlaceId);
946 if ($this->oContext->hasNearPoint()) {
947 $fRange = $this->oContext->nearRadius();
951 if ($this->oContext->hasNearPoint()) {
952 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
954 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
957 $sSQL = 'SELECT distinct l.place_id';
959 $sSQL .= ','.$sOrderBySQL.' as orderterm';
961 $sSQL .= ' FROM placex as l, placex as f';
962 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
963 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
964 $sSQL .= " AND l.class='".$this->sClass."'";
965 $sSQL .= " AND l.type='".$this->sType."'";
966 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
968 $sSQL .= 'ORDER BY orderterm ASC';
970 $sSQL .= " limit $iLimit";
972 Debug::printSQL($sSQL);
974 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
975 $aResults[$iPlaceId] = new Result($iPlaceId);
984 private function poiTable()
986 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
989 private function countryCodeSQL($sVar)
991 if ($this->sCountryCode) {
992 return $sVar.' = \''.$this->sCountryCode."'";
994 if ($this->oContext->sqlCountryList) {
995 return $sVar.' in '.$this->oContext->sqlCountryList;
1001 /////////// Sort functions
1004 public static function bySearchRank($a, $b)
1006 if ($a->iSearchRank == $b->iSearchRank) {
1007 return $a->iOperator + strlen($a->sHouseNumber)
1008 - $b->iOperator - strlen($b->sHouseNumber);
1011 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1014 //////////// Debugging functions
1017 public function debugInfo()
1020 'Search rank' => $this->iSearchRank,
1021 'Country code' => $this->sCountryCode,
1022 'Name terms' => $this->aName,
1023 'Name terms (stop words)' => $this->aNameNonSearch,
1024 'Address terms' => $this->aAddress,
1025 'Address terms (stop words)' => $this->aAddressNonSearch,
1026 'Address terms (full words)' => $this->aFullNameAddress,
1027 'Special search' => $this->iOperator,
1028 'Class' => $this->sClass,
1029 'Type' => $this->sType,
1030 'House number' => $this->sHouseNumber,
1031 'Postcode' => $this->sPostcode
1035 public function dumpAsHtmlTableRow(&$aWordIDs)
1037 $kf = function ($k) use (&$aWordIDs) {
1038 return $aWordIDs[$k];
1042 echo "<td>$this->iSearchRank</td>";
1043 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1044 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1045 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1046 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1047 echo '<td>'.$this->sCountryCode.'</td>';
1048 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1049 echo '<td>'.$this->sClass.'</td>';
1050 echo '<td>'.$this->sType.'</td>';
1051 echo '<td>'.$this->sPostcode.'</td>';
1052 echo '<td>'.$this->sHouseNumber.'</td>';