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 mixed[] $aSearchTerm 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($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
183 $aNewSearches = array();
185 if (($sPhraseType == '' || $sPhraseType == 'country')
186 && !empty($aSearchTerm['country_code'])
187 && $aSearchTerm['country_code'] != '0'
189 if (!$this->sCountryCode) {
190 $oSearch = clone $this;
191 $oSearch->iSearchRank++;
192 $oSearch->sCountryCode = $aSearchTerm['country_code'];
193 // Country is almost always at the end of the string
194 // - increase score for finding it anywhere else (optimisation)
196 $oSearch->iSearchRank += 5;
198 $aNewSearches[] = $oSearch;
200 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
201 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
203 // We need to try the case where the postal code is the primary element
204 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
206 if (!$this->sPostcode
207 && $aSearchTerm['word']
208 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
210 // If we have structured search or this is the first term,
211 // make the postcode the primary search element.
212 if ($this->iOperator == Operator::NONE
213 && ($sPhraseType == 'postalcode' || $bFirstToken)
215 $oSearch = clone $this;
216 $oSearch->iSearchRank++;
217 $oSearch->iOperator = Operator::POSTCODE;
218 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
220 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
221 $aNewSearches[] = $oSearch;
224 // If we have a structured search or this is not the first term,
225 // add the postcode as an addendum.
226 if ($this->iOperator != Operator::POSTCODE
227 && ($sPhraseType == 'postalcode' || !empty($this->aName))
229 $oSearch = clone $this;
230 $oSearch->iSearchRank++;
231 $oSearch->sPostcode = $aSearchTerm['word'];
232 $aNewSearches[] = $oSearch;
235 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
236 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
238 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
239 $oSearch = clone $this;
240 $oSearch->iSearchRank++;
241 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
242 // sanity check: if the housenumber is not mainly made
243 // up of numbers, add a penalty
244 if (preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
245 $oSearch->iSearchRank++;
247 if (!isset($aSearchTerm['word_id'])) {
248 $oSearch->iSearchRank++;
250 // also must not appear in the middle of the address
251 if (!empty($this->aAddress)
252 || (!empty($this->aAddressNonSearch))
255 $oSearch->iSearchRank++;
257 $aNewSearches[] = $oSearch;
259 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
260 if ($this->iOperator == Operator::NONE) {
261 $oSearch = clone $this;
262 $oSearch->iSearchRank++;
264 $iOp = Operator::NEAR; // near == in for the moment
265 if ($aSearchTerm['operator'] == '') {
266 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
267 $iOp = Operator::NAME;
269 $oSearch->iSearchRank += 2;
272 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
273 $aNewSearches[] = $oSearch;
275 } elseif (isset($aSearchTerm['word_id'])
276 && $aSearchTerm['word_id']
277 && $sPhraseType != 'country'
279 $iWordID = $aSearchTerm['word_id'];
280 // Full words can only be a name if they appear at the beginning
281 // of the phrase. In structured search the name must forcably in
282 // the first phrase. In unstructured search it may be in a later
283 // phrase when the first phrase is a house number.
284 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
285 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
286 $oSearch = clone $this;
287 $oSearch->iSearchRank++;
288 $oSearch->aAddress[$iWordID] = $iWordID;
289 $aNewSearches[] = $oSearch;
291 $this->aFullNameAddress[$iWordID] = $iWordID;
294 $oSearch = clone $this;
295 $oSearch->iSearchRank++;
296 $oSearch->aName = array($iWordID => $iWordID);
297 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
298 $oSearch->bRareName =
299 $aSearchTerm['search_name_count'] + 1
300 < CONST_Search_NameOnlySearchFrequencyThreshold;
302 $aNewSearches[] = $oSearch;
306 return $aNewSearches;
310 * Derive new searches by adding a partial term to the existing search.
312 * @param mixed[] $aSearchTerm Description of the token.
313 * @param bool $bStructuredPhrases True if the search is structured.
314 * @param integer $iPhrase Number of the phrase the token is in.
315 * @param array[] $aFullTokens List of full term tokens with the
318 * @return SearchDescription[] List of derived search descriptions.
320 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
322 // Only allow name terms.
323 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
327 $aNewSearches = array();
328 $iWordID = $aSearchTerm['word_id'];
330 if ((!$bStructuredPhrases || $iPhrase > 0)
331 && (!empty($this->aName))
332 && strpos($aSearchTerm['word_token'], ' ') === false
334 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
335 $oSearch = clone $this;
336 $oSearch->iSearchRank += 2;
337 $oSearch->aAddress[$iWordID] = $iWordID;
338 $aNewSearches[] = $oSearch;
340 $oSearch = clone $this;
341 $oSearch->iSearchRank++;
342 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
343 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
344 $oSearch->iSearchRank += 2;
346 if (!empty($aFullTokens)) {
347 $oSearch->iSearchRank++;
349 $aNewSearches[] = $oSearch;
351 // revert to the token version?
352 foreach ($aFullTokens as $aSearchTermToken) {
353 if (empty($aSearchTermToken['country_code'])
354 && empty($aSearchTermToken['lat'])
355 && empty($aSearchTermToken['class'])
357 $oSearch = clone $this;
358 $oSearch->iSearchRank++;
359 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
360 $aNewSearches[] = $oSearch;
366 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
367 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
369 $oSearch = clone $this;
370 $oSearch->iSearchRank += 2;
371 if (empty($this->aName)) {
372 $oSearch->iSearchRank += 1;
374 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
375 $oSearch->iSearchRank += 2;
377 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
378 if (empty($this->aName) && CONST_Search_NameOnlySearchFrequencyThreshold) {
379 $oSearch->bRareName =
380 $aSearchTerm['search_name_count'] + 1
381 < CONST_Search_NameOnlySearchFrequencyThreshold;
383 $oSearch->bRareName = false;
385 $oSearch->aName[$iWordID] = $iWordID;
387 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
389 $oSearch->iNamePhrase = $iPhrase;
390 $aNewSearches[] = $oSearch;
393 return $aNewSearches;
396 /////////// Query functions
400 * Query database for places that match this search.
402 * @param object $oDB Database connection to use.
403 * @param integer $iMinRank Minimum address rank to restrict search to.
404 * @param integer $iMaxRank Maximum address rank to restrict search to.
405 * @param integer $iLimit Maximum number of results.
407 * @return mixed[] An array with two fields: IDs contains the list of
408 * matching place IDs and houseNumber the houseNumber
409 * if appicable or -1 if not.
411 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
416 if ($this->sCountryCode
417 && empty($this->aName)
420 && !$this->oContext->hasNearPoint()
422 // Just looking for a country - look it up
423 if (4 >= $iMinRank && 4 <= $iMaxRank) {
424 $aResults = $this->queryCountry($oDB);
426 } elseif (empty($this->aName) && empty($this->aAddress)) {
427 // Neither name nor address? Then we must be
428 // looking for a POI in a geographic area.
429 if ($this->oContext->isBoundedSearch()) {
430 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
432 } elseif ($this->iOperator == Operator::POSTCODE) {
433 // looking for postcode
434 $aResults = $this->queryPostcode($oDB, $iLimit);
437 // First search for places according to name and address.
438 $aResults = $this->queryNamedPlace(
445 //now search for housenumber, if housenumber provided
446 if ($this->sHouseNumber && !empty($aResults)) {
447 $aNamedPlaceIDs = $aResults;
448 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs);
450 if (empty($aResults) && $this->looksLikeFullAddress()) {
451 $aResults = $aNamedPlaceIDs;
455 // finally get POIs if requested
456 if ($this->sClass && !empty($aResults)) {
457 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
461 Debug::printDebugTable('Place IDs', $aResults);
463 if (!empty($aResults) && $this->sPostcode) {
464 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
466 $sSQL = 'SELECT place_id FROM placex';
467 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
468 $sSQL .= " AND postcode = '".$this->sPostcode."'";
469 Debug::printSQL($sSQL);
470 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
471 if ($aFilteredPlaceIDs) {
472 $aNewResults = array();
473 foreach ($aFilteredPlaceIDs as $iPlaceId) {
474 $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
476 $aResults = $aNewResults;
477 Debug::printVar('Place IDs after postcode filtering', $aResults);
486 private function queryCountry(&$oDB)
488 $sSQL = 'SELECT place_id FROM placex ';
489 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
490 $sSQL .= ' AND rank_search = 4';
491 if ($this->oContext->bViewboxBounded) {
492 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
494 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
496 Debug::printSQL($sSQL);
499 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
500 $aResults[$iPlaceId] = new Result($iPlaceId);
506 private function queryNearbyPoi(&$oDB, $iLimit)
508 if (!$this->sClass) {
512 $aDBResults = array();
513 $sPoiTable = $this->poiTable();
515 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
516 if (chksql($oDB->getOne($sSQL))) {
517 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
518 if ($this->oContext->sqlCountryList) {
519 $sSQL .= ' JOIN placex USING (place_id)';
521 if ($this->oContext->hasNearPoint()) {
522 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
523 } elseif ($this->oContext->bViewboxBounded) {
524 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
526 if ($this->oContext->sqlCountryList) {
527 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
529 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
530 if ($this->oContext->sqlViewboxCentre) {
531 $sSQL .= ' ORDER BY ST_Distance(';
532 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
533 } elseif ($this->oContext->hasNearPoint()) {
534 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
536 $sSQL .= " limit $iLimit";
537 Debug::printSQL($sSQL);
538 $aDBResults = chksql($oDB->getCol($sSQL));
541 if ($this->oContext->hasNearPoint()) {
542 $sSQL = 'SELECT place_id FROM placex WHERE ';
543 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
544 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
545 $sSQL .= ' AND linked_place_id is null';
546 if ($this->oContext->sqlCountryList) {
547 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
549 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
550 $sSQL .= " LIMIT $iLimit";
551 Debug::printSQL($sSQL);
552 $aDBResults = chksql($oDB->getCol($sSQL));
556 foreach ($aDBResults as $iPlaceId) {
557 $aResults[$iPlaceId] = new Result($iPlaceId);
563 private function queryPostcode(&$oDB, $iLimit)
565 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
567 if (!empty($this->aAddress)) {
568 $sSQL .= ', search_name s ';
569 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
570 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
571 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
576 $sSQL .= "p.postcode = '".reset($this->aName)."'";
577 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
578 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
579 $sSQL .= " LIMIT $iLimit";
581 Debug::printSQL($sSQL);
584 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
585 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
591 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
596 // Sort by existence of the requested house number but only if not
597 // too many results are expected for the street, i.e. if the result
598 // will be narrowed down by an address. Remeber that with ordering
599 // every single result has to be checked.
600 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
601 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
603 $aOrder[0] .= 'EXISTS(';
604 $aOrder[0] .= ' SELECT place_id';
605 $aOrder[0] .= ' FROM placex';
606 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
607 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
608 $aOrder[0] .= ' LIMIT 1';
610 // also housenumbers from interpolation lines table are needed
611 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
612 $iHouseNumber = intval($this->sHouseNumber);
613 $aOrder[0] .= 'OR EXISTS(';
614 $aOrder[0] .= ' SELECT place_id ';
615 $aOrder[0] .= ' FROM location_property_osmline ';
616 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
617 $aOrder[0] .= ' AND startnumber is not NULL';
618 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
619 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
620 $aOrder[0] .= ' LIMIT 1';
623 $aOrder[0] .= ') DESC';
626 if (!empty($this->aName)) {
627 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
629 if (!empty($this->aAddress)) {
630 // For infrequent name terms disable index usage for address
631 if ($this->bRareName) {
632 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
634 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
638 $sCountryTerm = $this->countryCodeSQL('country_code');
640 $aTerms[] = $sCountryTerm;
643 if ($this->sHouseNumber) {
644 $aTerms[] = 'address_rank between 16 and 27';
645 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
646 if ($iMinAddressRank > 0) {
647 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
649 if ($iMaxAddressRank < 30) {
650 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
654 if ($this->oContext->hasNearPoint()) {
655 $aTerms[] = $this->oContext->withinSQL('centroid');
656 $aOrder[] = $this->oContext->distanceSQL('centroid');
657 } elseif ($this->sPostcode) {
658 if (empty($this->aAddress)) {
659 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
661 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
665 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
667 $aTerms[] = $sExcludeSQL;
670 if ($this->oContext->bViewboxBounded) {
671 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
674 if ($this->oContext->hasNearPoint()) {
675 $aOrder[] = $this->oContext->distanceSQL('centroid');
678 if ($this->sHouseNumber) {
679 $sImportanceSQL = '- abs(26 - address_rank) + 3';
681 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
683 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
684 $aOrder[] = "$sImportanceSQL DESC";
686 if (!empty($this->aFullNameAddress)) {
687 $sExactMatchSQL = ' ( ';
688 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
689 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
690 $sExactMatchSQL .= ' INTERSECT ';
691 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
692 $sExactMatchSQL .= ' ) s';
693 $sExactMatchSQL .= ') as exactmatch';
694 $aOrder[] = 'exactmatch DESC';
696 $sExactMatchSQL = '0::int as exactmatch';
699 if ($this->sHouseNumber || $this->sClass) {
705 if (!empty($aTerms)) {
706 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
707 $sSQL .= ' FROM search_name';
708 $sSQL .= ' WHERE '.join(' and ', $aTerms);
709 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
710 $sSQL .= ' LIMIT '.$iLimit;
712 Debug::printSQL($sSQL);
714 $aDBResults = chksql(
716 'Could not get places for search terms.'
719 foreach ($aDBResults as $aResult) {
720 $oResult = new Result($aResult['place_id']);
721 $oResult->iExactMatches = $aResult['exactmatch'];
722 $aResults[$aResult['place_id']] = $oResult;
729 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
732 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
738 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
739 $sSQL = 'SELECT place_id FROM placex ';
740 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
741 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
742 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
744 Debug::printSQL($sSQL);
746 // XXX should inherit the exactMatches from its parent
747 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
748 $aResults[$iPlaceId] = new Result($iPlaceId);
751 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
752 $iHousenumber = intval($this->sHouseNumber);
753 if ($bIsIntHouseNumber && empty($aResults)) {
754 // if nothing found, search in the interpolation line table
755 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
756 $sSQL .= ' WHERE startnumber is not NULL';
757 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
758 if ($iHousenumber % 2 == 0) {
759 // If housenumber is even, look for housenumber in streets
760 // with interpolationtype even or all.
761 $sSQL .= "interpolationtype='even'";
763 // Else look for housenumber with interpolationtype odd or all.
764 $sSQL .= "interpolationtype='odd'";
766 $sSQL .= " or interpolationtype='all') and ";
767 $sSQL .= $iHousenumber.'>=startnumber and ';
768 $sSQL .= $iHousenumber.'<=endnumber';
769 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
771 Debug::printSQL($sSQL);
773 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
774 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
775 $oResult->iHouseNumber = $iHousenumber;
776 $aResults[$iPlaceId] = $oResult;
780 // If nothing found try the aux fallback table
781 if (CONST_Use_Aux_Location_data && empty($aResults)) {
782 $sSQL = 'SELECT place_id FROM location_property_aux';
783 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
784 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
785 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
787 Debug::printSQL($sSQL);
789 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
790 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
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 (chksql($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 (chksql($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 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
853 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
855 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
856 Debug::printSQL($sSQL);
857 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
859 // For state / country level searches the normal radius search doesn't work very well
861 if ($iMaxRank < 9 && $bCacheTable) {
862 // Try and get a polygon to search in instead
863 $sSQL = 'SELECT geometry FROM placex';
864 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
865 $sSQL .= " AND rank_search < $iMaxRank + 5";
866 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
867 $sSQL .= ' ORDER BY rank_search ASC ';
869 Debug::printSQL($sSQL);
870 $sPlaceGeom = chksql($oDB->getOne($sSQL));
877 $sSQL = 'SELECT place_id FROM placex';
878 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
879 Debug::printSQL($sSQL);
880 $aPlaceIDs = chksql($oDB->getCol($sSQL));
881 $sPlaceIDs = join(',', $aPlaceIDs);
884 if ($sPlaceIDs || $sPlaceGeom) {
887 // More efficient - can make the range bigger
891 if ($this->oContext->hasNearPoint()) {
892 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
893 } elseif ($sPlaceIDs) {
894 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
895 } elseif ($sPlaceGeom) {
896 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
899 $sSQL = 'SELECT distinct i.place_id';
901 $sSQL .= ', i.order_term';
903 $sSQL .= ' from (SELECT l.place_id';
905 $sSQL .= ','.$sOrderBySQL.' as order_term';
907 $sSQL .= ' from '.$sClassTable.' as l';
910 $sSQL .= ',placex as f WHERE ';
911 $sSQL .= "f.place_id in ($sPlaceIDs) ";
912 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
913 } elseif ($sPlaceGeom) {
914 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
917 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
918 $sSQL .= 'limit 300) i ';
920 $sSQL .= 'order by order_term asc';
922 $sSQL .= " limit $iLimit";
924 Debug::printSQL($sSQL);
926 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
927 $aResults[$iPlaceId] = new Result($iPlaceId);
930 if ($this->oContext->hasNearPoint()) {
931 $fRange = $this->oContext->nearRadius();
935 if ($this->oContext->hasNearPoint()) {
936 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
938 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
941 $sSQL = 'SELECT distinct l.place_id';
943 $sSQL .= ','.$sOrderBySQL.' as orderterm';
945 $sSQL .= ' FROM placex as l, placex as f';
946 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
947 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
948 $sSQL .= " AND l.class='".$this->sClass."'";
949 $sSQL .= " AND l.type='".$this->sType."'";
950 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
952 $sSQL .= 'ORDER BY orderterm ASC';
954 $sSQL .= " limit $iLimit";
956 Debug::printSQL($sSQL);
958 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
959 $aResults[$iPlaceId] = new Result($iPlaceId);
968 private function poiTable()
970 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
973 private function countryCodeSQL($sVar)
975 if ($this->sCountryCode) {
976 return $sVar.' = \''.$this->sCountryCode."'";
978 if ($this->oContext->sqlCountryList) {
979 return $sVar.' in '.$this->oContext->sqlCountryList;
985 /////////// Sort functions
988 public static function bySearchRank($a, $b)
990 if ($a->iSearchRank == $b->iSearchRank) {
991 return $a->iOperator + strlen($a->sHouseNumber)
992 - $b->iOperator - strlen($b->sHouseNumber);
995 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
998 //////////// Debugging functions
1001 public function debugInfo()
1004 'Search rank' => $this->iSearchRank,
1005 'Country code' => $this->sCountryCode,
1006 'Name terms' => $this->aName,
1007 'Name terms (stop words)' => $this->aNameNonSearch,
1008 'Address terms' => $this->aAddress,
1009 'Address terms (stop words)' => $this->aAddressNonSearch,
1010 'Address terms (full words)' => $this->aFullNameAddress,
1011 'Special search' => $this->iOperator,
1012 'Class' => $this->sClass,
1013 'Type' => $this->sType,
1014 'House number' => $this->sHouseNumber,
1015 'Postcode' => $this->sPostcode
1019 public function dumpAsHtmlTableRow(&$aWordIDs)
1021 $kf = function ($k) use (&$aWordIDs) {
1022 return $aWordIDs[$k];
1026 echo "<td>$this->iSearchRank</td>";
1027 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1028 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1029 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1030 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1031 echo '<td>'.$this->sCountryCode.'</td>';
1032 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1033 echo '<td>'.$this->sClass.'</td>';
1034 echo '<td>'.$this->sType.'</td>';
1035 echo '<td>'.$this->sPostcode.'</td>';
1036 echo '<td>'.$this->sHouseNumber.'</td>';