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 if ($this->sHouseNumber && !empty($this->aAddress)) {
597 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
599 $aOrder[0] .= 'EXISTS(';
600 $aOrder[0] .= ' SELECT place_id';
601 $aOrder[0] .= ' FROM placex';
602 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
603 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
604 $aOrder[0] .= ' LIMIT 1';
606 // also housenumbers from interpolation lines table are needed
607 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
608 $iHouseNumber = intval($this->sHouseNumber);
609 $aOrder[0] .= 'OR EXISTS(';
610 $aOrder[0] .= ' SELECT place_id ';
611 $aOrder[0] .= ' FROM location_property_osmline ';
612 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
613 $aOrder[0] .= ' AND startnumber is not NULL';
614 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
615 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
616 $aOrder[0] .= ' LIMIT 1';
619 $aOrder[0] .= ') DESC';
622 if (!empty($this->aName)) {
623 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
625 if (!empty($this->aAddress)) {
626 // For infrequent name terms disable index usage for address
627 if ($this->bRareName) {
628 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
630 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
634 $sCountryTerm = $this->countryCodeSQL('country_code');
636 $aTerms[] = $sCountryTerm;
639 if ($this->sHouseNumber) {
640 $aTerms[] = 'address_rank between 16 and 27';
641 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
642 if ($iMinAddressRank > 0) {
643 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
645 if ($iMaxAddressRank < 30) {
646 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
650 if ($this->oContext->hasNearPoint()) {
651 $aTerms[] = $this->oContext->withinSQL('centroid');
652 $aOrder[] = $this->oContext->distanceSQL('centroid');
653 } elseif ($this->sPostcode) {
654 if (empty($this->aAddress)) {
655 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
657 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
661 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
663 $aTerms[] = $sExcludeSQL;
666 if ($this->oContext->bViewboxBounded) {
667 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
670 if ($this->oContext->hasNearPoint()) {
671 $aOrder[] = $this->oContext->distanceSQL('centroid');
674 if ($this->sHouseNumber) {
675 $sImportanceSQL = '- abs(26 - address_rank) + 3';
677 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
679 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
680 $aOrder[] = "$sImportanceSQL DESC";
682 if (!empty($this->aFullNameAddress)) {
683 $sExactMatchSQL = ' ( ';
684 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
685 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
686 $sExactMatchSQL .= ' INTERSECT ';
687 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
688 $sExactMatchSQL .= ' ) s';
689 $sExactMatchSQL .= ') as exactmatch';
690 $aOrder[] = 'exactmatch DESC';
692 $sExactMatchSQL = '0::int as exactmatch';
695 if ($this->sHouseNumber || $this->sClass) {
701 if (!empty($aTerms)) {
702 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
703 $sSQL .= ' FROM search_name';
704 $sSQL .= ' WHERE '.join(' and ', $aTerms);
705 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
706 $sSQL .= ' LIMIT '.$iLimit;
708 Debug::printSQL($sSQL);
710 $aDBResults = chksql(
712 'Could not get places for search terms.'
715 foreach ($aDBResults as $aResult) {
716 $oResult = new Result($aResult['place_id']);
717 $oResult->iExactMatches = $aResult['exactmatch'];
718 $aResults[$aResult['place_id']] = $oResult;
725 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
728 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
734 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
735 $sSQL = 'SELECT place_id FROM placex ';
736 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
737 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
738 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
740 Debug::printSQL($sSQL);
742 // XXX should inherit the exactMatches from its parent
743 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
744 $aResults[$iPlaceId] = new Result($iPlaceId);
747 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
748 $iHousenumber = intval($this->sHouseNumber);
749 if ($bIsIntHouseNumber && empty($aResults)) {
750 // if nothing found, search in the interpolation line table
751 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
752 $sSQL .= ' WHERE startnumber is not NULL';
753 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
754 if ($iHousenumber % 2 == 0) {
755 // If housenumber is even, look for housenumber in streets
756 // with interpolationtype even or all.
757 $sSQL .= "interpolationtype='even'";
759 // Else look for housenumber with interpolationtype odd or all.
760 $sSQL .= "interpolationtype='odd'";
762 $sSQL .= " or interpolationtype='all') and ";
763 $sSQL .= $iHousenumber.'>=startnumber and ';
764 $sSQL .= $iHousenumber.'<=endnumber';
765 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
767 Debug::printSQL($sSQL);
769 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
770 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
771 $oResult->iHouseNumber = $iHousenumber;
772 $aResults[$iPlaceId] = $oResult;
776 // If nothing found try the aux fallback table
777 if (CONST_Use_Aux_Location_data && empty($aResults)) {
778 $sSQL = 'SELECT place_id FROM location_property_aux';
779 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
780 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
781 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
783 Debug::printSQL($sSQL);
785 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
786 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
790 // If nothing found then search in Tiger data (location_property_tiger)
791 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
792 $sSQL = 'SELECT place_id FROM location_property_tiger';
793 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
794 if ($iHousenumber % 2 == 0) {
795 $sSQL .= "interpolationtype='even'";
797 $sSQL .= "interpolationtype='odd'";
799 $sSQL .= " or interpolationtype='all') and ";
800 $sSQL .= $iHousenumber.'>=startnumber and ';
801 $sSQL .= $iHousenumber.'<=endnumber';
802 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
804 Debug::printSQL($sSQL);
806 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
807 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
808 $oResult->iHouseNumber = $iHousenumber;
809 $aResults[$iPlaceId] = $oResult;
817 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
820 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
826 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
827 // If they were searching for a named class (i.e. 'Kings Head pub')
828 // then we might have an extra match
829 $sSQL = 'SELECT place_id FROM placex ';
830 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
831 $sSQL .= " AND class='".$this->sClass."' ";
832 $sSQL .= " AND type='".$this->sType."'";
833 $sSQL .= ' AND linked_place_id is null';
834 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
835 $sSQL .= ' ORDER BY rank_search ASC ';
836 $sSQL .= " LIMIT $iLimit";
838 Debug::printSQL($sSQL);
840 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
841 $aResults[$iPlaceId] = new Result($iPlaceId);
845 // NEAR and IN are handled the same
846 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
847 $sClassTable = $this->poiTable();
848 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
849 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
851 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
852 Debug::printSQL($sSQL);
853 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
855 // For state / country level searches the normal radius search doesn't work very well
857 if ($iMaxRank < 9 && $bCacheTable) {
858 // Try and get a polygon to search in instead
859 $sSQL = 'SELECT geometry FROM placex';
860 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
861 $sSQL .= " AND rank_search < $iMaxRank + 5";
862 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
863 $sSQL .= ' ORDER BY rank_search ASC ';
865 Debug::printSQL($sSQL);
866 $sPlaceGeom = chksql($oDB->getOne($sSQL));
873 $sSQL = 'SELECT place_id FROM placex';
874 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
875 Debug::printSQL($sSQL);
876 $aPlaceIDs = chksql($oDB->getCol($sSQL));
877 $sPlaceIDs = join(',', $aPlaceIDs);
880 if ($sPlaceIDs || $sPlaceGeom) {
883 // More efficient - can make the range bigger
887 if ($this->oContext->hasNearPoint()) {
888 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
889 } elseif ($sPlaceIDs) {
890 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
891 } elseif ($sPlaceGeom) {
892 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
895 $sSQL = 'SELECT distinct i.place_id';
897 $sSQL .= ', i.order_term';
899 $sSQL .= ' from (SELECT l.place_id';
901 $sSQL .= ','.$sOrderBySQL.' as order_term';
903 $sSQL .= ' from '.$sClassTable.' as l';
906 $sSQL .= ',placex as f WHERE ';
907 $sSQL .= "f.place_id in ($sPlaceIDs) ";
908 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
909 } elseif ($sPlaceGeom) {
910 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
913 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
914 $sSQL .= 'limit 300) i ';
916 $sSQL .= 'order by order_term asc';
918 $sSQL .= " limit $iLimit";
920 Debug::printSQL($sSQL);
922 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
923 $aResults[$iPlaceId] = new Result($iPlaceId);
926 if ($this->oContext->hasNearPoint()) {
927 $fRange = $this->oContext->nearRadius();
931 if ($this->oContext->hasNearPoint()) {
932 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
934 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
937 $sSQL = 'SELECT distinct l.place_id';
939 $sSQL .= ','.$sOrderBySQL.' as orderterm';
941 $sSQL .= ' FROM placex as l, placex as f';
942 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
943 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
944 $sSQL .= " AND l.class='".$this->sClass."'";
945 $sSQL .= " AND l.type='".$this->sType."'";
946 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
948 $sSQL .= 'ORDER BY orderterm ASC';
950 $sSQL .= " limit $iLimit";
952 Debug::printSQL($sSQL);
954 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
955 $aResults[$iPlaceId] = new Result($iPlaceId);
964 private function poiTable()
966 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
969 private function countryCodeSQL($sVar)
971 if ($this->sCountryCode) {
972 return $sVar.' = \''.$this->sCountryCode."'";
974 if ($this->oContext->sqlCountryList) {
975 return $sVar.' in '.$this->oContext->sqlCountryList;
981 /////////// Sort functions
984 public static function bySearchRank($a, $b)
986 if ($a->iSearchRank == $b->iSearchRank) {
987 return $a->iOperator + strlen($a->sHouseNumber)
988 - $b->iOperator - strlen($b->sHouseNumber);
991 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
994 //////////// Debugging functions
997 public function debugInfo()
1000 'Search rank' => $this->iSearchRank,
1001 'Country code' => $this->sCountryCode,
1002 'Name terms' => $this->aName,
1003 'Name terms (stop words)' => $this->aNameNonSearch,
1004 'Address terms' => $this->aAddress,
1005 'Address terms (stop words)' => $this->aAddressNonSearch,
1006 'Address terms (full words)' => $this->aFullNameAddress,
1007 'Special search' => $this->iOperator,
1008 'Class' => $this->sClass,
1009 'Type' => $this->sType,
1010 'House number' => $this->sHouseNumber,
1011 'Postcode' => $this->sPostcode
1015 public function dumpAsHtmlTableRow(&$aWordIDs)
1017 $kf = function ($k) use (&$aWordIDs) {
1018 return $aWordIDs[$k];
1022 echo "<td>$this->iSearchRank</td>";
1023 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1024 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1025 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1026 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1027 echo '<td>'.$this->sCountryCode.'</td>';
1028 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1029 echo '<td>'.$this->sClass.'</td>';
1030 echo '<td>'.$this->sType.'</td>';
1031 echo '<td>'.$this->sPostcode.'</td>';
1032 echo '<td>'.$this->sHouseNumber.'</td>';