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 /// True if the name is rare enough to force index use on name.
21 private $bRareName = false;
22 /// List of word ids making up the address of the object.
23 private $aAddress = array();
24 /// Subset of word ids of full words making up the address.
25 private $aFullNameAddress = array();
26 /// List of word ids that appear in the name but should be ignored.
27 private $aNameNonSearch = array();
28 /// List of word ids that appear in the address but should be ignored.
29 private $aAddressNonSearch = array();
30 /// Kind of search for special searches, see Nominatim::Operator.
31 private $iOperator = Operator::NONE;
32 /// Class of special feature to search for.
34 /// Type of special feature to search for.
36 /// Housenumber of the object.
37 private $sHouseNumber = '';
38 /// Postcode for the object.
39 private $sPostcode = '';
40 /// Global search constraints.
43 // Temporary values used while creating the search description.
45 /// Index of phrase currently processed.
46 private $iNamePhrase = -1;
49 * Create an empty search description.
51 * @param object $oContext Global context to use. Will be inherited by
52 * all derived search objects.
54 public function __construct($oContext)
56 $this->oContext = $oContext;
60 * Get current search rank.
62 * The higher the search rank the lower the likelihood that the
63 * search is a correct interpretation of the search query.
65 * @return integer Search rank.
67 public function getRank()
69 return $this->iSearchRank;
73 * Make this search a POI search.
75 * In a POI search, objects are not (only) searched by their name
76 * but also by the primary OSM key/value pair (class and type in Nominatim).
78 * @param integer $iOperator Type of POI search
79 * @param string $sClass Class (or OSM tag key) of POI.
80 * @param string $sType Type (or OSM tag value) of POI.
84 public function setPoiSearch($iOperator, $sClass, $sType)
86 $this->iOperator = $iOperator;
87 $this->sClass = $sClass;
88 $this->sType = $sType;
92 * Check if this might be a full address search.
94 * @return bool True if the search contains name, address and housenumber.
96 public function looksLikeFullAddress()
98 return (!empty($this->aName))
99 && (!empty($this->aAddress) || $this->sCountryCode)
100 && preg_match('/[0-9]+/', $this->sHouseNumber);
104 * Check if any operator is set.
106 * @return bool True, if this is a special search operation.
108 public function hasOperator()
110 return $this->iOperator != Operator::NONE;
114 * Extract key/value pairs from a query.
116 * Key/value pairs are recognised if they are of the form [<key>=<value>].
117 * If multiple terms of this kind are found then all terms are removed
118 * but only the first is used for search.
120 * @param string $sQuery Original query string.
122 * @return string The query string with the special search patterns removed.
124 public function extractKeyValuePairs($sQuery)
126 // Search for terms of kind [<key>=<value>].
128 '/\\[([\\w_]*)=([\\w_]*)\\]/',
134 foreach ($aSpecialTermsRaw as $aTerm) {
135 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
136 if (!$this->hasOperator()) {
137 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
145 * Check if the combination of parameters is sensible.
147 * @return bool True, if the search looks valid.
149 public function isValidSearch()
151 if (empty($this->aName)) {
152 if ($this->sHouseNumber) {
155 if (!$this->sClass && !$this->sCountryCode) {
163 /////////// Search building functions
167 * Derive new searches by adding a full term to the existing search.
169 * @param object $oSearchTerm Description of the token.
170 * @param bool $bHasPartial True if there are also tokens of partial terms
171 * with the same name.
172 * @param string $sPhraseType Type of phrase the token is contained in.
173 * @param bool $bFirstToken True if the token is at the beginning of the
175 * @param bool $bFirstPhrase True if the token is in the first phrase of
177 * @param bool $bLastToken True if the token is at the end of the query.
179 * @return SearchDescription[] List of derived search descriptions.
181 public function extendWithFullTerm($oSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken)
183 $aNewSearches = array();
185 if (($sPhraseType == '' || $sPhraseType == 'country')
186 && is_a($oSearchTerm, '\Nominatim\Token\Country')
188 if (!$this->sCountryCode) {
189 $oSearch = clone $this;
190 $oSearch->iSearchRank++;
191 $oSearch->sCountryCode = $oSearchTerm->sCountryCode;
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 && is_a($oSearchTerm, '\Nominatim\Token\Postcode')
202 if (!$this->sPostcode) {
203 // If we have structured search or this is the first term,
204 // make the postcode the primary search element.
205 if ($this->iOperator == Operator::NONE && $bFirstToken) {
206 $oSearch = clone $this;
207 $oSearch->iSearchRank++;
208 $oSearch->iOperator = Operator::POSTCODE;
209 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
211 array($oSearchTerm->iId => $oSearchTerm->sPostcode);
212 $aNewSearches[] = $oSearch;
215 // If we have a structured search or this is not the first term,
216 // add the postcode as an addendum.
217 if ($this->iOperator != Operator::POSTCODE
218 && ($sPhraseType == 'postalcode' || !empty($this->aName))
220 $oSearch = clone $this;
221 $oSearch->iSearchRank++;
222 $oSearch->sPostcode = $oSearchTerm->sPostcode;
223 $aNewSearches[] = $oSearch;
226 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
227 && is_a($oSearchTerm, '\Nominatim\Token\HouseNumber')
229 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
230 $oSearch = clone $this;
231 $oSearch->iSearchRank++;
232 $oSearch->sHouseNumber = $oSearchTerm->sToken;
233 // sanity check: if the housenumber is not mainly made
234 // up of numbers, add a penalty
235 if (preg_match('/\\d/', $oSearch->sHouseNumber) === 0
236 || preg_match_all('/[^0-9]/', $oSearch->sHouseNumber, $aMatches) > 2) {
237 $oSearch->iSearchRank++;
239 if (empty($oSearchTerm->iId)) {
240 $oSearch->iSearchRank++;
242 // also must not appear in the middle of the address
243 if (!empty($this->aAddress)
244 || (!empty($this->aAddressNonSearch))
247 $oSearch->iSearchRank++;
249 $aNewSearches[] = $oSearch;
250 // Housenumbers may appear in the name when the place has its own
252 if (($this->iNamePhrase >= 0 || empty($this->aName)) && empty($this->aAddress)) {
253 $oSearch = clone $this;
254 $oSearch->iSearchRank++;
255 $oSearch->aAddress = $this->aName;
256 $oSearch->aName = array($oSearchTerm->iId => $oSearchTerm->iId);
257 $aNewSearches[] = $oSearch;
260 } elseif ($sPhraseType == ''
261 && is_a($oSearchTerm, '\Nominatim\Token\SpecialTerm')
263 if ($this->iOperator == Operator::NONE) {
264 $oSearch = clone $this;
265 $oSearch->iSearchRank++;
267 $iOp = $oSearchTerm->iOperator;
268 if ($iOp == Operator::NONE) {
269 if (!empty($this->aName) || $this->oContext->isBoundedSearch()) {
270 $iOp = Operator::NAME;
272 $iOp = Operator::NEAR;
274 $oSearch->iSearchRank += 2;
277 $oSearch->setPoiSearch(
279 $oSearchTerm->sClass,
282 $aNewSearches[] = $oSearch;
284 } elseif ($sPhraseType != 'country'
285 && is_a($oSearchTerm, '\Nominatim\Token\Word')
287 $iWordID = $oSearchTerm->iId;
288 // Full words can only be a name if they appear at the beginning
289 // of the phrase. In structured search the name must forcably in
290 // the first phrase. In unstructured search it may be in a later
291 // phrase when the first phrase is a house number.
292 if (!empty($this->aName) || !($bFirstPhrase || $sPhraseType == '')) {
293 if (($sPhraseType == '' || !$bFirstPhrase) && !$bHasPartial) {
294 $oSearch = clone $this;
295 $oSearch->iSearchRank += 2;
296 $oSearch->aAddress[$iWordID] = $iWordID;
297 $aNewSearches[] = $oSearch;
299 $this->aFullNameAddress[$iWordID] = $iWordID;
302 $oSearch = clone $this;
303 $oSearch->iSearchRank++;
304 $oSearch->aName = array($iWordID => $iWordID);
305 if (CONST_Search_NameOnlySearchFrequencyThreshold) {
306 $oSearch->bRareName =
307 $oSearchTerm->iSearchNameCount
308 < CONST_Search_NameOnlySearchFrequencyThreshold;
310 $aNewSearches[] = $oSearch;
314 return $aNewSearches;
318 * Derive new searches by adding a partial term to the existing search.
320 * @param string $sToken Term for the token.
321 * @param object $oSearchTerm Description of the token.
322 * @param bool $bStructuredPhrases True if the search is structured.
323 * @param integer $iPhrase Number of the phrase the token is in.
324 * @param array[] $aFullTokens List of full term tokens with the
327 * @return SearchDescription[] List of derived search descriptions.
329 public function extendWithPartialTerm($sToken, $oSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
331 // Only allow name terms.
332 if (!(is_a($oSearchTerm, '\Nominatim\Token\Word'))) {
336 $aNewSearches = array();
337 $iWordID = $oSearchTerm->iId;
339 if ((!$bStructuredPhrases || $iPhrase > 0)
340 && (!empty($this->aName))
341 && strpos($sToken, ' ') === false
343 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
344 $oSearch = clone $this;
345 $oSearch->iSearchRank += 2;
346 $oSearch->aAddress[$iWordID] = $iWordID;
347 $aNewSearches[] = $oSearch;
349 $oSearch = clone $this;
350 $oSearch->iSearchRank++;
351 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
352 if (preg_match('#^[0-9]+$#', $sToken)) {
353 $oSearch->iSearchRank += 2;
355 if (!empty($aFullTokens)) {
356 $oSearch->iSearchRank++;
358 $aNewSearches[] = $oSearch;
360 // revert to the token version?
361 foreach ($aFullTokens as $oSearchTermToken) {
362 if (is_a($oSearchTermToken, '\Nominatim\Token\Word')) {
363 $oSearch = clone $this;
364 $oSearch->iSearchRank++;
365 $oSearch->aAddress[$oSearchTermToken->iId]
366 = $oSearchTermToken->iId;
367 $aNewSearches[] = $oSearch;
373 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
374 && (empty($this->aName) || $this->iNamePhrase == $iPhrase)
376 $oSearch = clone $this;
377 $oSearch->iSearchRank += 2;
378 if (empty($this->aName)) {
379 $oSearch->iSearchRank += 1;
381 if (preg_match('#^[0-9]+$#', $sToken)) {
382 $oSearch->iSearchRank += 2;
384 if ($oSearchTerm->iSearchNameCount < CONST_Max_Word_Frequency) {
385 if (empty($this->aName)
386 && CONST_Search_NameOnlySearchFrequencyThreshold
388 $oSearch->bRareName =
389 $oSearchTerm->iSearchNameCount
390 < CONST_Search_NameOnlySearchFrequencyThreshold;
392 $oSearch->bRareName = false;
394 $oSearch->aName[$iWordID] = $iWordID;
396 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
398 $oSearch->iNamePhrase = $iPhrase;
399 $aNewSearches[] = $oSearch;
402 return $aNewSearches;
405 /////////// Query functions
409 * Query database for places that match this search.
411 * @param object $oDB Nominatim::DB instance to use.
412 * @param integer $iMinRank Minimum address rank to restrict search to.
413 * @param integer $iMaxRank Maximum address rank to restrict search to.
414 * @param integer $iLimit Maximum number of results.
416 * @return mixed[] An array with two fields: IDs contains the list of
417 * matching place IDs and houseNumber the houseNumber
418 * if appicable or -1 if not.
420 public function query(&$oDB, $iMinRank, $iMaxRank, $iLimit)
425 if ($this->sCountryCode
426 && empty($this->aName)
429 && !$this->oContext->hasNearPoint()
431 // Just looking for a country - look it up
432 if (4 >= $iMinRank && 4 <= $iMaxRank) {
433 $aResults = $this->queryCountry($oDB);
435 } elseif (empty($this->aName) && empty($this->aAddress)) {
436 // Neither name nor address? Then we must be
437 // looking for a POI in a geographic area.
438 if ($this->oContext->isBoundedSearch()) {
439 $aResults = $this->queryNearbyPoi($oDB, $iLimit);
441 } elseif ($this->iOperator == Operator::POSTCODE) {
442 // looking for postcode
443 $aResults = $this->queryPostcode($oDB, $iLimit);
446 // First search for places according to name and address.
447 $aResults = $this->queryNamedPlace(
454 // Now search for housenumber, if housenumber provided. Can be zero.
455 if (($this->sHouseNumber || $this->sHouseNumber === '0') && !empty($aResults)) {
456 // Downgrade the rank of the street results, they are missing
458 foreach ($aResults as $oRes) {
459 $oRes->iResultRank++;
462 $aHnResults = $this->queryHouseNumber($oDB, $aResults);
464 if (!empty($aHnResults)) {
465 foreach ($aHnResults as $oRes) {
466 $aResults[$oRes->iId] = $oRes;
471 // finally get POIs if requested
472 if ($this->sClass && !empty($aResults)) {
473 $aResults = $this->queryPoiByOperator($oDB, $aResults, $iLimit);
477 Debug::printDebugTable('Place IDs', $aResults);
479 if (!empty($aResults) && $this->sPostcode) {
480 $sPlaceIds = Result::joinIdsByTable($aResults, Result::TABLE_PLACEX);
482 $sSQL = 'SELECT place_id FROM placex';
483 $sSQL .= ' WHERE place_id in ('.$sPlaceIds.')';
484 $sSQL .= " AND postcode != '".$this->sPostcode."'";
485 Debug::printSQL($sSQL);
486 $aFilteredPlaceIDs = $oDB->getCol($sSQL);
487 if ($aFilteredPlaceIDs) {
488 foreach ($aFilteredPlaceIDs as $iPlaceId) {
489 $aResults[$iPlaceId]->iResultRank++;
499 private function queryCountry(&$oDB)
501 $sSQL = 'SELECT place_id FROM placex ';
502 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
503 $sSQL .= ' AND rank_search = 4';
504 if ($this->oContext->bViewboxBounded) {
505 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
507 $sSQL .= ' ORDER BY st_area(geometry) DESC LIMIT 1';
509 Debug::printSQL($sSQL);
511 $iPlaceId = $oDB->getOne($sSQL);
515 $aResults[$iPlaceId] = new Result($iPlaceId);
521 private function queryNearbyPoi(&$oDB, $iLimit)
523 if (!$this->sClass) {
527 $aDBResults = array();
528 $sPoiTable = $this->poiTable();
530 if ($oDB->tableExists($sPoiTable)) {
531 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
532 if ($this->oContext->sqlCountryList) {
533 $sSQL .= ' JOIN placex USING (place_id)';
535 if ($this->oContext->hasNearPoint()) {
536 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
537 } elseif ($this->oContext->bViewboxBounded) {
538 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
540 if ($this->oContext->sqlCountryList) {
541 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
543 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
544 if ($this->oContext->sqlViewboxCentre) {
545 $sSQL .= ' ORDER BY ST_Distance(';
546 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
547 } elseif ($this->oContext->hasNearPoint()) {
548 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
550 $sSQL .= " LIMIT $iLimit";
551 Debug::printSQL($sSQL);
552 $aDBResults = $oDB->getCol($sSQL);
555 if ($this->oContext->hasNearPoint()) {
556 $sSQL = 'SELECT place_id FROM placex WHERE ';
557 $sSQL .= 'class = :class and type = :type';
558 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
559 $sSQL .= ' AND linked_place_id is null';
560 if ($this->oContext->sqlCountryList) {
561 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
563 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid').' ASC';
564 $sSQL .= " LIMIT $iLimit";
565 Debug::printSQL($sSQL);
566 $aDBResults = $oDB->getCol(
568 array(':class' => $this->sClass, ':type' => $this->sType)
573 foreach ($aDBResults as $iPlaceId) {
574 $aResults[$iPlaceId] = new Result($iPlaceId);
580 private function queryPostcode(&$oDB, $iLimit)
582 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
584 if (!empty($this->aAddress)) {
585 $sSQL .= ', search_name s ';
586 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
587 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
588 $sSQL .= ' @> '.$oDB->getArraySQL($this->aAddress).' AND ';
593 $sSQL .= "p.postcode = '".reset($this->aName)."'";
594 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
595 if ($this->oContext->bViewboxBounded) {
596 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
598 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
599 $sSQL .= " LIMIT $iLimit";
601 Debug::printSQL($sSQL);
604 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
605 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_POSTCODE);
611 private function queryNamedPlace(&$oDB, $iMinAddressRank, $iMaxAddressRank, $iLimit)
616 // Sort by existence of the requested house number but only if not
617 // too many results are expected for the street, i.e. if the result
618 // will be narrowed down by an address. Remeber that with ordering
619 // every single result has to be checked.
620 if ($this->sHouseNumber && (!empty($this->aAddress) || $this->sPostcode)) {
621 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
623 $aOrder[0] .= 'EXISTS(';
624 $aOrder[0] .= ' SELECT place_id';
625 $aOrder[0] .= ' FROM placex';
626 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
627 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
628 $aOrder[0] .= ' LIMIT 1';
630 // also housenumbers from interpolation lines table are needed
631 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
632 $iHouseNumber = intval($this->sHouseNumber);
633 $aOrder[0] .= 'OR EXISTS(';
634 $aOrder[0] .= ' SELECT place_id ';
635 $aOrder[0] .= ' FROM location_property_osmline ';
636 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
637 $aOrder[0] .= ' AND startnumber is not NULL';
638 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
639 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
640 $aOrder[0] .= ' LIMIT 1';
643 $aOrder[0] .= ') DESC';
646 if (!empty($this->aName)) {
647 $aTerms[] = 'name_vector @> '.$oDB->getArraySQL($this->aName);
649 if (!empty($this->aAddress)) {
650 // For infrequent name terms disable index usage for address
651 if ($this->bRareName) {
652 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.$oDB->getArraySQL($this->aAddress);
654 $aTerms[] = 'nameaddress_vector @> '.$oDB->getArraySQL($this->aAddress);
658 $sCountryTerm = $this->countryCodeSQL('country_code');
660 $aTerms[] = $sCountryTerm;
663 if ($this->sHouseNumber) {
664 $aTerms[] = 'address_rank between 16 and 30';
665 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
666 if ($iMinAddressRank > 0) {
667 $aTerms[] = "((address_rank between $iMinAddressRank and $iMaxAddressRank) or (search_rank between $iMinAddressRank and $iMaxAddressRank))";
671 if ($this->oContext->hasNearPoint()) {
672 $aTerms[] = $this->oContext->withinSQL('centroid');
673 $aOrder[] = $this->oContext->distanceSQL('centroid');
674 } elseif ($this->sPostcode) {
675 if (empty($this->aAddress)) {
676 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
678 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
682 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
684 $aTerms[] = $sExcludeSQL;
687 if ($this->oContext->bViewboxBounded) {
688 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
691 if ($this->oContext->hasNearPoint()) {
692 $aOrder[] = $this->oContext->distanceSQL('centroid');
695 if ($this->sHouseNumber) {
696 $sImportanceSQL = '- abs(26 - address_rank) + 3';
698 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75001-(search_rank::float/40) ELSE importance END)';
700 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
701 $aOrder[] = "$sImportanceSQL DESC";
703 if (!empty($this->aFullNameAddress)) {
704 $sExactMatchSQL = ' ( ';
705 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
706 $sExactMatchSQL .= ' SELECT unnest('.$oDB->getArraySQL($this->aFullNameAddress).')';
707 $sExactMatchSQL .= ' INTERSECT ';
708 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
709 $sExactMatchSQL .= ' ) s';
710 $sExactMatchSQL .= ') as exactmatch';
711 $aOrder[] = 'exactmatch DESC';
713 $sExactMatchSQL = '0::int as exactmatch';
716 if ($this->sHouseNumber || $this->sClass) {
722 if (!empty($aTerms)) {
723 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
724 $sSQL .= ' FROM search_name';
725 $sSQL .= ' WHERE '.join(' and ', $aTerms);
726 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
727 $sSQL .= ' LIMIT '.$iLimit;
729 Debug::printSQL($sSQL);
731 $aDBResults = $oDB->getAll($sSQL, null, 'Could not get places for search terms.');
733 foreach ($aDBResults as $aResult) {
734 $oResult = new Result($aResult['place_id']);
735 $oResult->iExactMatches = $aResult['exactmatch'];
736 $aResults[$aResult['place_id']] = $oResult;
743 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs)
746 $sPlaceIDs = Result::joinIdsByTable($aRoadPlaceIDs, Result::TABLE_PLACEX);
752 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
753 $sSQL = 'SELECT place_id FROM placex ';
754 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
755 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
756 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
758 Debug::printSQL($sSQL);
760 // XXX should inherit the exactMatches from its parent
761 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
762 $aResults[$iPlaceId] = new Result($iPlaceId);
765 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
766 $iHousenumber = intval($this->sHouseNumber);
767 if ($bIsIntHouseNumber && empty($aResults)) {
768 // if nothing found, search in the interpolation line table
769 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
770 $sSQL .= ' WHERE startnumber is not NULL';
771 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
772 if ($iHousenumber % 2 == 0) {
773 // If housenumber is even, look for housenumber in streets
774 // with interpolationtype even or all.
775 $sSQL .= "interpolationtype='even'";
777 // Else look for housenumber with interpolationtype odd or all.
778 $sSQL .= "interpolationtype='odd'";
780 $sSQL .= " or interpolationtype='all') and ";
781 $sSQL .= $iHousenumber.'>=startnumber and ';
782 $sSQL .= $iHousenumber.'<=endnumber';
783 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
785 Debug::printSQL($sSQL);
787 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
788 $oResult = new Result($iPlaceId, Result::TABLE_OSMLINE);
789 $oResult->iHouseNumber = $iHousenumber;
790 $aResults[$iPlaceId] = $oResult;
794 // If nothing found try the aux fallback table
795 if (CONST_Use_Aux_Location_data && empty($aResults)) {
796 $sSQL = 'SELECT place_id FROM location_property_aux';
797 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
798 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
799 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
801 Debug::printSQL($sSQL);
803 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
804 $aResults[$iPlaceId] = new Result($iPlaceId, Result::TABLE_AUX);
808 // If nothing found then search in Tiger data (location_property_tiger)
809 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber && empty($aResults)) {
810 $sSQL = 'SELECT place_id FROM location_property_tiger';
811 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
812 if ($iHousenumber % 2 == 0) {
813 $sSQL .= "interpolationtype='even'";
815 $sSQL .= "interpolationtype='odd'";
817 $sSQL .= " or interpolationtype='all') and ";
818 $sSQL .= $iHousenumber.'>=startnumber and ';
819 $sSQL .= $iHousenumber.'<=endnumber';
820 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
822 Debug::printSQL($sSQL);
824 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
825 $oResult = new Result($iPlaceId, Result::TABLE_TIGER);
826 $oResult->iHouseNumber = $iHousenumber;
827 $aResults[$iPlaceId] = $oResult;
835 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
838 $sPlaceIDs = Result::joinIdsByTable($aParentIDs, Result::TABLE_PLACEX);
844 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
845 // If they were searching for a named class (i.e. 'Kings Head pub')
846 // then we might have an extra match
847 $sSQL = 'SELECT place_id FROM placex ';
848 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
849 $sSQL .= " AND class='".$this->sClass."' ";
850 $sSQL .= " AND type='".$this->sType."'";
851 $sSQL .= ' AND linked_place_id is null';
852 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
853 $sSQL .= ' ORDER BY rank_search ASC ';
854 $sSQL .= " LIMIT $iLimit";
856 Debug::printSQL($sSQL);
858 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
859 $aResults[$iPlaceId] = new Result($iPlaceId);
863 // NEAR and IN are handled the same
864 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
865 $sClassTable = $this->poiTable();
866 $bCacheTable = $oDB->tableExists($sClassTable);
868 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
869 Debug::printSQL($sSQL);
870 $iMaxRank = (int) $oDB->getOne($sSQL);
872 // For state / country level searches the normal radius search doesn't work very well
874 if ($iMaxRank < 9 && $bCacheTable) {
875 // Try and get a polygon to search in instead
876 $sSQL = 'SELECT geometry FROM placex';
877 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
878 $sSQL .= " AND rank_search < $iMaxRank + 5";
879 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
880 $sSQL .= ' ORDER BY rank_search ASC ';
882 Debug::printSQL($sSQL);
883 $sPlaceGeom = $oDB->getOne($sSQL);
890 $sSQL = 'SELECT place_id FROM placex';
891 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
892 Debug::printSQL($sSQL);
893 $aPlaceIDs = $oDB->getCol($sSQL);
894 $sPlaceIDs = join(',', $aPlaceIDs);
897 if ($sPlaceIDs || $sPlaceGeom) {
900 // More efficient - can make the range bigger
904 if ($this->oContext->hasNearPoint()) {
905 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
906 } elseif ($sPlaceIDs) {
907 $sOrderBySQL = 'ST_Distance(l.centroid, f.geometry)';
908 } elseif ($sPlaceGeom) {
909 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
912 $sSQL = 'SELECT distinct i.place_id';
914 $sSQL .= ', i.order_term';
916 $sSQL .= ' from (SELECT l.place_id';
918 $sSQL .= ','.$sOrderBySQL.' as order_term';
920 $sSQL .= ' from '.$sClassTable.' as l';
923 $sSQL .= ',placex as f WHERE ';
924 $sSQL .= "f.place_id in ($sPlaceIDs) ";
925 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
926 } elseif ($sPlaceGeom) {
927 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
930 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
931 $sSQL .= 'limit 300) i ';
933 $sSQL .= 'order by order_term asc';
935 $sSQL .= " limit $iLimit";
937 Debug::printSQL($sSQL);
939 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
940 $aResults[$iPlaceId] = new Result($iPlaceId);
943 if ($this->oContext->hasNearPoint()) {
944 $fRange = $this->oContext->nearRadius();
948 if ($this->oContext->hasNearPoint()) {
949 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
951 $sOrderBySQL = 'ST_Distance(l.geometry, f.geometry)';
954 $sSQL = 'SELECT distinct l.place_id';
956 $sSQL .= ','.$sOrderBySQL.' as orderterm';
958 $sSQL .= ' FROM placex as l, placex as f';
959 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
960 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
961 $sSQL .= " AND l.class='".$this->sClass."'";
962 $sSQL .= " AND l.type='".$this->sType."'";
963 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
965 $sSQL .= 'ORDER BY orderterm ASC';
967 $sSQL .= " limit $iLimit";
969 Debug::printSQL($sSQL);
971 foreach ($oDB->getCol($sSQL) as $iPlaceId) {
972 $aResults[$iPlaceId] = new Result($iPlaceId);
981 private function poiTable()
983 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
986 private function countryCodeSQL($sVar)
988 if ($this->sCountryCode) {
989 return $sVar.' = \''.$this->sCountryCode."'";
991 if ($this->oContext->sqlCountryList) {
992 return $sVar.' in '.$this->oContext->sqlCountryList;
998 /////////// Sort functions
1001 public static function bySearchRank($a, $b)
1003 if ($a->iSearchRank == $b->iSearchRank) {
1004 return $a->iOperator + strlen($a->sHouseNumber)
1005 - $b->iOperator - strlen($b->sHouseNumber);
1008 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
1011 //////////// Debugging functions
1014 public function debugInfo()
1017 'Search rank' => $this->iSearchRank,
1018 'Country code' => $this->sCountryCode,
1019 'Name terms' => $this->aName,
1020 'Name terms (stop words)' => $this->aNameNonSearch,
1021 'Address terms' => $this->aAddress,
1022 'Address terms (stop words)' => $this->aAddressNonSearch,
1023 'Address terms (full words)' => $this->aFullNameAddress,
1024 'Special search' => $this->iOperator,
1025 'Class' => $this->sClass,
1026 'Type' => $this->sType,
1027 'House number' => $this->sHouseNumber,
1028 'Postcode' => $this->sPostcode
1032 public function dumpAsHtmlTableRow(&$aWordIDs)
1034 $kf = function ($k) use (&$aWordIDs) {
1035 return $aWordIDs[$k];
1039 echo "<td>$this->iSearchRank</td>";
1040 echo '<td>'.join(', ', array_map($kf, $this->aName)).'</td>';
1041 echo '<td>'.join(', ', array_map($kf, $this->aNameNonSearch)).'</td>';
1042 echo '<td>'.join(', ', array_map($kf, $this->aAddress)).'</td>';
1043 echo '<td>'.join(', ', array_map($kf, $this->aAddressNonSearch)).'</td>';
1044 echo '<td>'.$this->sCountryCode.'</td>';
1045 echo '<td>'.Operator::toString($this->iOperator).'</td>';
1046 echo '<td>'.$this->sClass.'</td>';
1047 echo '<td>'.$this->sType.'</td>';
1048 echo '<td>'.$this->sPostcode.'</td>';
1049 echo '<td>'.$this->sHouseNumber.'</td>';