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 * 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)) {
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 $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 && sizeof($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 (sizeof($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 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
362 $oSearch = clone $this;
363 $oSearch->iSearchRank += 2;
364 if (!sizeof($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 && !sizeof($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 (!sizeof($this->aName) && !sizeof($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 && sizeof($aResults)) {
438 $aNamedPlaceIDs = $aResults;
439 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
441 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
442 $aResults = $aNamedPlaceIDs;
446 // finally get POIs if requested
447 if ($this->sClass && sizeof($aResults)) {
448 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
453 echo '<br><b>Place IDs:</b> ';
454 var_dump(array_keys($aResults));
457 if (sizeof($aResults) && $this->sPostcode) {
458 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
460 $sSQL = 'SELECT place_id FROM placex';
461 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
462 $sSQL .= " AND postcode = '".$this->sPostcode."'";
463 if (CONST_Debug) var_dump($sSQL);
464 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
465 if ($aFilteredPlaceIDs) {
466 $aNewResults = array();
467 foreach ($aFilteredPlaceIDs as $iPlaceId) {
468 $aNewResults[$iPlaceId] = $aResults[$iPlaceId];
470 $aResults = $aNewResults;
472 echo '<br><b>Place IDs after postcode filtering:</b> ';
473 var_dump(array_keys($aResults));
483 private function queryCountry(&$oDB)
485 $sSQL = 'SELECT place_id FROM placex ';
486 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
487 $sSQL .= ' AND rank_search = 4';
488 if ($this->oContext->bViewboxBounded) {
489 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
491 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
493 if (CONST_Debug) var_dump($sSQL);
496 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
497 $aResults[$iPlaceId] = new Result($iPlaceId);
503 private function queryNearbyPoi(&$oDB, $iLimit)
505 if (!$this->sClass) {
509 $aDBResults = array();
510 $sPoiTable = $this->poiTable();
512 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
513 if (chksql($oDB->getOne($sSQL))) {
514 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
515 if ($this->oContext->sqlCountryList) {
516 $sSQL .= ' JOIN placex USING (place_id)';
518 if ($this->oContext->hasNearPoint()) {
519 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
520 } elseif ($this->oContext->bViewboxBounded) {
521 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
523 if ($this->oContext->sqlCountryList) {
524 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
526 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
527 if ($this->oContext->sqlViewboxCentre) {
528 $sSQL .= ' ORDER BY ST_Distance(';
529 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
530 } elseif ($this->oContext->hasNearPoint()) {
531 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
533 $sSQL .= " limit $iLimit";
534 if (CONST_Debug) var_dump($sSQL);
535 $aDBResults = chksql($oDB->getCol($sSQL));
538 if ($this->oContext->hasNearPoint()) {
539 $sSQL = 'SELECT place_id FROM placex WHERE ';
540 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
541 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
542 $sSQL .= ' AND linked_place_id is null';
543 if ($this->oContext->sqlCountryList) {
544 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
546 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
547 $sSQL .= " LIMIT $iLimit";
548 if (CONST_Debug) var_dump($sSQL);
549 $aDBResults = chksql($oDB->getCol($sSQL));
553 foreach ($aDBResults as $iPlaceId) {
554 $aResults[$iPlaceId] = new Result($iPlaceId);
560 private function queryPostcode(&$oDB, $iLimit)
562 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
564 if (sizeof($this->aAddress)) {
565 $sSQL .= ', search_name s ';
566 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
567 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
568 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
573 $sSQL .= "p.postcode = '".reset($this->aName)."'";
574 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
575 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
576 $sSQL .= " LIMIT $iLimit";
578 if (CONST_Debug) var_dump($sSQL);
581 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
582 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
588 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
593 if ($this->sHouseNumber && sizeof($this->aAddress)) {
594 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
596 $aOrder[0] .= 'EXISTS(';
597 $aOrder[0] .= ' SELECT place_id';
598 $aOrder[0] .= ' FROM placex';
599 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
600 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
601 $aOrder[0] .= ' LIMIT 1';
603 // also housenumbers from interpolation lines table are needed
604 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
605 $iHouseNumber = intval($this->sHouseNumber);
606 $aOrder[0] .= 'OR EXISTS(';
607 $aOrder[0] .= ' SELECT place_id ';
608 $aOrder[0] .= ' FROM location_property_osmline ';
609 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
610 $aOrder[0] .= ' AND startnumber is not NULL';
611 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
612 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
613 $aOrder[0] .= ' LIMIT 1';
616 $aOrder[0] .= ') DESC';
619 if (sizeof($this->aName)) {
620 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
622 if (sizeof($this->aAddress)) {
623 // For infrequent name terms disable index usage for address
624 if (CONST_Search_NameOnlySearchFrequencyThreshold
625 && sizeof($this->aName) == 1
626 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
627 < CONST_Search_NameOnlySearchFrequencyThreshold
629 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
631 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
635 $sCountryTerm = $this->countryCodeSQL('country_code');
637 $aTerms[] = $sCountryTerm;
640 if ($this->sHouseNumber) {
641 $aTerms[] = 'address_rank between 16 and 27';
642 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
643 if ($iMinAddressRank > 0) {
644 $aTerms[] = 'address_rank >= '.$iMinAddressRank;
646 if ($iMaxAddressRank < 30) {
647 $aTerms[] = 'address_rank <= '.$iMaxAddressRank;
651 if ($this->oContext->hasNearPoint()) {
652 $aTerms[] = $this->oContext->withinSQL('centroid');
653 $aOrder[] = $this->oContext->distanceSQL('centroid');
654 } elseif ($this->sPostcode) {
655 if (!sizeof($this->aAddress)) {
656 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
658 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
662 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
664 $aTerms[] = $sExcludeSQL;
667 if ($this->oContext->bViewboxBounded) {
668 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
671 if ($this->oContext->hasNearPoint()) {
672 $aOrder[] = $this->oContext->distanceSQL('centroid');
675 if ($this->sHouseNumber) {
676 $sImportanceSQL = '- abs(26 - address_rank) + 3';
678 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
680 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
681 $aOrder[] = "$sImportanceSQL DESC";
683 if (sizeof($this->aFullNameAddress)) {
684 $sExactMatchSQL = ' ( ';
685 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
686 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
687 $sExactMatchSQL .= ' INTERSECT ';
688 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
689 $sExactMatchSQL .= ' ) s';
690 $sExactMatchSQL .= ') as exactmatch';
691 $aOrder[] = 'exactmatch DESC';
693 $sExactMatchSQL = '0::int as exactmatch';
696 if ($this->sHouseNumber || $this->sClass) {
702 if (sizeof($aTerms)) {
703 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
704 $sSQL .= ' FROM search_name';
705 $sSQL .= ' WHERE '.join(' and ', $aTerms);
706 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
707 $sSQL .= ' LIMIT '.$iLimit;
709 if (CONST_Debug) var_dump($sSQL);
711 $aDBResults = chksql(
713 'Could not get places for search terms.'
716 foreach ($aDBResults as $aResult) {
717 $oResult = new Result($aResult['place_id']);
718 $oResult->iExactMatches = $aResult['exactmatch'];
719 $aResults[$aResult['place_id']] = $oResult;
726 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
729 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
735 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
736 $sSQL = 'SELECT place_id FROM placex ';
737 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
738 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
739 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
740 $sSQL .= " LIMIT $iLimit";
742 if (CONST_Debug) var_dump($sSQL);
744 // XXX should inherit the exactMatches from its parent
745 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
746 $aResults[$iPlaceId] = new Result($iPlaceId);
749 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
750 $iHousenumber = intval($this->sHouseNumber);
751 if ($bIsIntHouseNumber && !sizeof($aResults)) {
752 // if nothing found, search in the interpolation line table
753 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
754 $sSQL .= ' WHERE startnumber is not NULL';
755 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
756 if ($iHousenumber % 2 == 0) {
757 // If housenumber is even, look for housenumber in streets
758 // with interpolationtype even or all.
759 $sSQL .= "interpolationtype='even'";
761 // Else look for housenumber with interpolationtype odd or all.
762 $sSQL .= "interpolationtype='odd'";
764 $sSQL .= " or interpolationtype='all') and ";
765 $sSQL .= $iHousenumber.'>=startnumber and ';
766 $sSQL .= $iHousenumber.'<=endnumber';
767 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
768 $sSQL .= " limit $iLimit";
770 if (CONST_Debug) var_dump($sSQL);
772 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
773 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
774 $oResult->iHouseNumber = $iHousenumber;
775 $aResults[$iPlaceId] = $oResult;
779 // If nothing found try the aux fallback table
780 if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
781 $sSQL = 'SELECT place_id FROM location_property_aux';
782 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
783 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
784 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
785 $sSQL .= " limit $iLimit";
787 if (CONST_Debug) var_dump($sSQL);
789 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
790 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
794 // If nothing found then search in Tiger data (location_property_tiger)
795 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
796 $sSQL = 'SELECT place_id FROM location_property_tiger';
797 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
798 if ($iHousenumber % 2 == 0) {
799 $sSQL .= "interpolationtype='even'";
801 $sSQL .= "interpolationtype='odd'";
803 $sSQL .= " or interpolationtype='all') and ";
804 $sSQL .= $iHousenumber.'>=startnumber and ';
805 $sSQL .= $iHousenumber.'<=endnumber';
806 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
807 $sSQL .= " limit $iLimit";
809 if (CONST_Debug) var_dump($sSQL);
811 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
812 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
813 $oResult->iHouseNumber = $iHousenumber;
814 $aResults[$iPlaceId] = $oResult;
822 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
825 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
831 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
832 // If they were searching for a named class (i.e. 'Kings Head pub')
833 // then we might have an extra match
834 $sSQL = 'SELECT place_id FROM placex ';
835 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
836 $sSQL .= " AND class='".$this->sClass."' ";
837 $sSQL .= " AND type='".$this->sType."'";
838 $sSQL .= ' AND linked_place_id is null';
839 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
840 $sSQL .= ' ORDER BY rank_search ASC ';
841 $sSQL .= " LIMIT $iLimit";
843 if (CONST_Debug) var_dump($sSQL);
845 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
846 $aResults[$iPlaceId] = new Result($iPlaceId);
850 // NEAR and IN are handled the same
851 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
852 $sClassTable = $this->poiTable();
853 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
854 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
856 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
857 if (CONST_Debug) var_dump($sSQL);
858 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
860 // For state / country level searches the normal radius search doesn't work very well
862 if ($iMaxRank < 9 && $bCacheTable) {
863 // Try and get a polygon to search in instead
864 $sSQL = 'SELECT geometry FROM placex';
865 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
866 $sSQL .= " AND rank_search < $iMaxRank + 5";
867 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
868 $sSQL .= ' ORDER BY rank_search ASC ';
870 if (CONST_Debug) var_dump($sSQL);
871 $sPlaceGeom = chksql($oDB->getOne($sSQL));
878 $sSQL = 'SELECT place_id FROM placex';
879 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
880 if (CONST_Debug) var_dump($sSQL);
881 $aPlaceIDs = chksql($oDB->getCol($sSQL));
882 $sPlaceIDs = join(',', $aPlaceIDs);
885 if ($sPlaceIDs || $sPlaceGeom) {
888 // More efficient - can make the range bigger
892 if ($this->oContext->hasNearPoint()) {
893 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
894 } elseif ($sPlaceIDs) {
895 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
896 } elseif ($sPlaceGeom) {
897 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
900 $sSQL = 'SELECT distinct i.place_id';
902 $sSQL .= ', i.order_term';
904 $sSQL .= ' from (SELECT l.place_id';
906 $sSQL .= ','.$sOrderBySQL.' as order_term';
908 $sSQL .= ' from '.$sClassTable.' as l';
911 $sSQL .= ',placex as f WHERE ';
912 $sSQL .= "f.place_id in ($sPlaceIDs) ";
913 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
914 } elseif ($sPlaceGeom) {
915 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
918 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
919 $sSQL .= 'limit 300) i ';
921 $sSQL .= 'order by order_term asc';
923 $sSQL .= " limit $iLimit";
925 if (CONST_Debug) var_dump($sSQL);
927 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
928 $aResults[$iPlaceId] = new Result($iPlaceId);
931 if ($this->oContext->hasNearPoint()) {
932 $fRange = $this->oContext->nearRadius();
936 if ($this->oContext->hasNearPoint()) {
937 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
939 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
942 $sSQL = 'SELECT distinct l.place_id';
944 $sSQL .= ','.$sOrderBySQL.' as orderterm';
946 $sSQL .= ' FROM placex as l, placex as f';
947 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
948 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
949 $sSQL .= " AND l.class='".$this->sClass."'";
950 $sSQL .= " AND l.type='".$this->sType."'";
951 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
953 $sSQL .= 'ORDER BY orderterm ASC';
955 $sSQL .= " limit $iLimit";
957 if (CONST_Debug) var_dump($sSQL);
959 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
960 $aResults[$iPlaceId] = new Result($iPlaceId);
969 private function poiTable()
971 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
974 private function countryCodeSQL($sVar)
976 if ($this->sCountryCode) {
977 return $sVar.' = \''.$this->sCountryCode."'";
979 if ($this->oContext->sqlCountryList) {
980 return $sVar.' in '.$this->oContext->sqlCountryList;
986 /////////// Sort functions
989 public static function bySearchRank($a, $b)
991 if ($a->iSearchRank == $b->iSearchRank) {
992 return $a->iOperator + strlen($a->sHouseNumber)
993 - $b->iOperator - strlen($b->sHouseNumber);
996 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
999 //////////// Debugging functions
1002 public function dumpAsHtmlTableRow(&$aWordIDs)
1004 $kf = function ($k) use (&$aWordIDs) {
1005 return $aWordIDs[$k];
1009 echo "<td>$this->iSearchRank</td>";
1010 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1011 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1012 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1013 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1014 echo '<td>'.$this->sCountryCode.'</td>';
1015 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1016 echo '<td>'.$this->sClass.'</td>';
1017 echo '<td>'.$this->sType.'</td>';
1018 echo '<td>'.$this->sPostcode.'</td>';
1019 echo '<td>'.$this->sHouseNumber.'</td>';