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;
47 * Create an empty search description.
49 * @param object $oContext Global context to use. Will be inherited by
50 * all derived search objects.
52 public function __construct($oContext)
54 $this->oContext = $oContext;
58 * Get current search rank.
60 * The higher the search rank the lower the likelihood that the
61 * search is a correct interpretation of the search query.
63 * @return integer Search rank.
65 public function getRank()
67 return $this->iSearchRank;
71 * Make this search a POI search.
73 * In a POI search, objects are not (only) searched by their name
74 * but also by the primary OSM key/value pair (class and type in Nominatim).
76 * @param integer $iOperator Type of POI search
77 * @param string $sClass Class (or OSM tag key) of POI.
78 * @param string $sType Type (or OSM tag value) of POI.
82 public function setPoiSearch($iOperator, $sClass, $sType)
84 $this->iOperator = $iOperator;
85 $this->sClass = $sClass;
86 $this->sType = $sType;
90 * Check if this might be a full address search.
92 * @return bool True if the search contains name, address and housenumber.
94 public function looksLikeFullAddress()
96 return (!empty($this->aName))
97 && (!empty($this->aAddress) || $this->sCountryCode)
98 && preg_match('/[0-9]+/', $this->sHouseNumber);
102 * Check if any operator is set.
104 * @return bool True, if this is a special search operation.
106 public function hasOperator()
108 return $this->iOperator != Operator::NONE;
112 * Extract key/value pairs from a query.
114 * Key/value pairs are recognised if they are of the form [<key>=<value>].
115 * If multiple terms of this kind are found then all terms are removed
116 * but only the first is used for search.
118 * @param string $sQuery Original query string.
120 * @return string The query string with the special search patterns removed.
122 public function extractKeyValuePairs($sQuery)
124 // Search for terms of kind [<key>=<value>].
126 '/\\[([\\w_]*)=([\\w_]*)\\]/',
132 foreach ($aSpecialTermsRaw as $aTerm) {
133 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
134 if (!$this->hasOperator()) {
135 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
143 * Check if the combination of parameters is sensible.
145 * @return bool True, if the search looks valid.
147 public function isValidSearch()
149 if (empty($this->aName)) {
150 if ($this->sHouseNumber) {
153 if (!$this->sClass && !$this->sCountryCode) {
161 /////////// Search building functions
165 * Derive new searches by adding a full term to the existing search.
167 * @param mixed[] $aSearchTerm Description of the token.
168 * @param bool $bHasPartial True if there are also tokens of partial terms
169 * with the same name.
170 * @param string $sPhraseType Type of phrase the token is contained in.
171 * @param bool $bFirstToken True if the token is at the beginning of the
173 * @param bool $bFirstPhrase True if the token is in the first phrase of
175 * @param bool $bLastToken True if the token is at the end of the query.
177 * @return SearchDescription[] List of derived search descriptions.
179 public function extendWithFullTerm($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
181 $aNewSearches = array();
183 if (($sPhraseType == '' || $sPhraseType == 'country')
184 && !empty($aSearchTerm['country_code'])
185 && $aSearchTerm['country_code'] != '0'
187 if (!$this->sCountryCode) {
188 $oSearch = clone $this;
189 $oSearch->iSearchRank++;
190 $oSearch->sCountryCode = $aSearchTerm['country_code'];
191 // Country is almost always at the end of the string
192 // - increase score for finding it anywhere else (optimisation)
194 $oSearch->iSearchRank += 5;
196 $aNewSearches[] = $oSearch;
198 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
199 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
201 // We need to try the case where the postal code is the primary element
202 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
204 if (!$this->sPostcode
205 && $aSearchTerm['word']
206 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
208 // If we have structured search or this is the first term,
209 // make the postcode the primary search element.
210 if ($this->iOperator == Operator::NONE
211 && ($sPhraseType == 'postalcode' || $bFirstToken)
213 $oSearch = clone $this;
214 $oSearch->iSearchRank++;
215 $oSearch->iOperator = Operator::POSTCODE;
216 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
218 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
219 $aNewSearches[] = $oSearch;
222 // If we have a structured search or this is not the first term,
223 // add the postcode as an addendum.
224 if ($this->iOperator != Operator::POSTCODE
225 && ($sPhraseType == 'postalcode' || !empty($this->aName))
227 $oSearch = clone $this;
228 $oSearch->iSearchRank++;
229 $oSearch->sPostcode = $aSearchTerm['word'];
230 $aNewSearches[] = $oSearch;
233 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
234 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
236 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
237 $oSearch = clone $this;
238 $oSearch->iSearchRank++;
239 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
240 // sanity check: if the housenumber is not mainly made
241 // up of numbers, add a penalty
242 if (preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
243 $oSearch->iSearchRank++;
245 if (!isset($aSearchTerm['word_id'])) {
246 $oSearch->iSearchRank++;
248 // also must not appear in the middle of the address
249 if (!empty($this->aAddress)
250 || (!empty($this->aAddressNonSearch))
253 $oSearch->iSearchRank++;
255 $aNewSearches[] = $oSearch;
257 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
258 if ($this->iOperator == Operator::NONE) {
259 $oSearch = clone $this;
260 $oSearch->iSearchRank++;
262 $iOp = Operator::NEAR; // near == in for the moment
263 if ($aSearchTerm['operator'] == '') {
264 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
265 $iOp = Operator::NAME;
267 $oSearch->iSearchRank += 2;
270 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
271 $aNewSearches[] = $oSearch;
273 } elseif (isset($aSearchTerm['word_id'])
274 && $aSearchTerm['word_id']
275 && $sPhraseType != 'country'
277 $iWordID = $aSearchTerm['word_id'];
278 // Full words can only be a name if they appear at the beginning
279 // of the phrase. In structured search the name must forcably in
280 // the first phrase. In unstructured search it may be in a later
281 // phrase when the first phrase is a house number.
282 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
283 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
284 $oSearch = clone $this;
285 $oSearch->iSearchRank++;
286 $oSearch->aAddress[$iWordID] = $iWordID;
287 $aNewSearches[] = $oSearch;
289 $this->aFullNameAddress[$iWordID] = $iWordID;
292 $oSearch = clone $this;
293 $oSearch->iSearchRank++;
294 $oSearch->aName = array($iWordID => $iWordID);
295 $aNewSearches[] = $oSearch;
299 return $aNewSearches;
303 * Derive new searches by adding a partial term to the existing search.
305 * @param mixed[] $aSearchTerm Description of the token.
306 * @param bool $bStructuredPhrases True if the search is structured.
307 * @param integer $iPhrase Number of the phrase the token is in.
308 * @param array[] $aFullTokens List of full term tokens with the
311 * @return SearchDescription[] List of derived search descriptions.
313 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
315 // Only allow name terms.
316 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
320 $aNewSearches = array();
321 $iWordID = $aSearchTerm['word_id'];
323 if ((!$bStructuredPhrases || $iPhrase > 0)
324 && (!empty($this->aName))
325 && strpos($aSearchTerm['word_token'], ' ') === false
327 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
328 $oSearch = clone $this;
329 $oSearch->iSearchRank += 2;
330 $oSearch->aAddress[$iWordID] = $iWordID;
331 $aNewSearches[] = $oSearch;
333 $oSearch = clone $this;
334 $oSearch->iSearchRank++;
335 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
336 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
337 $oSearch->iSearchRank += 2;
339 if (!empty($aFullTokens)) {
340 $oSearch->iSearchRank++;
342 $aNewSearches[] = $oSearch;
344 // revert to the token version?
345 foreach ($aFullTokens as $aSearchTermToken) {
346 if (empty($aSearchTermToken['country_code'])
347 && empty($aSearchTermToken['lat'])
348 && empty($aSearchTermToken['class'])
350 $oSearch = clone $this;
351 $oSearch->iSearchRank++;
352 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
353 $aNewSearches[] = $oSearch;
359 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
360 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
362 $oSearch = clone $this;
363 $oSearch->iSearchRank += 2;
364 if (empty($this->aName)) {
365 $oSearch->iSearchRank += 1;
367 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
368 $oSearch->iSearchRank += 2;
370 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
371 $oSearch->aName[$iWordID] = $iWordID;
373 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
375 $oSearch->iNamePhrase = $iPhrase;
376 $aNewSearches[] = $oSearch;
379 return $aNewSearches;
382 /////////// Query functions
386 * Query database for places that match this search.
388 * @param object $oDB Database connection to use.
389 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
390 * overall in a planet database.
391 * @param integer $iMinRank Minimum address rank to restrict
393 * @param integer $iMaxRank Maximum address rank to restrict
395 * @param integer $iLimit Maximum number of results.
397 * @return mixed[] An array with two fields: IDs contains the list of
398 * matching place IDs and houseNumber the houseNumber
399 * if appicable or -1 if not.
401 public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
406 if ($this->sCountryCode
407 && empty($this->aName)
410 && !$this->oContext->hasNearPoint()
412 // Just looking for a country - look it up
413 if (4 >= $iMinRank && 4 <= $iMaxRank) {
414 $aResults = $this->queryCountry($oDB);
416 } elseif (empty($this->aName) && empty($this->aAddress)) {
417 // Neither name nor address? Then we must be
418 // looking for a POI in a geographic area.
419 if ($this->oContext->isBoundedSearch()) {
420 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
422 } elseif ($this->iOperator == Operator::POSTCODE) {
423 // looking for postcode
424 $aResults = $this->queryPostcode($oDB, $iLimit);
427 // First search for places according to name and address.
428 $aResults = $this->queryNamedPlace(
430 $aWordFrequencyScores,
436 //now search for housenumber, if housenumber provided
437 if ($this->sHouseNumber && !empty($aResults)) {
438 $aNamedPlaceIDs = $aResults;
439 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs);
441 if (empty($aResults) && $this->looksLikeFullAddress()) {
442 $aResults = $aNamedPlaceIDs;
446 // finally get POIs if requested
447 if ($this->sClass && !empty($aResults)) {
448 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
452 Debug::printDebugTable('Place IDs', $aResults);
454 if (!empty($aResults) && $this->sPostcode) {
455 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
457 $sSQL = 'SELECT place_id FROM placex';
458 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
459 $sSQL .= " AND postcode = '".$this->sPostcode."'";
460 Debug::printSQL($sSQL);
461 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
462 if ($aFilteredPlaceIDs) {
463 $aNewResults = array();
464 foreach ($aFilteredPlaceIDs as $iPlaceId) {
465 $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
467 $aResults = $aNewResults;
468 Debug::printVar('Place IDs after postcode filtering', $aResults);
477 private function queryCountry(&$oDB)
479 $sSQL = 'SELECT place_id FROM placex ';
480 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
481 $sSQL .= ' AND rank_search = 4';
482 if ($this->oContext->bViewboxBounded) {
483 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
485 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
487 Debug::printSQL($sSQL);
490 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
491 $aResults[$iPlaceId] = new Result($iPlaceId);
497 private function queryNearbyPoi(&$oDB, $iLimit)
499 if (!$this->sClass) {
503 $aDBResults = array();
504 $sPoiTable = $this->poiTable();
506 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
507 if (chksql($oDB->getOne($sSQL))) {
508 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
509 if ($this->oContext->sqlCountryList) {
510 $sSQL .= ' JOIN placex USING (place_id)';
512 if ($this->oContext->hasNearPoint()) {
513 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
514 } elseif ($this->oContext->bViewboxBounded) {
515 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
517 if ($this->oContext->sqlCountryList) {
518 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
520 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
521 if ($this->oContext->sqlViewboxCentre) {
522 $sSQL .= ' ORDER BY ST_Distance(';
523 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
524 } elseif ($this->oContext->hasNearPoint()) {
525 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
527 $sSQL .= " limit $iLimit";
528 Debug::printSQL($sSQL);
529 $aDBResults = chksql($oDB->getCol($sSQL));
532 if ($this->oContext->hasNearPoint()) {
533 $sSQL = 'SELECT place_id FROM placex WHERE ';
534 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
535 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
536 $sSQL .= ' AND linked_place_id is null';
537 if ($this->oContext->sqlCountryList) {
538 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
540 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
541 $sSQL .= " LIMIT $iLimit";
542 Debug::printSQL($sSQL);
543 $aDBResults = chksql($oDB->getCol($sSQL));
547 foreach ($aDBResults as $iPlaceId) {
548 $aResults[$iPlaceId] = new Result($iPlaceId);
554 private function queryPostcode(&$oDB, $iLimit)
556 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
558 if (!empty($this->aAddress)) {
559 $sSQL .= ', search_name s ';
560 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
561 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
562 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
567 $sSQL .= "p.postcode = '".reset($this->aName)."'";
568 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
569 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
570 $sSQL .= " LIMIT $iLimit";
572 Debug::printSQL($sSQL);
575 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
576 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
582 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
587 if ($this->sHouseNumber && !empty($this->aAddress)) {
588 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
590 $aOrder[0] .= 'EXISTS(';
591 $aOrder[0] .= ' SELECT place_id';
592 $aOrder[0] .= ' FROM placex';
593 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
594 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
595 $aOrder[0] .= ' LIMIT 1';
597 // also housenumbers from interpolation lines table are needed
598 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
599 $iHouseNumber = intval($this->sHouseNumber);
600 $aOrder[0] .= 'OR EXISTS(';
601 $aOrder[0] .= ' SELECT place_id ';
602 $aOrder[0] .= ' FROM location_property_osmline ';
603 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
604 $aOrder[0] .= ' AND startnumber is not NULL';
605 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
606 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
607 $aOrder[0] .= ' LIMIT 1';
610 $aOrder[0] .= ') DESC';
613 if (!empty($this->aName)) {
614 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
616 if (!empty($this->aAddress)) {
617 // For infrequent name terms disable index usage for address
618 if (CONST_Search_NameOnlySearchFrequencyThreshold
619 && count($this->aName) == 1
620 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
621 < CONST_Search_NameOnlySearchFrequencyThreshold
623 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
625 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
629 $sCountryTerm = $this->countryCodeSQL('country_code');
631 $aTerms[] = $sCountryTerm;
634 if ($this->sHouseNumber) {
635 $aTerms[] = 'address_rank between 16 and 27';
636 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
637 if ($iMinAddressRank > 0) {
638 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
640 if ($iMaxAddressRank < 30) {
641 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
645 if ($this->oContext->hasNearPoint()) {
646 $aTerms[] = $this->oContext->withinSQL('centroid');
647 $aOrder[] = $this->oContext->distanceSQL('centroid');
648 } elseif ($this->sPostcode) {
649 if (empty($this->aAddress)) {
650 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
652 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
656 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
658 $aTerms[] = $sExcludeSQL;
661 if ($this->oContext->bViewboxBounded) {
662 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
665 if ($this->oContext->hasNearPoint()) {
666 $aOrder[] = $this->oContext->distanceSQL('centroid');
669 if ($this->sHouseNumber) {
670 $sImportanceSQL = '- abs(26 - address_rank) + 3';
672 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
674 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
675 $aOrder[] = "$sImportanceSQL DESC";
677 if (!empty($this->aFullNameAddress)) {
678 $sExactMatchSQL = ' ( ';
679 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
680 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
681 $sExactMatchSQL .= ' INTERSECT ';
682 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
683 $sExactMatchSQL .= ' ) s';
684 $sExactMatchSQL .= ') as exactmatch';
685 $aOrder[] = 'exactmatch DESC';
687 $sExactMatchSQL = '0::int as exactmatch';
690 if ($this->sHouseNumber || $this->sClass) {
696 if (!empty($aTerms)) {
697 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
698 $sSQL .= ' FROM search_name';
699 $sSQL .= ' WHERE '.join(' and ', $aTerms);
700 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
701 $sSQL .= ' LIMIT '.$iLimit;
703 Debug::printSQL($sSQL);
705 $aDBResults = chksql(
707 'Could not get places for search terms.'
710 foreach ($aDBResults as $aResult) {
711 $oResult = new Result($aResult['place_id']);
712 $oResult->iExactMatches = $aResult['exactmatch'];
713 $aResults[$aResult['place_id']] = $oResult;
720 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
723 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
729 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
730 $sSQL = 'SELECT place_id FROM placex ';
731 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
732 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
733 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
735 Debug::printSQL($sSQL);
737 // XXX should inherit the exactMatches from its parent
738 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
739 $aResults[$iPlaceId] = new Result($iPlaceId);
742 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
743 $iHousenumber = intval($this->sHouseNumber);
744 if ($bIsIntHouseNumber && empty($aResults)) {
745 // if nothing found, search in the interpolation line table
746 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
747 $sSQL .= ' WHERE startnumber is not NULL';
748 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
749 if ($iHousenumber % 2 == 0) {
750 // If housenumber is even, look for housenumber in streets
751 // with interpolationtype even or all.
752 $sSQL .= "interpolationtype='even'";
754 // Else look for housenumber with interpolationtype odd or all.
755 $sSQL .= "interpolationtype='odd'";
757 $sSQL .= " or interpolationtype='all') and ";
758 $sSQL .= $iHousenumber.'>=startnumber and ';
759 $sSQL .= $iHousenumber.'<=endnumber';
760 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
762 Debug::printSQL($sSQL);
764 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
765 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
766 $oResult->iHouseNumber = $iHousenumber;
767 $aResults[$iPlaceId] = $oResult;
771 // If nothing found try the aux fallback table
772 if (CONST_Use_Aux_Location_data && empty($aResults)) {
773 $sSQL = 'SELECT place_id FROM location_property_aux';
774 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
775 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
776 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
778 Debug::printSQL($sSQL);
780 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
781 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
785 // If nothing found then search in Tiger data (location_property_tiger)
786 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
787 $sSQL = 'SELECT place_id FROM location_property_tiger';
788 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
789 if ($iHousenumber % 2 == 0) {
790 $sSQL .= "interpolationtype='even'";
792 $sSQL .= "interpolationtype='odd'";
794 $sSQL .= " or interpolationtype='all') and ";
795 $sSQL .= $iHousenumber.'>=startnumber and ';
796 $sSQL .= $iHousenumber.'<=endnumber';
797 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
799 Debug::printSQL($sSQL);
801 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
802 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
803 $oResult->iHouseNumber = $iHousenumber;
804 $aResults[$iPlaceId] = $oResult;
812 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
815 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
821 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
822 // If they were searching for a named class (i.e. 'Kings Head pub')
823 // then we might have an extra match
824 $sSQL = 'SELECT place_id FROM placex ';
825 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
826 $sSQL .= " AND class='".$this->sClass."' ";
827 $sSQL .= " AND type='".$this->sType."'";
828 $sSQL .= ' AND linked_place_id is null';
829 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
830 $sSQL .= ' ORDER BY rank_search ASC ';
831 $sSQL .= " LIMIT $iLimit";
833 Debug::printSQL($sSQL);
835 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
836 $aResults[$iPlaceId] = new Result($iPlaceId);
840 // NEAR and IN are handled the same
841 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
842 $sClassTable = $this->poiTable();
843 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
844 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
846 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
847 Debug::printSQL($sSQL);
848 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
850 // For state / country level searches the normal radius search doesn't work very well
852 if ($iMaxRank < 9 && $bCacheTable) {
853 // Try and get a polygon to search in instead
854 $sSQL = 'SELECT geometry FROM placex';
855 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
856 $sSQL .= " AND rank_search < $iMaxRank + 5";
857 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
858 $sSQL .= ' ORDER BY rank_search ASC ';
860 Debug::printSQL($sSQL);
861 $sPlaceGeom = chksql($oDB->getOne($sSQL));
868 $sSQL = 'SELECT place_id FROM placex';
869 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
870 Debug::printSQL($sSQL);
871 $aPlaceIDs = chksql($oDB->getCol($sSQL));
872 $sPlaceIDs = join(',', $aPlaceIDs);
875 if ($sPlaceIDs || $sPlaceGeom) {
878 // More efficient - can make the range bigger
882 if ($this->oContext->hasNearPoint()) {
883 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
884 } elseif ($sPlaceIDs) {
885 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
886 } elseif ($sPlaceGeom) {
887 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
890 $sSQL = 'SELECT distinct i.place_id';
892 $sSQL .= ', i.order_term';
894 $sSQL .= ' from (SELECT l.place_id';
896 $sSQL .= ','.$sOrderBySQL.' as order_term';
898 $sSQL .= ' from '.$sClassTable.' as l';
901 $sSQL .= ',placex as f WHERE ';
902 $sSQL .= "f.place_id in ($sPlaceIDs) ";
903 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
904 } elseif ($sPlaceGeom) {
905 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
908 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
909 $sSQL .= 'limit 300) i ';
911 $sSQL .= 'order by order_term asc';
913 $sSQL .= " limit $iLimit";
915 Debug::printSQL($sSQL);
917 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
918 $aResults[$iPlaceId] = new Result($iPlaceId);
921 if ($this->oContext->hasNearPoint()) {
922 $fRange = $this->oContext->nearRadius();
926 if ($this->oContext->hasNearPoint()) {
927 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
929 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
932 $sSQL = 'SELECT distinct l.place_id';
934 $sSQL .= ','.$sOrderBySQL.' as orderterm';
936 $sSQL .= ' FROM placex as l, placex as f';
937 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
938 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
939 $sSQL .= " AND l.class='".$this->sClass."'";
940 $sSQL .= " AND l.type='".$this->sType."'";
941 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
943 $sSQL .= 'ORDER BY orderterm ASC';
945 $sSQL .= " limit $iLimit";
947 Debug::printSQL($sSQL);
949 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
950 $aResults[$iPlaceId] = new Result($iPlaceId);
959 private function poiTable()
961 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
964 private function countryCodeSQL($sVar)
966 if ($this->sCountryCode) {
967 return $sVar.' = \''.$this->sCountryCode."'";
969 if ($this->oContext->sqlCountryList) {
970 return $sVar.' in '.$this->oContext->sqlCountryList;
976 /////////// Sort functions
979 public static function bySearchRank($a, $b)
981 if ($a->iSearchRank == $b->iSearchRank) {
982 return $a->iOperator + strlen($a->sHouseNumber)
983 - $b->iOperator - strlen($b->sHouseNumber);
986 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
989 //////////// Debugging functions
992 public function debugInfo()
995 'Search rank' => $this->iSearchRank,
996 'Country code' => $this->sCountryCode,
997 'Name terms' => $this->aName,
998 'Name terms (stop words)' => $this->aNameNonSearch,
999 'Address terms' => $this->aAddress,
1000 'Address terms (stop words)' => $this->aAddressNonSearch,
1001 'Address terms (full words)' => $this->aFullNameAddress,
1002 'Special search' => $this->iOperator,
1003 'Class' => $this->sClass,
1004 'Type' => $this->sType,
1005 'House number' => $this->sHouseNumber,
1006 'Postcode' => $this->sPostcode
1010 public function dumpAsHtmlTableRow(&$aWordIDs)
1012 $kf = function ($k) use (&$aWordIDs) {
1013 return $aWordIDs[$k];
1017 echo "<td>$this->iSearchRank</td>";
1018 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1019 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1020 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1021 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1022 echo '<td>'.$this->sCountryCode.'</td>';
1023 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1024 echo '<td>'.$this->sClass.'</td>';
1025 echo '<td>'.$this->sType.'</td>';
1026 echo '<td>'.$this->sPostcode.'</td>';
1027 echo '<td>'.$this->sHouseNumber.'</td>';