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 /// List of word ids making up the address of the object.
21 private $aAddress = array();
22 /// Subset of word ids of full words making up the address.
23 private $aFullNameAddress = 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;
48 * Create an empty search description.
50 * @param object $oContext Global context to use. Will be inherited by
51 * all derived search objects.
53 public function __construct($oContext)
55 $this->oContext = $oContext;
59 * Get current search rank.
61 * The higher the search rank the lower the likelihood that the
62 * search is a correct interpretation of the search query.
64 * @return integer Search rank.
66 public function getRank()
68 return $this->iSearchRank;
72 * Make this search a POI search.
74 * In a POI search, objects are not (only) searched by their name
75 * but also by the primary OSM key/value pair (class and type in Nominatim).
77 * @param integer $iOperator Type of POI search
78 * @param string $sClass Class (or OSM tag key) of POI.
79 * @param string $sType Type (or OSM tag value) of POI.
83 public function setPoiSearch($iOperator, $sClass, $sType)
85 $this->iOperator = $iOperator;
86 $this->sClass = $sClass;
87 $this->sType = $sType;
91 * Check if this might be a full address search.
93 * @return bool True if the search contains name, address and housenumber.
95 public function looksLikeFullAddress()
97 return sizeof($this->aName)
98 && (sizeof($this->aAddress || $this->sCountryCode))
99 && preg_match('/[0-9]+/', $this->sHouseNumber);
103 * Check if any operator is set.
105 * @return bool True, if this is a special search operation.
107 public function hasOperator()
109 return $this->iOperator != Operator::NONE;
113 * Extract key/value pairs from a query.
115 * Key/value pairs are recognised if they are of the form [<key>=<value>].
116 * If multiple terms of this kind are found then all terms are removed
117 * but only the first is used for search.
119 * @param string $sQuery Original query string.
121 * @return string The query string with the special search patterns removed.
123 public function extractKeyValuePairs($sQuery)
125 // Search for terms of kind [<key>=<value>].
127 '/\\[([\\w_]*)=([\\w_]*)\\]/',
133 foreach ($aSpecialTermsRaw as $aTerm) {
134 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
135 if (!$this->hasOperator()) {
136 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
144 * Check if the combination of parameters is sensible.
146 * @return bool True, if the search looks valid.
148 public function isValidSearch()
150 if (!sizeof($this->aName)) {
151 if ($this->sHouseNumber) {
154 if (!$this->sClass && !$this->sCountryCode) {
162 /////////// Search building functions
166 * Derive new searches by adding a full term to the existing search.
168 * @param mixed[] $aSearchTerm Description of the token.
169 * @param bool $bHasPartial True if there are also tokens of partial terms
170 * with the same name.
171 * @param string $sPhraseType Type of phrase the token is contained in.
172 * @param bool $bFirstToken True if the token is at the beginning of the
174 * @param bool $bFirstPhrase True if the token is in the first phrase of
176 * @param bool $bLastToken True if the token is at the end of the query.
178 * @return SearchDescription[] List of derived search descriptions.
180 public function extendWithFullTerm($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
182 $aNewSearches = array();
184 if (($sPhraseType == '' || $sPhraseType == 'country')
185 && !empty($aSearchTerm['country_code'])
186 && $aSearchTerm['country_code'] != '0'
188 if (!$this->sCountryCode) {
189 $oSearch = clone $this;
190 $oSearch->iSearchRank++;
191 $oSearch->sCountryCode = $aSearchTerm['country_code'];
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 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
202 // We need to try the case where the postal code is the primary element
203 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
205 if (!$this->sPostcode
206 && $aSearchTerm['word']
207 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
209 // If we have structured search or this is the first term,
210 // make the postcode the primary search element.
211 if ($this->iOperator == Operator::NONE
212 && ($sPhraseType == 'postalcode' || $bFirstToken)
214 $oSearch = clone $this;
215 $oSearch->iSearchRank++;
216 $oSearch->iOperator = Operator::POSTCODE;
217 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
219 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
220 $aNewSearches[] = $oSearch;
223 // If we have a structured search or this is not the first term,
224 // add the postcode as an addendum.
225 if ($this->iOperator != Operator::POSTCODE
226 && ($sPhraseType == 'postalcode' || sizeof($this->aName))
228 $oSearch = clone $this;
229 $oSearch->iSearchRank++;
230 $oSearch->sPostcode = $aSearchTerm['word'];
231 $aNewSearches[] = $oSearch;
234 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
235 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
237 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
238 $oSearch = clone $this;
239 $oSearch->iSearchRank++;
240 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
241 // sanity check: if the housenumber is not mainly made
242 // up of numbers, add a penalty
243 if (preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
244 $oSearch->iSearchRank++;
246 if (!isset($aSearchTerm['word_id'])) {
247 $oSearch->iSearchRank++;
249 // also must not appear in the middle of the address
250 if (sizeof($this->aAddress)
251 || sizeof($this->aAddressNonSearch)
254 $oSearch->iSearchRank++;
256 $aNewSearches[] = $oSearch;
258 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
259 if ($this->iOperator == Operator::NONE) {
260 $oSearch = clone $this;
261 $oSearch->iSearchRank++;
263 $iOp = Operator::NEAR; // near == in for the moment
264 if ($aSearchTerm['operator'] == '') {
265 if (sizeof($this->aName) || $this->oContext->isBoundedSearch()) {
266 $iOp = Operator::NAME;
268 $oSearch->iSearchRank += 2;
271 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
272 $aNewSearches[] = $oSearch;
274 } elseif (isset($aSearchTerm['word_id'])
275 && $aSearchTerm['word_id']
276 && $sPhraseType != 'country'
278 $iWordID = $aSearchTerm['word_id'];
279 if (sizeof($this->aName)) {
280 if (($sPhraseType == '' || !$bFirstPhrase)
281 && $sPhraseType != 'country'
284 $oSearch = clone $this;
285 $oSearch->iSearchRank++;
286 $oSearch->aAddress[$iWordID] = $iWordID;
287 $aNewSearches[] = $oSearch;
289 $this->aFullNameAddress[$iWordID] = $iWordID;
292 // in structured search only the first phrase can be the
294 if ($sPhraseType == '' || $bFirstPhrase) {
295 $oSearch = clone $this;
296 $oSearch->iSearchRank++;
297 $oSearch->aName = array($iWordID => $iWordID);
298 $aNewSearches[] = $oSearch;
303 return $aNewSearches;
307 * Derive new searches by adding a partial term to the existing search.
309 * @param mixed[] $aSearchTerm Description of the token.
310 * @param bool $bStructuredPhrases True if the search is structured.
311 * @param integer $iPhrase Number of the phrase the token is in.
312 * @param array[] $aFullTokens List of full term tokens with the
315 * @return SearchDescription[] List of derived search descriptions.
317 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
319 // Only allow name terms.
320 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
324 $aNewSearches = array();
325 $iWordID = $aSearchTerm['word_id'];
327 if ((!$bStructuredPhrases || $iPhrase > 0)
328 && sizeof($this->aName)
329 && strpos($aSearchTerm['word_token'], ' ') === false
331 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
332 $oSearch = clone $this;
333 $oSearch->iSearchRank += 2;
334 $oSearch->aAddress[$iWordID] = $iWordID;
335 $aNewSearches[] = $oSearch;
337 $oSearch = clone $this;
338 $oSearch->iSearchRank++;
339 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
340 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
341 $oSearch->iSearchRank += 2;
343 if (sizeof($aFullTokens)) {
344 $oSearch->iSearchRank++;
346 $aNewSearches[] = $oSearch;
348 // revert to the token version?
349 foreach ($aFullTokens as $aSearchTermToken) {
350 if (empty($aSearchTermToken['country_code'])
351 && empty($aSearchTermToken['lat'])
352 && empty($aSearchTermToken['class'])
354 $oSearch = clone $this;
355 $oSearch->iSearchRank++;
356 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
357 $aNewSearches[] = $oSearch;
363 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
364 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
366 $oSearch = clone $this;
367 $oSearch->iSearchRank += 2;
368 if (!sizeof($this->aName)) {
369 $oSearch->iSearchRank += 1;
371 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
372 $oSearch->iSearchRank += 2;
374 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
375 $oSearch->aName[$iWordID] = $iWordID;
377 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
379 $oSearch->iNamePhrase = $iPhrase;
380 $aNewSearches[] = $oSearch;
383 return $aNewSearches;
386 /////////// Query functions
390 * Query database for places that match this search.
392 * @param object $oDB Database connection to use.
393 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
394 * overall in a planet database.
395 * @param integer $iMinRank Minimum address rank to restrict
397 * @param integer $iMaxRank Maximum address rank to restrict
399 * @param integer $iLimit Maximum number of results.
401 * @return mixed[] An array with two fields: IDs contains the list of
402 * matching place IDs and houseNumber the houseNumber
403 * if appicable or -1 if not.
405 public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
410 if ($this->sCountryCode
411 && !sizeof($this->aName)
414 && !$this->oContext->hasNearPoint()
416 // Just looking for a country - look it up
417 if (4 >= $iMinRank && 4 <= $iMaxRank) {
418 $aResults = $this->queryCountry($oDB);
420 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
421 // Neither name nor address? Then we must be
422 // looking for a POI in a geographic area.
423 if ($this->oContext->isBoundedSearch()) {
424 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
426 } elseif ($this->iOperator == Operator::POSTCODE) {
427 // looking for postcode
428 $aResults = $this->queryPostcode($oDB, $iLimit);
431 // First search for places according to name and address.
432 $aResults = $this->queryNamedPlace(
434 $aWordFrequencyScores,
440 //now search for housenumber, if housenumber provided
441 if ($this->sHouseNumber && sizeof($aResults)) {
442 $aNamedPlaceIDs = $aResults;
443 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
445 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
446 $aResults = $aNamedPlaceIDs;
450 // finally get POIs if requested
451 if ($this->sClass && sizeof($aResults)) {
452 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
457 echo '<br><b>Place IDs:</b> ';
458 var_dump(array_keys($aResults));
461 if (sizeof($aResults) && $this->sPostcode) {
462 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
464 $sSQL = 'SELECT place_id FROM placex';
465 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
466 $sSQL .= " AND postcode = '".$this->sPostcode."'";
467 if (CONST_Debug) var_dump($sSQL);
468 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
469 if ($aFilteredPlaceIDs) {
470 $aNewResults = array();
471 foreach ($aFilteredPlaceIDs as $iPlaceId) {
472 $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
474 $aResults = $aNewResults;
476 echo '<br><b>Place IDs after postcode filtering:</b> ';
477 var_dump(array_keys($aResults));
487 private function queryCountry(&$oDB)
489 $sSQL = 'SELECT place_id FROM placex ';
490 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
491 $sSQL .= ' AND rank_search = 4';
492 if ($this->oContext->bViewboxBounded) {
493 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
495 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
497 if (CONST_Debug) var_dump($sSQL);
500 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
501 $aResults[$iPlaceId] = new Result($iPlaceId);
507 private function queryNearbyPoi(&$oDB, $iLimit)
509 if (!$this->sClass) {
513 $aDBResults = array();
514 $sPoiTable = $this->poiTable();
516 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
517 if (chksql($oDB->getOne($sSQL))) {
518 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
519 if ($this->oContext->sqlCountryList) {
520 $sSQL .= ' JOIN placex USING (place_id)';
522 if ($this->oContext->hasNearPoint()) {
523 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
524 } elseif ($this->oContext->bViewboxBounded) {
525 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
527 if ($this->oContext->sqlCountryList) {
528 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
530 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
531 if ($this->oContext->sqlViewboxCentre) {
532 $sSQL .= ' ORDER BY ST_Distance(';
533 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
534 } elseif ($this->oContext->hasNearPoint()) {
535 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
537 $sSQL .= " limit $iLimit";
538 if (CONST_Debug) var_dump($sSQL);
539 $aDBResults = chksql($oDB->getCol($sSQL));
542 if ($this->oContext->hasNearPoint()) {
543 $sSQL = 'SELECT place_id FROM placex WHERE ';
544 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
545 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
546 $sSQL .= ' AND linked_place_id is null';
547 if ($this->oContext->sqlCountryList) {
548 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
550 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
551 $sSQL .= " LIMIT $iLimit";
552 if (CONST_Debug) var_dump($sSQL);
553 $aDBResults = chksql($oDB->getCol($sSQL));
557 foreach ($aDBResults as $iPlaceId) {
558 $aResults[$iPlaceId] = new Result($iPlaceId);
564 private function queryPostcode(&$oDB, $iLimit)
566 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
568 if (sizeof($this->aAddress)) {
569 $sSQL .= ', search_name s ';
570 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
571 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
572 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
577 $sSQL .= "p.postcode = '".reset($this->aName)."'";
578 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
579 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
580 $sSQL .= " LIMIT $iLimit";
582 if (CONST_Debug) var_dump($sSQL);
585 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
586 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
592 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
597 if ($this->sHouseNumber && sizeof($this->aAddress)) {
598 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
600 $aOrder[0] .= 'EXISTS(';
601 $aOrder[0] .= ' SELECT place_id';
602 $aOrder[0] .= ' FROM placex';
603 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
604 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
605 $aOrder[0] .= ' LIMIT 1';
607 // also housenumbers from interpolation lines table are needed
608 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
609 $iHouseNumber = intval($this->sHouseNumber);
610 $aOrder[0] .= 'OR EXISTS(';
611 $aOrder[0] .= ' SELECT place_id ';
612 $aOrder[0] .= ' FROM location_property_osmline ';
613 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
614 $aOrder[0] .= ' AND startnumber is not NULL';
615 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
616 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
617 $aOrder[0] .= ' LIMIT 1';
620 $aOrder[0] .= ') DESC';
623 if (sizeof($this->aName)) {
624 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
626 if (sizeof($this->aAddress)) {
627 // For infrequent name terms disable index usage for address
628 if (CONST_Search_NameOnlySearchFrequencyThreshold
629 && sizeof($this->aName) == 1
630 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
631 < CONST_Search_NameOnlySearchFrequencyThreshold
633 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
635 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
639 $sCountryTerm = $this->countryCodeSQL('country_code');
641 $aTerms[] = $sCountryTerm;
644 if ($this->sHouseNumber) {
645 $aTerms[] = 'address_rank between 16 and 27';
646 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
647 if ($iMinAddressRank > 0) {
648 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
650 if ($iMaxAddressRank < 30) {
651 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
655 if ($this->oContext->hasNearPoint()) {
656 $aTerms[] = $this->oContext->withinSQL('centroid');
657 $aOrder[] = $this->oContext->distanceSQL('centroid');
658 } elseif ($this->sPostcode) {
659 if (!sizeof($this->aAddress)) {
660 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
662 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
666 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
668 $aTerms[] = $sExcludeSQL;
671 if ($this->oContext->bViewboxBounded) {
672 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
675 if ($this->oContext->hasNearPoint()) {
676 $aOrder[] = $this->oContext->distanceSQL('centroid');
679 if ($this->sHouseNumber) {
680 $sImportanceSQL = '- abs(26 - address_rank) + 3';
682 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
684 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
685 $aOrder[] = "$sImportanceSQL DESC";
687 if (sizeof($this->aFullNameAddress)) {
688 $sExactMatchSQL = ' ( ';
689 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
690 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
691 $sExactMatchSQL .= ' INTERSECT ';
692 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
693 $sExactMatchSQL .= ' ) s';
694 $sExactMatchSQL .= ') as exactmatch';
695 $aOrder[] = 'exactmatch DESC';
697 $sExactMatchSQL = '0::int as exactmatch';
700 if ($this->sHouseNumber || $this->sClass) {
706 if (sizeof($aTerms)) {
707 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
708 $sSQL .= ' FROM search_name';
709 $sSQL .= ' WHERE '.join(' and ', $aTerms);
710 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
711 $sSQL .= ' LIMIT '.$iLimit;
713 if (CONST_Debug) var_dump($sSQL);
715 $aDBResults = chksql(
717 'Could not get places for search terms.'
720 foreach ($aDBResults as $aResult) {
721 $oResult = new Result($aResult['place_id']);
722 $oResult->iExactMatches = $aResult['exactmatch'];
723 $aResults[$aResult['place_id']] = $oResult;
730 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
733 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
739 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
740 $sSQL = 'SELECT place_id FROM placex ';
741 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
742 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
743 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
744 $sSQL .= " LIMIT $iLimit";
746 if (CONST_Debug) var_dump($sSQL);
748 // XXX should inherit the exactMatches from its parent
749 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
750 $aResults[$iPlaceId] = new Result($iPlaceId);
753 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
754 $iHousenumber = intval($this->sHouseNumber);
755 if ($bIsIntHouseNumber && !sizeof($aResults)) {
756 // if nothing found, search in the interpolation line table
757 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
758 $sSQL .= ' WHERE startnumber is not NULL';
759 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
760 if ($iHousenumber % 2 == 0) {
761 // If housenumber is even, look for housenumber in streets
762 // with interpolationtype even or all.
763 $sSQL .= "interpolationtype='even'";
765 // Else look for housenumber with interpolationtype odd or all.
766 $sSQL .= "interpolationtype='odd'";
768 $sSQL .= " or interpolationtype='all') and ";
769 $sSQL .= $iHousenumber.'>=startnumber and ';
770 $sSQL .= $iHousenumber.'<=endnumber';
771 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
772 $sSQL .= " limit $iLimit";
774 if (CONST_Debug) var_dump($sSQL);
776 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
777 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
778 $oResult->iHouseNumber = $iHousenumber;
779 $aResults[$iPlaceId] = $oResult;
783 // If nothing found try the aux fallback table
784 if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
785 $sSQL = 'SELECT place_id FROM location_property_aux';
786 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
787 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
788 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
789 $sSQL .= " limit $iLimit";
791 if (CONST_Debug) var_dump($sSQL);
793 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
794 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
798 // If nothing found then search in Tiger data (location_property_tiger)
799 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
800 $sSQL = 'SELECT place_id FROM location_property_tiger';
801 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
802 if ($iHousenumber % 2 == 0) {
803 $sSQL .= "interpolationtype='even'";
805 $sSQL .= "interpolationtype='odd'";
807 $sSQL .= " or interpolationtype='all') and ";
808 $sSQL .= $iHousenumber.'>=startnumber and ';
809 $sSQL .= $iHousenumber.'<=endnumber';
810 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
811 $sSQL .= " limit $iLimit";
813 if (CONST_Debug) var_dump($sSQL);
815 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
816 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
817 $oResult->iHouseNumber = $iHousenumber;
818 $aResults[$iPlaceId] = $oResult;
826 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
829 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
835 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
836 // If they were searching for a named class (i.e. 'Kings Head pub')
837 // then we might have an extra match
838 $sSQL = 'SELECT place_id FROM placex ';
839 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
840 $sSQL .= " AND class='".$this->sClass."' ";
841 $sSQL .= " AND type='".$this->sType."'";
842 $sSQL .= ' AND linked_place_id is null';
843 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
844 $sSQL .= ' ORDER BY rank_search ASC ';
845 $sSQL .= " LIMIT $iLimit";
847 if (CONST_Debug) var_dump($sSQL);
849 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
850 $aResults[$iPlaceId] = new Result($iPlaceId);
854 // NEAR and IN are handled the same
855 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
856 $sClassTable = $this->poiTable();
857 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
858 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
860 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
861 if (CONST_Debug) var_dump($sSQL);
862 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
864 // For state / country level searches the normal radius search doesn't work very well
866 if ($iMaxRank < 9 && $bCacheTable) {
867 // Try and get a polygon to search in instead
868 $sSQL = 'SELECT geometry FROM placex';
869 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
870 $sSQL .= " AND rank_search < $iMaxRank + 5";
871 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
872 $sSQL .= ' ORDER BY rank_search ASC ';
874 if (CONST_Debug) var_dump($sSQL);
875 $sPlaceGeom = chksql($oDB->getOne($sSQL));
882 $sSQL = 'SELECT place_id FROM placex';
883 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
884 if (CONST_Debug) var_dump($sSQL);
885 $aPlaceIDs = chksql($oDB->getCol($sSQL));
886 $sPlaceIDs = join(',', $aPlaceIDs);
889 if ($sPlaceIDs || $sPlaceGeom) {
892 // More efficient - can make the range bigger
896 if ($this->oContext->hasNearPoint()) {
897 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
898 } elseif ($sPlaceIDs) {
899 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
900 } elseif ($sPlaceGeom) {
901 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
904 $sSQL = 'SELECT distinct i.place_id';
906 $sSQL .= ', i.order_term';
908 $sSQL .= ' from (SELECT l.place_id';
910 $sSQL .= ','.$sOrderBySQL.' as order_term';
912 $sSQL .= ' from '.$sClassTable.' as l';
915 $sSQL .= ',placex as f WHERE ';
916 $sSQL .= "f.place_id in ($sPlaceIDs) ";
917 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
918 } elseif ($sPlaceGeom) {
919 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
922 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
923 $sSQL .= 'limit 300) i ';
925 $sSQL .= 'order by order_term asc';
927 $sSQL .= " limit $iLimit";
929 if (CONST_Debug) var_dump($sSQL);
931 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
932 $aResults[$iPlaceId] = new Result($iPlaceId);
935 if ($this->oContext->hasNearPoint()) {
936 $fRange = $this->oContext->nearRadius();
940 if ($this->oContext->hasNearPoint()) {
941 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
943 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
946 $sSQL = 'SELECT distinct l.place_id';
948 $sSQL .= ','.$sOrderBySQL.' as orderterm';
950 $sSQL .= ' FROM placex as l, placex as f';
951 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
952 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
953 $sSQL .= " AND l.class='".$this->sClass."'";
954 $sSQL .= " AND l.type='".$this->sType."'";
955 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
957 $sSQL .= 'ORDER BY orderterm ASC';
959 $sSQL .= " limit $iLimit";
961 if (CONST_Debug) var_dump($sSQL);
963 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
964 $aResults[$iPlaceId] = new Result($iPlaceId);
973 private function poiTable()
975 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
978 private function countryCodeSQL($sVar)
980 if ($this->sCountryCode) {
981 return $sVar.' = \''.$this->sCountryCode."'";
983 if ($this->oContext->sqlCountryList) {
984 return $sVar.' in '.$this->oContext->sqlCountryList;
990 /////////// Sort functions
993 public static function bySearchRank($a, $b)
995 if ($a->iSearchRank == $b->iSearchRank) {
996 return $a->iOperator + strlen($a->sHouseNumber)
997 - $b->iOperator - strlen($b->sHouseNumber);
1000 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1003 //////////// Debugging functions
1006 public function dumpAsHtmlTableRow(&$aWordIDs)
1008 $kf = function ($k) use (&$aWordIDs) {
1009 return $aWordIDs[$k];
1013 echo "<td>$this->iSearchRank</td>";
1014 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1015 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1016 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1017 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1018 echo '<td>'.$this->sCountryCode.'</td>';
1019 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1020 echo '<td>'.$this->sClass.'</td>';
1021 echo '<td>'.$this->sType.'</td>';
1022 echo '<td>'.$this->sPostcode.'</td>';
1023 echo '<td>'.$this->sHouseNumber.'</td>';