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 likelyhood 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 * Increase the search rank.
74 * @param integer $iAddRank Number of ranks to increase.
78 public function addToRank($iAddRank)
80 $this->iSearchRank += $iAddRank;
81 return $this->iSearchRank;
85 * Make this search a POI search.
87 * In a POI search, objects are not (only) searched by their name
88 * but also by the primary OSM key/value pair (class and type in Nominatim).
90 * @param integer $iOperator Type of POI search
91 * @param string $sClass Class (or OSM tag key) of POI.
92 * @param string $sType Type (or OSM tag value) of POI.
96 public function setPoiSearch($iOperator, $sClass, $sType)
98 $this->iOperator = $iOperator;
99 $this->sClass = $sClass;
100 $this->sType = $sType;
104 * Check if this might be a full address search.
106 * @return bool True if the search contains name, address and housenumber.
108 public function looksLikeFullAddress()
110 return sizeof($this->aName)
111 && (sizeof($this->aAddress || $this->sCountryCode))
112 && preg_match('/[0-9]+/', $this->sHouseNumber);
116 * Check if any operator is set.
118 * @return bool True, if this is a special search operation.
120 public function hasOperator()
122 return $this->iOperator != Operator::NONE;
126 * Extract key/value pairs from a query.
128 * Key/value pairs are recognised if they are of the form [<key>=<value>].
129 * If multiple terms of this kind are found then all terms are removed
130 * but only the first is used for search.
132 * @param string $sQuery Original query string.
134 * @return string The query string with the special search patterns removed.
136 public function extractKeyValuePairs($sQuery)
138 // Search for terms of kind [<key>=<value>].
140 '/\\[([\\w_]*)=([\\w_]*)\\]/',
146 foreach ($aSpecialTermsRaw as $aTerm) {
147 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
148 if (!$this->hasOperator()) {
149 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
157 * Check if the combination of parameters is sensible.
159 * @return bool True, if the search looks valid.
161 public function isValidSearch()
163 if (!sizeof($this->aName)) {
164 if ($this->sHouseNumber) {
167 if (!$this->sClass && !$this->sCountryCode) {
175 /////////// Search building functions
179 * Derive new searches by adding a full term to the existing search.
181 * @param mixed[] $aSearchTerm Description of the token.
182 * @param bool $bHasPartial True if there are also tokens of partial terms
183 * with the same name.
184 * @param string $sPhraseType Type of phrase the token is contained in.
185 * @param bool $bFirstToken True if the token is at the beginning of the
187 * @param bool $bFirstPhrase True if the token is in the first phrase of
189 * @param bool $bLastToken True if the token is at the end of the query.
190 * @param integer $iGlobalRank Changable ranking of all searches in the
193 * @return SearchDescription[] List of derived search descriptions.
195 public function extendWithFullTerm($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken, &$iGlobalRank)
197 $aNewSearches = array();
199 if (($sPhraseType == '' || $sPhraseType == 'country')
200 && !empty($aSearchTerm['country_code'])
201 && $aSearchTerm['country_code'] != '0'
203 if (!$this->sCountryCode) {
204 $oSearch = clone $this;
205 $oSearch->iSearchRank++;
206 $oSearch->sCountryCode = $aSearchTerm['country_code'];
207 // Country is almost always at the end of the string
208 // - increase score for finding it anywhere else (optimisation)
210 $oSearch->iSearchRank += 5;
212 $aNewSearches[] = $oSearch;
214 // If it is at the beginning, we can be almost sure that
215 // the terms are in the wrong order. Increase score for all searches.
220 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
221 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
223 // We need to try the case where the postal code is the primary element
224 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
226 if (!$this->sPostcode
227 && $aSearchTerm['word']
228 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
230 // If we have structured search or this is the first term,
231 // make the postcode the primary search element.
232 if ($this->iOperator == Operator::NONE
233 && ($sPhraseType == 'postalcode' || $bFirstToken)
235 $oSearch = clone $this;
236 $oSearch->iSearchRank++;
237 $oSearch->iOperator = Operator::POSTCODE;
238 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
240 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
241 $aNewSearches[] = $oSearch;
244 // If we have a structured search or this is not the first term,
245 // add the postcode as an addendum.
246 if ($this->iOperator != Operator::POSTCODE
247 && ($sPhraseType == 'postalcode' || sizeof($this->aName))
249 $oSearch = clone $this;
250 $oSearch->iSearchRank++;
251 $oSearch->sPostcode = $aSearchTerm['word'];
252 $aNewSearches[] = $oSearch;
255 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
256 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
258 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
259 $oSearch = clone $this;
260 $oSearch->iSearchRank++;
261 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
262 // sanity check: if the housenumber is not mainly made
263 // up of numbers, add a penalty
264 if (preg_match_all("/[^0-9]/", $oSearch->sHouseNumber, $aMatches) > 2) {
265 $oSearch->iSearchRank++;
267 if (!isset($aSearchTerm['word_id'])) {
268 $oSearch->iSearchRank++;
270 // also must not appear in the middle of the address
271 if (sizeof($this->aAddress) || sizeof($this->aAddressNonSearch)) {
272 $oSearch->iSearchRank++;
274 $aNewSearches[] = $oSearch;
276 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
277 if ($this->iOperator == Operator::NONE) {
278 $oSearch = clone $this;
279 $oSearch->iSearchRank++;
281 $iOp = Operator::NEAR; // near == in for the moment
282 if ($aSearchTerm['operator'] == '') {
283 if (sizeof($this->aName)) {
284 $iOp = Operator::NAME;
286 $oSearch->iSearchRank += 2;
289 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
290 $aNewSearches[] = $oSearch;
292 } elseif (isset($aSearchTerm['word_id'])
293 && $aSearchTerm['word_id']
294 && $sPhraseType != 'country'
296 $iWordID = $aSearchTerm['word_id'];
297 if (sizeof($this->aName)) {
298 if (($sPhraseType == '' || !$bFirstPhrase)
299 && $sPhraseType != 'country'
302 $oSearch = clone $this;
303 $oSearch->iSearchRank++;
304 $oSearch->aAddress[$iWordID] = $iWordID;
305 $aNewSearches[] = $oSearch;
307 $this->aFullNameAddress[$iWordID] = $iWordID;
310 $oSearch = clone $this;
311 $oSearch->iSearchRank++;
312 $oSearch->aName = array($iWordID => $iWordID);
313 $aNewSearches[] = $oSearch;
317 return $aNewSearches;
321 * Derive new searches by adding a partial term to the existing search.
323 * @param mixed[] $aSearchTerm Description of the token.
324 * @param bool $bStructuredPhrases True if the search is structured.
325 * @param integer $iPhrase Number of the phrase the token is in.
326 * @param array[] $aFullTokens List of full term tokens with the
329 * @return SearchDescription[] List of derived search descriptions.
331 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
333 // Only allow name terms.
334 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
338 $aNewSearches = array();
339 $iWordID = $aSearchTerm['word_id'];
341 if ((!$bStructuredPhrases || $iPhrase > 0)
342 && sizeof($this->aName)
343 && strpos($aSearchTerm['word_token'], ' ') === false
345 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
346 $oSearch = clone $this;
347 $oSearch->iSearchRank++;
348 $oSearch->aAddress[$iWordID] = $iWordID;
349 $aNewSearches[] = $oSearch;
351 $oSearch = clone $this;
352 $oSearch->iSearchRank++;
353 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
354 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
355 $oSearch->iSearchRank += 2;
357 if (sizeof($aFullTokens)) {
358 $oSearch->iSearchRank++;
360 $aNewSearches[] = $oSearch;
362 // revert to the token version?
363 foreach ($aFullTokens as $aSearchTermToken) {
364 if (empty($aSearchTermToken['country_code'])
365 && empty($aSearchTermToken['lat'])
366 && empty($aSearchTermToken['class'])
368 $oSearch = clone $this;
369 $oSearch->iSearchRank++;
370 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
371 $aNewSearches[] = $oSearch;
377 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
378 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
380 $oSearch = clone $this;
381 $oSearch->iSearchRank++;
382 if (!sizeof($this->aName)) {
383 $oSearch->iSearchRank += 1;
385 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
386 $oSearch->iSearchRank += 2;
388 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
389 $oSearch->aName[$iWordID] = $iWordID;
391 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
393 $oSearch->iNamePhrase = $iPhrase;
394 $aNewSearches[] = $oSearch;
397 return $aNewSearches;
400 /////////// Query functions
404 * Query database for places that match this search.
406 * @param object $oDB Database connection to use.
407 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
408 * overall in a planet database.
409 * @param integer $iMinRank Minimum address rank to restrict
411 * @param integer $iMaxRank Maximum address rank to restrict
413 * @param integer $iLimit Maximum number of results.
415 * @return mixed[] An array with two fields: IDs contains the list of
416 * matching place IDs and houseNumber the houseNumber
417 * if appicable or -1 if not.
419 public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
424 if ($this->sCountryCode
425 && !sizeof($this->aName)
428 && !$this->oContext->hasNearPoint()
430 // Just looking for a country - look it up
431 if (4 >= $iMinRank && 4 <= $iMaxRank) {
432 $aResults = $this->queryCountry($oDB);
434 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
435 // Neither name nor address? Then we must be
436 // looking for a POI in a geographic area.
437 if ($this->oContext->isBoundedSearch()) {
438 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
440 } elseif ($this->iOperator == Operator::POSTCODE) {
441 // looking for postcode
442 $aResults = $this->queryPostcode($oDB, $iLimit);
445 // First search for places according to name and address.
446 $aResults = $this->queryNamedPlace(
448 $aWordFrequencyScores,
454 //now search for housenumber, if housenumber provided
455 if ($this->sHouseNumber && sizeof($aResults)) {
456 $aNamedPlaceIDs = $aResults;
457 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
459 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
460 $aResults = $aNamedPlaceIDs;
464 // finally get POIs if requested
465 if ($this->sClass && sizeof($aResults)) {
466 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
471 echo "<br><b>Place IDs:</b> ";
472 var_dump(array_keys($aResults));
475 if (sizeof($aResults) && $this->sPostcode) {
476 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
478 $sSQL = 'SELECT place_id FROM placex';
479 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
480 $sSQL .= " AND postcode = '".$this->sPostcode."'";
481 if (CONST_Debug) var_dump($sSQL);
482 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
483 if ($aFilteredPlaceIDs) {
484 $aNewResults = array();
485 foreach ($aFilteredPlaceIDs as $iPlaceId) {
486 $aNewResults[$iPlaceId] = $aResults[$iPLaceId];
488 $aResults = $aNewResults;
490 echo "<br><b>Place IDs after postcode filtering:</b> ";
491 var_dump(array_keys($aResults));
501 private function queryCountry(&$oDB)
503 $sSQL = 'SELECT place_id FROM placex ';
504 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
505 $sSQL .= ' AND rank_search = 4';
506 if ($this->oContext->bViewboxBounded) {
507 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
509 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
511 if (CONST_Debug) var_dump($sSQL);
514 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
515 $aResults[$iPlaceId] = new Result($iPlaceId);
521 private function queryNearbyPoi(&$oDB, $iLimit)
523 if (!$this->sClass) {
527 $aDBResults = array();
528 $sPoiTable = $this->poiTable();
530 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
531 if (chksql($oDB->getOne($sSQL))) {
532 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
533 if ($this->oContext->sqlCountryList) {
534 $sSQL .= ' JOIN placex USING (place_id)';
536 if ($this->oContext->hasNearPoint()) {
537 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
538 } elseif ($this->oContext->bViewboxBounded) {
539 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
541 if ($this->oContext->sqlCountryList) {
542 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
544 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
545 if ($this->oContext->sqlViewboxCentre) {
546 $sSQL .= ' ORDER BY ST_Distance(';
547 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
548 } elseif ($this->oContext->hasNearPoint()) {
549 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
551 $sSQL .= " limit $iLimit";
552 if (CONST_Debug) var_dump($sSQL);
553 $aDBResults = chksql($oDB->getCol($sSQL));
556 if ($this->oContext->hasNearPoint()) {
557 $sSQL = 'SELECT place_id FROM placex WHERE ';
558 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
559 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
560 $sSQL .= ' AND linked_place_id is null';
561 if ($this->oContext->sqlCountryList) {
562 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
564 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
565 $sSQL .= " LIMIT $iLimit";
566 if (CONST_Debug) var_dump($sSQL);
567 $aDBResults = chksql($oDB->getCol($sSQL));
571 foreach ($aDBResults as $iPlaceId) {
572 $aResults[$iPlaceId] = new Result($iPlaceId);
578 private function queryPostcode(&$oDB, $iLimit)
580 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
582 if (sizeof($this->aAddress)) {
583 $sSQL .= ', search_name s ';
584 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
585 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
586 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
591 $sSQL .= "p.postcode = '".reset($this->aName)."'";
592 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
593 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
594 $sSQL .= " LIMIT $iLimit";
596 if (CONST_Debug) var_dump($sSQL);
599 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
600 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
606 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
611 if ($this->sHouseNumber && sizeof($this->aAddress)) {
612 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
614 $aOrder[0] .= 'EXISTS(';
615 $aOrder[0] .= ' SELECT place_id';
616 $aOrder[0] .= ' FROM placex';
617 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
618 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
619 $aOrder[0] .= ' LIMIT 1';
621 // also housenumbers from interpolation lines table are needed
622 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
623 $iHouseNumber = intval($this->sHouseNumber);
624 $aOrder[0] .= 'OR EXISTS(';
625 $aOrder[0] .= ' SELECT place_id ';
626 $aOrder[0] .= ' FROM location_property_osmline ';
627 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
628 $aOrder[0] .= ' AND startnumber is not NULL';
629 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
630 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
631 $aOrder[0] .= ' LIMIT 1';
634 $aOrder[0] .= ') DESC';
637 if (sizeof($this->aName)) {
638 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
640 if (sizeof($this->aAddress)) {
641 // For infrequent name terms disable index usage for address
642 if (CONST_Search_NameOnlySearchFrequencyThreshold
643 && sizeof($this->aName) == 1
644 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
645 < CONST_Search_NameOnlySearchFrequencyThreshold
647 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
649 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
653 $sCountryTerm = $this->countryCodeSQL('country_code');
655 $aTerms[] = $sCountryTerm;
658 if ($this->sHouseNumber) {
659 $aTerms[] = "address_rank between 16 and 27";
660 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
661 if ($iMinAddressRank > 0) {
662 $aTerms[] = "address_rank >= ".$iMinAddressRank;
664 if ($iMaxAddressRank < 30) {
665 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
669 if ($this->oContext->hasNearPoint()) {
670 $aTerms[] = $this->oContext->withinSQL('centroid');
671 $aOrder[] = $this->oContext->distanceSQL('centroid');
672 } elseif ($this->sPostcode) {
673 if (!sizeof($this->aAddress)) {
674 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
676 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
680 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
682 $aTerms[] = $sExcludeSQL;
685 if ($this->oContext->bViewboxBounded) {
686 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
689 if ($this->oContext->hasNearPoint()) {
690 $aOrder[] = $this->oContext->distanceSQL('centroid');
693 if ($this->sHouseNumber) {
694 $sImportanceSQL = '- abs(26 - address_rank) + 3';
696 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
698 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
699 $aOrder[] = "$sImportanceSQL DESC";
701 if (sizeof($this->aFullNameAddress)) {
702 $sExactMatchSQL = ' ( ';
703 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
704 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
705 $sExactMatchSQL .= ' INTERSECT ';
706 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
707 $sExactMatchSQL .= ' ) s';
708 $sExactMatchSQL .= ') as exactmatch';
709 $aOrder[] = 'exactmatch DESC';
711 $sExactMatchSQL = '0::int as exactmatch';
714 if ($this->sHouseNumber || $this->sClass) {
720 if (sizeof($aTerms)) {
721 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
722 $sSQL .= ' FROM search_name';
723 $sSQL .= ' WHERE '.join(' and ', $aTerms);
724 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
725 $sSQL .= ' LIMIT '.$iLimit;
727 if (CONST_Debug) var_dump($sSQL);
729 $aDBResults = chksql(
731 "Could not get places for search terms."
734 foreach ($aDBResults as $aResult) {
735 $oResult = new Result($aResult['place_id']);
736 $oResult->iExactMatches = $aResult['exactmatch'];
737 $aResults[$aResult['place_id']] = $oResult;
744 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
747 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
753 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
754 $sSQL = 'SELECT place_id FROM placex ';
755 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
756 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
757 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
758 $sSQL .= " LIMIT $iLimit";
760 if (CONST_Debug) var_dump($sSQL);
762 // XXX should inherit the exactMatches from its parent
763 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
764 $aResults[$iPlaceId] = new Result($iPlaceId);
767 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
768 $iHousenumber = intval($this->sHouseNumber);
769 if ($bIsIntHouseNumber && !sizeof($aResults)) {
770 // if nothing found, search in the interpolation line table
771 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
772 $sSQL .= ' WHERE startnumber is not NULL';
773 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
774 if ($iHousenumber % 2 == 0) {
775 // If housenumber is even, look for housenumber in streets
776 // with interpolationtype even or all.
777 $sSQL .= "interpolationtype='even'";
779 // Else look for housenumber with interpolationtype odd or all.
780 $sSQL .= "interpolationtype='odd'";
782 $sSQL .= " or interpolationtype='all') and ";
783 $sSQL .= $iHousenumber.">=startnumber and ";
784 $sSQL .= $iHousenumber."<=endnumber";
785 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
786 $sSQL .= " limit $iLimit";
788 if (CONST_Debug) var_dump($sSQL);
790 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
791 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
792 $oResult->iHouseNumber = $iHousenumber;
793 $aResults[$iPlaceId] = $oResult;
797 // If nothing found try the aux fallback table
798 if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
799 $sSQL = 'SELECT place_id FROM location_property_aux';
800 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
801 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
802 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
803 $sSQL .= " limit $iLimit";
805 if (CONST_Debug) var_dump($sSQL);
807 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
808 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
812 // If nothing found then search in Tiger data (location_property_tiger)
813 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
814 $sSQL = 'SELECT place_id FROM location_property_tiger';
815 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
816 if ($iHousenumber % 2 == 0) {
817 $sSQL .= "interpolationtype='even'";
819 $sSQL .= "interpolationtype='odd'";
821 $sSQL .= " or interpolationtype='all') and ";
822 $sSQL .= $iHousenumber.">=startnumber and ";
823 $sSQL .= $iHousenumber."<=endnumber";
824 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
825 $sSQL .= " limit $iLimit";
827 if (CONST_Debug) var_dump($sSQL);
829 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
830 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
831 $oResult->iHouseNumber = $iHousenumber;
832 $aResults[$iPlaceId] = $oResult;
840 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
843 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
849 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
850 // If they were searching for a named class (i.e. 'Kings Head pub')
851 // then we might have an extra match
852 $sSQL = 'SELECT place_id FROM placex ';
853 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
854 $sSQL .= " AND class='".$this->sClass."' ";
855 $sSQL .= " AND type='".$this->sType."'";
856 $sSQL .= " AND linked_place_id is null";
857 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
858 $sSQL .= " ORDER BY rank_search ASC ";
859 $sSQL .= " LIMIT $iLimit";
861 if (CONST_Debug) var_dump($sSQL);
863 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
864 $aResults[$iPlaceId] = new Result($iPlaceId);
868 // NEAR and IN are handled the same
869 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
870 $sClassTable = $this->poiTable();
871 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
872 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
874 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
875 if (CONST_Debug) var_dump($sSQL);
876 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
878 // For state / country level searches the normal radius search doesn't work very well
880 if ($iMaxRank < 9 && $bCacheTable) {
881 // Try and get a polygon to search in instead
882 $sSQL = 'SELECT geometry FROM placex';
883 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
884 $sSQL .= " AND rank_search < $iMaxRank + 5";
885 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
886 $sSQL .= " ORDER BY rank_search ASC ";
888 if (CONST_Debug) var_dump($sSQL);
889 $sPlaceGeom = chksql($oDB->getOne($sSQL));
896 $sSQL = 'SELECT place_id FROM placex';
897 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
898 if (CONST_Debug) var_dump($sSQL);
899 $aPlaceIDs = chksql($oDB->getCol($sSQL));
900 $sPlaceIDs = join(',', $aPlaceIDs);
903 if ($sPlaceIDs || $sPlaceGeom) {
906 // More efficient - can make the range bigger
910 if ($this->oContext->hasNearPoint()) {
911 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
912 } elseif ($sPlaceIDs) {
913 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
914 } elseif ($sPlaceGeom) {
915 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
918 $sSQL = 'SELECT distinct i.place_id';
920 $sSQL .= ', i.order_term';
922 $sSQL .= ' from (SELECT l.place_id';
924 $sSQL .= ','.$sOrderBySQL.' as order_term';
926 $sSQL .= ' from '.$sClassTable.' as l';
929 $sSQL .= ",placex as f WHERE ";
930 $sSQL .= "f.place_id in ($sPlaceIDs) ";
931 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
932 } elseif ($sPlaceGeom) {
933 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
936 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
937 $sSQL .= 'limit 300) i ';
939 $sSQL .= 'order by order_term asc';
941 $sSQL .= " limit $iLimit";
943 if (CONST_Debug) var_dump($sSQL);
945 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
946 $aResults[$iPlaceId] = new Result($iPlaceId);
949 if ($this->oContext->hasNearPoint()) {
950 $fRange = $this->oContext->nearRadius();
954 if ($this->oContext->hasNearPoint()) {
955 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
957 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
960 $sSQL = 'SELECT distinct l.place_id';
962 $sSQL .= ','.$sOrderBySQL.' as orderterm';
964 $sSQL .= ' FROM placex as l, placex as f';
965 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
966 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
967 $sSQL .= " AND l.class='".$this->sClass."'";
968 $sSQL .= " AND l.type='".$this->sType."'";
969 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
971 $sSQL .= "ORDER BY orderterm ASC";
973 $sSQL .= " limit $iLimit";
975 if (CONST_Debug) var_dump($sSQL);
977 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
978 $aResults[$iPlaceId] = new Result($iPlaceId);
987 private function poiTable()
989 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
992 private function countryCodeSQL($sVar)
994 if ($this->sCountryCode) {
995 return $sVar.' = \''.$this->sCountryCode."'";
997 if ($this->oContext->sqlCountryList) {
998 return $sVar.' in '.$this->oContext->sqlCountryList;
1004 /////////// Sort functions
1007 public static function bySearchRank($a, $b)
1009 if ($a->iSearchRank == $b->iSearchRank) {
1010 return $a->iOperator + strlen($a->sHouseNumber)
1011 - $b->iOperator - strlen($b->sHouseNumber);
1014 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1017 //////////// Debugging functions
1020 public function dumpAsHtmlTableRow(&$aWordIDs)
1022 $kf = function ($k) use (&$aWordIDs) {
1023 return $aWordIDs[$k];
1027 echo "<td>$this->iSearchRank</td>";
1028 echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
1029 echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
1030 echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
1031 echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
1032 echo "<td>".$this->sCountryCode."</td>";
1033 echo "<td>".Operator::toString($this->iOperator)."</td>";
1034 echo "<td>".$this->sClass."</td>";
1035 echo "<td>".$this->sType."</td>";
1036 echo "<td>".$this->sPostcode."</td>";
1037 echo "<td>".$this->sHouseNumber."</td>";