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) || sizeof($this->aAddressNonSearch)) {
251 $oSearch->iSearchRank++;
253 $aNewSearches[] = $oSearch;
255 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
256 if ($this->iOperator == Operator::NONE) {
257 $oSearch = clone $this;
258 $oSearch->iSearchRank++;
260 $iOp = Operator::NEAR; // near == in for the moment
261 if ($aSearchTerm['operator'] == '') {
262 if (sizeof($this->aName)) {
263 $iOp = Operator::NAME;
265 $oSearch->iSearchRank += 2;
268 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
269 $aNewSearches[] = $oSearch;
271 } elseif (isset($aSearchTerm['word_id'])
272 && $aSearchTerm['word_id']
273 && $sPhraseType != 'country'
275 $iWordID = $aSearchTerm['word_id'];
276 if (sizeof($this->aName)) {
277 if (($sPhraseType == '' || !$bFirstPhrase)
278 && $sPhraseType != 'country'
281 $oSearch = clone $this;
282 $oSearch->iSearchRank++;
283 $oSearch->aAddress[$iWordID] = $iWordID;
284 $aNewSearches[] = $oSearch;
286 $this->aFullNameAddress[$iWordID] = $iWordID;
289 $oSearch = clone $this;
290 $oSearch->iSearchRank++;
291 $oSearch->aName = array($iWordID => $iWordID);
292 $aNewSearches[] = $oSearch;
296 return $aNewSearches;
300 * Derive new searches by adding a partial term to the existing search.
302 * @param mixed[] $aSearchTerm Description of the token.
303 * @param bool $bStructuredPhrases True if the search is structured.
304 * @param integer $iPhrase Number of the phrase the token is in.
305 * @param array[] $aFullTokens List of full term tokens with the
308 * @return SearchDescription[] List of derived search descriptions.
310 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
312 // Only allow name terms.
313 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
317 $aNewSearches = array();
318 $iWordID = $aSearchTerm['word_id'];
320 if ((!$bStructuredPhrases || $iPhrase > 0)
321 && sizeof($this->aName)
322 && strpos($aSearchTerm['word_token'], ' ') === false
324 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
325 $oSearch = clone $this;
326 $oSearch->iSearchRank++;
327 $oSearch->aAddress[$iWordID] = $iWordID;
328 $aNewSearches[] = $oSearch;
330 $oSearch = clone $this;
331 $oSearch->iSearchRank++;
332 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
333 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
334 $oSearch->iSearchRank += 2;
336 if (sizeof($aFullTokens)) {
337 $oSearch->iSearchRank++;
339 $aNewSearches[] = $oSearch;
341 // revert to the token version?
342 foreach ($aFullTokens as $aSearchTermToken) {
343 if (empty($aSearchTermToken['country_code'])
344 && empty($aSearchTermToken['lat'])
345 && empty($aSearchTermToken['class'])
347 $oSearch = clone $this;
348 $oSearch->iSearchRank++;
349 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
350 $aNewSearches[] = $oSearch;
356 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
357 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
359 $oSearch = clone $this;
360 $oSearch->iSearchRank++;
361 if (!sizeof($this->aName)) {
362 $oSearch->iSearchRank += 1;
364 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
365 $oSearch->iSearchRank += 2;
367 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
368 $oSearch->aName[$iWordID] = $iWordID;
370 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
372 $oSearch->iNamePhrase = $iPhrase;
373 $aNewSearches[] = $oSearch;
376 return $aNewSearches;
379 /////////// Query functions
383 * Query database for places that match this search.
385 * @param object $oDB Database connection to use.
386 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
387 * overall in a planet database.
388 * @param integer $iMinRank Minimum address rank to restrict
390 * @param integer $iMaxRank Maximum address rank to restrict
392 * @param integer $iLimit Maximum number of results.
394 * @return mixed[] An array with two fields: IDs contains the list of
395 * matching place IDs and houseNumber the houseNumber
396 * if appicable or -1 if not.
398 public function query(&$oDB, &$aWordFrequencyScores, $iMinRank, $iMaxRank, $iLimit)
403 if ($this->sCountryCode
404 && !sizeof($this->aName)
407 && !$this->oContext->hasNearPoint()
409 // Just looking for a country - look it up
410 if (4 >= $iMinRank && 4 <= $iMaxRank) {
411 $aResults = $this->queryCountry($oDB);
413 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
414 // Neither name nor address? Then we must be
415 // looking for a POI in a geographic area.
416 if ($this->oContext->isBoundedSearch()) {
417 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
419 } elseif ($this->iOperator == Operator::POSTCODE) {
420 // looking for postcode
421 $aResults = $this->queryPostcode($oDB, $iLimit);
424 // First search for places according to name and address.
425 $aResults = $this->queryNamedPlace(
427 $aWordFrequencyScores,
433 //now search for housenumber, if housenumber provided
434 if ($this->sHouseNumber && sizeof($aResults)) {
435 $aNamedPlaceIDs = $aResults;
436 $aResults = $this->queryHouseNumber($oDB, $aNamedPlaceIDs, $iLimit);
438 if (!sizeof($aResults) && $this->looksLikeFullAddress()) {
439 $aResults = $aNamedPlaceIDs;
443 // finally get POIs if requested
444 if ($this->sClass && sizeof($aResults)) {
445 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
450 echo "<br><b>Place IDs:</b> ";
451 var_dump(array_keys($aResults));
454 if (sizeof($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 if (CONST_Debug) var_dump($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;
469 echo "<br><b>Place IDs after postcode filtering:</b> ";
470 var_dump(array_keys($aResults));
480 private function queryCountry(&$oDB)
482 $sSQL = 'SELECT place_id FROM placex ';
483 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
484 $sSQL .= ' AND rank_search = 4';
485 if ($this->oContext->bViewboxBounded) {
486 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
488 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
490 if (CONST_Debug) var_dump($sSQL);
493 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
494 $aResults[$iPlaceId] = new Result($iPlaceId);
500 private function queryNearbyPoi(&$oDB, $iLimit)
502 if (!$this->sClass) {
506 $aDBResults = array();
507 $sPoiTable = $this->poiTable();
509 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
510 if (chksql($oDB->getOne($sSQL))) {
511 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
512 if ($this->oContext->sqlCountryList) {
513 $sSQL .= ' JOIN placex USING (place_id)';
515 if ($this->oContext->hasNearPoint()) {
516 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
517 } elseif ($this->oContext->bViewboxBounded) {
518 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
520 if ($this->oContext->sqlCountryList) {
521 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
523 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
524 if ($this->oContext->sqlViewboxCentre) {
525 $sSQL .= ' ORDER BY ST_Distance(';
526 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
527 } elseif ($this->oContext->hasNearPoint()) {
528 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
530 $sSQL .= " limit $iLimit";
531 if (CONST_Debug) var_dump($sSQL);
532 $aDBResults = chksql($oDB->getCol($sSQL));
535 if ($this->oContext->hasNearPoint()) {
536 $sSQL = 'SELECT place_id FROM placex WHERE ';
537 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
538 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
539 $sSQL .= ' AND linked_place_id is null';
540 if ($this->oContext->sqlCountryList) {
541 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
543 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
544 $sSQL .= " LIMIT $iLimit";
545 if (CONST_Debug) var_dump($sSQL);
546 $aDBResults = chksql($oDB->getCol($sSQL));
550 foreach ($aDBResults as $iPlaceId) {
551 $aResults[$iPlaceId] = new Result($iPlaceId);
557 private function queryPostcode(&$oDB, $iLimit)
559 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
561 if (sizeof($this->aAddress)) {
562 $sSQL .= ', search_name s ';
563 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
564 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
565 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
570 $sSQL .= "p.postcode = '".reset($this->aName)."'";
571 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
572 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
573 $sSQL .= " LIMIT $iLimit";
575 if (CONST_Debug) var_dump($sSQL);
578 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
579 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
585 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
590 if ($this->sHouseNumber && sizeof($this->aAddress)) {
591 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
593 $aOrder[0] .= 'EXISTS(';
594 $aOrder[0] .= ' SELECT place_id';
595 $aOrder[0] .= ' FROM placex';
596 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
597 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
598 $aOrder[0] .= ' LIMIT 1';
600 // also housenumbers from interpolation lines table are needed
601 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
602 $iHouseNumber = intval($this->sHouseNumber);
603 $aOrder[0] .= 'OR EXISTS(';
604 $aOrder[0] .= ' SELECT place_id ';
605 $aOrder[0] .= ' FROM location_property_osmline ';
606 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
607 $aOrder[0] .= ' AND startnumber is not NULL';
608 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
609 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
610 $aOrder[0] .= ' LIMIT 1';
613 $aOrder[0] .= ') DESC';
616 if (sizeof($this->aName)) {
617 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
619 if (sizeof($this->aAddress)) {
620 // For infrequent name terms disable index usage for address
621 if (CONST_Search_NameOnlySearchFrequencyThreshold
622 && sizeof($this->aName) == 1
623 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
624 < CONST_Search_NameOnlySearchFrequencyThreshold
626 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
628 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
632 $sCountryTerm = $this->countryCodeSQL('country_code');
634 $aTerms[] = $sCountryTerm;
637 if ($this->sHouseNumber) {
638 $aTerms[] = "address_rank between 16 and 27";
639 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
640 if ($iMinAddressRank > 0) {
641 $aTerms[] = "address_rank >= ".$iMinAddressRank;
643 if ($iMaxAddressRank < 30) {
644 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
648 if ($this->oContext->hasNearPoint()) {
649 $aTerms[] = $this->oContext->withinSQL('centroid');
650 $aOrder[] = $this->oContext->distanceSQL('centroid');
651 } elseif ($this->sPostcode) {
652 if (!sizeof($this->aAddress)) {
653 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
655 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
659 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
661 $aTerms[] = $sExcludeSQL;
664 if ($this->oContext->bViewboxBounded) {
665 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
668 if ($this->oContext->hasNearPoint()) {
669 $aOrder[] = $this->oContext->distanceSQL('centroid');
672 if ($this->sHouseNumber) {
673 $sImportanceSQL = '- abs(26 - address_rank) + 3';
675 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
677 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
678 $aOrder[] = "$sImportanceSQL DESC";
680 if (sizeof($this->aFullNameAddress)) {
681 $sExactMatchSQL = ' ( ';
682 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
683 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
684 $sExactMatchSQL .= ' INTERSECT ';
685 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
686 $sExactMatchSQL .= ' ) s';
687 $sExactMatchSQL .= ') as exactmatch';
688 $aOrder[] = 'exactmatch DESC';
690 $sExactMatchSQL = '0::int as exactmatch';
693 if ($this->sHouseNumber || $this->sClass) {
699 if (sizeof($aTerms)) {
700 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
701 $sSQL .= ' FROM search_name';
702 $sSQL .= ' WHERE '.join(' and ', $aTerms);
703 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
704 $sSQL .= ' LIMIT '.$iLimit;
706 if (CONST_Debug) var_dump($sSQL);
708 $aDBResults = chksql(
710 "Could not get places for search terms."
713 foreach ($aDBResults as $aResult) {
714 $oResult = new Result($aResult['place_id']);
715 $oResult->iExactMatches = $aResult['exactmatch'];
716 $aResults[$aResult['place_id']] = $oResult;
723 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
726 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
732 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
733 $sSQL = 'SELECT place_id FROM placex ';
734 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
735 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
736 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
737 $sSQL .= " LIMIT $iLimit";
739 if (CONST_Debug) var_dump($sSQL);
741 // XXX should inherit the exactMatches from its parent
742 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
743 $aResults[$iPlaceId] = new Result($iPlaceId);
746 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
747 $iHousenumber = intval($this->sHouseNumber);
748 if ($bIsIntHouseNumber && !sizeof($aResults)) {
749 // if nothing found, search in the interpolation line table
750 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
751 $sSQL .= ' WHERE startnumber is not NULL';
752 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
753 if ($iHousenumber % 2 == 0) {
754 // If housenumber is even, look for housenumber in streets
755 // with interpolationtype even or all.
756 $sSQL .= "interpolationtype='even'";
758 // Else look for housenumber with interpolationtype odd or all.
759 $sSQL .= "interpolationtype='odd'";
761 $sSQL .= " or interpolationtype='all') and ";
762 $sSQL .= $iHousenumber.">=startnumber and ";
763 $sSQL .= $iHousenumber."<=endnumber";
764 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
765 $sSQL .= " limit $iLimit";
767 if (CONST_Debug) var_dump($sSQL);
769 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
770 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
771 $oResult->iHouseNumber = $iHousenumber;
772 $aResults[$iPlaceId] = $oResult;
776 // If nothing found try the aux fallback table
777 if (CONST_Use_Aux_Location_data && !sizeof($aResults)) {
778 $sSQL = 'SELECT place_id FROM location_property_aux';
779 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
780 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
781 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
782 $sSQL .= " limit $iLimit";
784 if (CONST_Debug) var_dump($sSQL);
786 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
787 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
791 // If nothing found then search in Tiger data (location_property_tiger)
792 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && !sizeof($aResults)) {
793 $sSQL = 'SELECT place_id FROM location_property_tiger';
794 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
795 if ($iHousenumber % 2 == 0) {
796 $sSQL .= "interpolationtype='even'";
798 $sSQL .= "interpolationtype='odd'";
800 $sSQL .= " or interpolationtype='all') and ";
801 $sSQL .= $iHousenumber.">=startnumber and ";
802 $sSQL .= $iHousenumber."<=endnumber";
803 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
804 $sSQL .= " limit $iLimit";
806 if (CONST_Debug) var_dump($sSQL);
808 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
809 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
810 $oResult->iHouseNumber = $iHousenumber;
811 $aResults[$iPlaceId] = $oResult;
819 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
822 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
828 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
829 // If they were searching for a named class (i.e. 'Kings Head pub')
830 // then we might have an extra match
831 $sSQL = 'SELECT place_id FROM placex ';
832 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
833 $sSQL .= " AND class='".$this->sClass."' ";
834 $sSQL .= " AND type='".$this->sType."'";
835 $sSQL .= " AND linked_place_id is null";
836 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
837 $sSQL .= " ORDER BY rank_search ASC ";
838 $sSQL .= " LIMIT $iLimit";
840 if (CONST_Debug) var_dump($sSQL);
842 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
843 $aResults[$iPlaceId] = new Result($iPlaceId);
847 // NEAR and IN are handled the same
848 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
849 $sClassTable = $this->poiTable();
850 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
851 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
853 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
854 if (CONST_Debug) var_dump($sSQL);
855 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
857 // For state / country level searches the normal radius search doesn't work very well
859 if ($iMaxRank < 9 && $bCacheTable) {
860 // Try and get a polygon to search in instead
861 $sSQL = 'SELECT geometry FROM placex';
862 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
863 $sSQL .= " AND rank_search < $iMaxRank + 5";
864 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
865 $sSQL .= " ORDER BY rank_search ASC ";
867 if (CONST_Debug) var_dump($sSQL);
868 $sPlaceGeom = chksql($oDB->getOne($sSQL));
875 $sSQL = 'SELECT place_id FROM placex';
876 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
877 if (CONST_Debug) var_dump($sSQL);
878 $aPlaceIDs = chksql($oDB->getCol($sSQL));
879 $sPlaceIDs = join(',', $aPlaceIDs);
882 if ($sPlaceIDs || $sPlaceGeom) {
885 // More efficient - can make the range bigger
889 if ($this->oContext->hasNearPoint()) {
890 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
891 } elseif ($sPlaceIDs) {
892 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
893 } elseif ($sPlaceGeom) {
894 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
897 $sSQL = 'SELECT distinct i.place_id';
899 $sSQL .= ', i.order_term';
901 $sSQL .= ' from (SELECT l.place_id';
903 $sSQL .= ','.$sOrderBySQL.' as order_term';
905 $sSQL .= ' from '.$sClassTable.' as l';
908 $sSQL .= ",placex as f WHERE ";
909 $sSQL .= "f.place_id in ($sPlaceIDs) ";
910 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
911 } elseif ($sPlaceGeom) {
912 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
915 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
916 $sSQL .= 'limit 300) i ';
918 $sSQL .= 'order by order_term asc';
920 $sSQL .= " limit $iLimit";
922 if (CONST_Debug) var_dump($sSQL);
924 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
925 $aResults[$iPlaceId] = new Result($iPlaceId);
928 if ($this->oContext->hasNearPoint()) {
929 $fRange = $this->oContext->nearRadius();
933 if ($this->oContext->hasNearPoint()) {
934 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
936 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
939 $sSQL = 'SELECT distinct l.place_id';
941 $sSQL .= ','.$sOrderBySQL.' as orderterm';
943 $sSQL .= ' FROM placex as l, placex as f';
944 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
945 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
946 $sSQL .= " AND l.class='".$this->sClass."'";
947 $sSQL .= " AND l.type='".$this->sType."'";
948 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
950 $sSQL .= "ORDER BY orderterm ASC";
952 $sSQL .= " limit $iLimit";
954 if (CONST_Debug) var_dump($sSQL);
956 foreach (chksql($oDB->getCol($sSQL)) as $iPlaceId) {
957 $aResults[$iPlaceId] = new Result($iPlaceId);
966 private function poiTable()
968 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
971 private function countryCodeSQL($sVar)
973 if ($this->sCountryCode) {
974 return $sVar.' = \''.$this->sCountryCode."'";
976 if ($this->oContext->sqlCountryList) {
977 return $sVar.' in '.$this->oContext->sqlCountryList;
983 /////////// Sort functions
986 public static function bySearchRank($a, $b)
988 if ($a->iSearchRank == $b->iSearchRank) {
989 return $a->iOperator + strlen($a->sHouseNumber)
990 - $b->iOperator - strlen($b->sHouseNumber);
993 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
996 //////////// Debugging functions
999 public function dumpAsHtmlTableRow(&$aWordIDs)
1001 $kf = function ($k) use (&$aWordIDs) {
1002 return $aWordIDs[$k];
1006 echo "<td>$this->iSearchRank</td>";
1007 echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
1008 echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
1009 echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
1010 echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
1011 echo "<td>".$this->sCountryCode."</td>";
1012 echo "<td>".Operator::toString($this->iOperator)."</td>";
1013 echo "<td>".$this->sClass."</td>";
1014 echo "<td>".$this->sType."</td>";
1015 echo "<td>".$this->sPostcode."</td>";
1016 echo "<td>".$this->sHouseNumber."</td>";