5 require_once(CONST_BasePath.'/lib/SpecialSearchOperator.php');
6 require_once(CONST_BasePath.'/lib/SearchContext.php');
9 * Description of a single interpretation of a search query.
11 class SearchDescription
13 /// Ranking how well the description fits the query.
14 private $iSearchRank = 0;
15 /// Country code of country the result must belong to.
16 private $sCountryCode = '';
17 /// List of word ids making up the name of the object.
18 private $aName = array();
19 /// List of word ids making up the address of the object.
20 private $aAddress = array();
21 /// Subset of word ids of full words making up the address.
22 private $aFullNameAddress = array();
23 /// List of word ids that appear in the name but should be ignored.
24 private $aNameNonSearch = array();
25 /// List of word ids that appear in the address but should be ignored.
26 private $aAddressNonSearch = array();
27 /// Kind of search for special searches, see Nominatim::Operator.
28 private $iOperator = Operator::NONE;
29 /// Class of special feature to search for.
31 /// Type of special feature to search for.
33 /// Housenumber of the object.
34 private $sHouseNumber = '';
35 /// Postcode for the object.
36 private $sPostcode = '';
37 /// Global search constraints.
40 // Temporary values used while creating the search description.
42 /// Index of phrase currently processed.
43 private $iNamePhrase = -1;
47 * Create an empty search description.
49 * @param object $oContext Global context to use. Will be inherited by
50 * all derived search objects.
52 public function __construct($oContext)
54 $this->oContext = $oContext;
58 * Get current search rank.
60 * The higher the search rank the lower the likelyhood that the
61 * search is a correct interpretation of the search query.
63 * @return integer Search rank.
65 public function getRank()
67 return $this->iSearchRank;
71 * Increase the search rank.
73 * @param integer $iAddRank Number of ranks to increase.
77 public function addToRank($iAddRank)
79 $this->iSearchRank += $iAddRank;
80 return $this->iSearchRank;
84 * Make this search a POI search.
86 * In a POI search, objects are not (only) searched by their name
87 * but also by the primary OSM key/value pair (class and type in Nominatim).
89 * @param integer $iOperator Type of POI search
90 * @param string $sClass Class (or OSM tag key) of POI.
91 * @param string $sType Type (or OSM tag value) of POI.
95 public function setPoiSearch($iOperator, $sClass, $sType)
97 $this->iOperator = $iOperator;
98 $this->sClass = $sClass;
99 $this->sType = $sType;
103 * Check if this might be a full address search.
105 * @return bool True if the search contains name, address and housenumber.
107 public function looksLikeFullAddress()
109 return sizeof($this->aName)
110 && (sizeof($this->aAddress || $this->sCountryCode))
111 && preg_match('/[0-9]+/', $this->sHouseNumber);
115 * Check if any operator is set.
117 * @return bool True, if this is a special search operation.
119 public function hasOperator()
121 return $this->iOperator != Operator::NONE;
125 * Extract key/value pairs from a query.
127 * Key/value pairs are recognised if they are of the form [<key>=<value>].
128 * If multiple terms of this kind are found then all terms are removed
129 * but only the first is used for search.
131 * @param string $sQuery Original query string.
133 * @return string The query string with the special search patterns removed.
135 public function extractKeyValuePairs($sQuery)
137 // Search for terms of kind [<key>=<value>].
139 '/\\[([\\w_]*)=([\\w_]*)\\]/',
145 foreach ($aSpecialTermsRaw as $aTerm) {
146 $sQuery = str_replace($aTerm[0], ' ', $sQuery);
147 if (!$this->hasOperator()) {
148 $this->setPoiSearch(Operator::TYPE, $aTerm[1], $aTerm[2]);
156 * Check if the combination of parameters is sensible.
158 * @return bool True, if the search looks valid.
160 public function isValidSearch()
162 if (!sizeof($this->aName)) {
163 if ($this->sHouseNumber) {
166 if (!$this->sClass && !$this->sCountryCode) {
174 /////////// Search building functions
178 * Derive new searches by adding a full term to the existing search.
180 * @param mixed[] $aSearchTerm Description of the token.
181 * @param bool $bWordInQuery True, if the normalised version of the word
182 * is contained in the query.
183 * @param bool $bHasPartial True if there are also tokens of partial terms
184 * with the same name.
185 * @param string $sPhraseType Type of phrase the token is contained in.
186 * @param bool $bFirstToken True if the token is at the beginning of the
188 * @param bool $bFirstPhrase True if the token is in the first phrase of
190 * @param bool $bLastToken True if the token is at the end of the query.
191 * @param integer $iGlobalRank Changable ranking of all searches in the
194 * @return SearchDescription[] List of derived search descriptions.
196 public function extendWithFullTerm($aSearchTerm, $bWordInQuery, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken, &$iGlobalRank)
198 $aNewSearches = array();
200 if (($sPhraseType == '' || $sPhraseType == 'country')
201 && !empty($aSearchTerm['country_code'])
202 && $aSearchTerm['country_code'] != '0'
204 if (!$this->sCountryCode) {
205 $oSearch = clone $this;
206 $oSearch->iSearchRank++;
207 $oSearch->sCountryCode = $aSearchTerm['country_code'];
208 // Country is almost always at the end of the string
209 // - increase score for finding it anywhere else (optimisation)
211 $oSearch->iSearchRank += 5;
213 $aNewSearches[] = $oSearch;
215 // If it is at the beginning, we can be almost sure that
216 // the terms are in the wrong order. Increase score for all searches.
221 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
222 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
224 // We need to try the case where the postal code is the primary element
225 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
227 if (!$this->sPostcode && $bWordInQuery
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 == ''
277 && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null
279 // require a normalized exact match of the term
280 // if we have the normalizer version of the query
282 if ($this->iOperator == Operator::NONE
283 && (isset($aSearchTerm['word']) && $aSearchTerm['word'])
286 $oSearch = clone $this;
287 $oSearch->iSearchRank++;
289 $iOp = Operator::NEAR; // near == in for the moment
290 if ($aSearchTerm['operator'] == '') {
291 if (sizeof($this->aName)) {
292 $iOp = Operator::NAME;
294 $oSearch->iSearchRank += 2;
297 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
298 $aNewSearches[] = $oSearch;
300 } elseif (isset($aSearchTerm['word_id'])
301 && $aSearchTerm['word_id']
302 && $sPhraseType != 'country'
304 $iWordID = $aSearchTerm['word_id'];
305 if (sizeof($this->aName)) {
306 if (($sPhraseType == '' || !$bFirstPhrase)
307 && $sPhraseType != 'country'
310 $oSearch = clone $this;
311 $oSearch->iSearchRank++;
312 $oSearch->aAddress[$iWordID] = $iWordID;
313 $aNewSearches[] = $oSearch;
315 $this->aFullNameAddress[$iWordID] = $iWordID;
318 $oSearch = clone $this;
319 $oSearch->iSearchRank++;
320 $oSearch->aName = array($iWordID => $iWordID);
321 $aNewSearches[] = $oSearch;
325 return $aNewSearches;
329 * Derive new searches by adding a partial term to the existing search.
331 * @param mixed[] $aSearchTerm Description of the token.
332 * @param bool $bStructuredPhrases True if the search is structured.
333 * @param integer $iPhrase Number of the phrase the token is in.
334 * @param array[] $aFullTokens List of full term tokens with the
337 * @return SearchDescription[] List of derived search descriptions.
339 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
341 // Only allow name terms.
342 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
346 $aNewSearches = array();
347 $iWordID = $aSearchTerm['word_id'];
349 if ((!$bStructuredPhrases || $iPhrase > 0)
350 && sizeof($this->aName)
351 && strpos($aSearchTerm['word_token'], ' ') === false
353 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
354 $oSearch = clone $this;
355 $oSearch->iSearchRank++;
356 $oSearch->aAddress[$iWordID] = $iWordID;
357 $aNewSearches[] = $oSearch;
359 $oSearch = clone $this;
360 $oSearch->iSearchRank++;
361 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
362 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
363 $oSearch->iSearchRank += 2;
365 if (sizeof($aFullTokens)) {
366 $oSearch->iSearchRank++;
368 $aNewSearches[] = $oSearch;
370 // revert to the token version?
371 foreach ($aFullTokens as $aSearchTermToken) {
372 if (empty($aSearchTermToken['country_code'])
373 && empty($aSearchTermToken['lat'])
374 && empty($aSearchTermToken['class'])
376 $oSearch = clone $this;
377 $oSearch->iSearchRank++;
378 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
379 $aNewSearches[] = $oSearch;
385 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
386 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
388 $oSearch = clone $this;
389 $oSearch->iSearchRank++;
390 if (!sizeof($this->aName)) {
391 $oSearch->iSearchRank += 1;
393 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
394 $oSearch->iSearchRank += 2;
396 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
397 $oSearch->aName[$iWordID] = $iWordID;
399 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
401 $oSearch->iNamePhrase = $iPhrase;
402 $aNewSearches[] = $oSearch;
405 return $aNewSearches;
408 /////////// Query functions
412 * Query database for places that match this search.
414 * @param object $oDB Database connection to use.
415 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
416 * overall in a planet database.
417 * @param mixed[] $aExactMatchCache Saves number of exact matches.
418 * @param integer $iMinRank Minimum address rank to restrict
420 * @param integer $iMaxRank Maximum address rank to restrict
422 * @param integer $iLimit Maximum number of results.
424 * @return mixed[] An array with two fields: IDs contains the list of
425 * matching place IDs and houseNumber the houseNumber
426 * if appicable or -1 if not.
428 public function query(&$oDB, &$aWordFrequencyScores, &$aExactMatchCache, $iMinRank, $iMaxRank, $iLimit)
430 $aPlaceIDs = array();
433 if ($this->sCountryCode
434 && !sizeof($this->aName)
437 && !$this->oContext->hasNearPoint()
439 // Just looking for a country - look it up
440 if (4 >= $iMinRank && 4 <= $iMaxRank) {
441 $aPlaceIDs = $this->queryCountry($oDB);
443 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
444 // Neither name nor address? Then we must be
445 // looking for a POI in a geographic area.
446 if ($this->oContext->isBoundedSearch()) {
447 $aPlaceIDs = $this->queryNearbyPoi($oDB, $iLimit);
449 } elseif ($this->iOperator == Operator::POSTCODE) {
450 // looking for postcode
451 $aPlaceIDs = $this->queryPostcode($oDB, $iLimit);
454 // First search for places according to name and address.
455 $aNamedPlaceIDs = $this->queryNamedPlace(
457 $aWordFrequencyScores,
463 if (sizeof($aNamedPlaceIDs)) {
464 foreach ($aNamedPlaceIDs as $aRow) {
465 $aPlaceIDs[] = $aRow['place_id'];
466 $aExactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
470 //now search for housenumber, if housenumber provided
471 if ($this->sHouseNumber && sizeof($aPlaceIDs)) {
472 $aResult = $this->queryHouseNumber($oDB, $aPlaceIDs, $iLimit);
474 if (sizeof($aResult)) {
475 $iHousenumber = $aResult['iHouseNumber'];
476 $aPlaceIDs = $aResult['aPlaceIDs'];
477 } elseif (!$this->looksLikeFullAddress()) {
478 $aPlaceIDs = array();
482 // finally get POIs if requested
483 if ($this->sClass && sizeof($aPlaceIDs)) {
484 $aPlaceIDs = $this->queryPoiByOperator($oDB, $aPlaceIDs, $iLimit);
489 echo "<br><b>Place IDs:</b> ";
490 var_Dump($aPlaceIDs);
493 if (sizeof($aPlaceIDs) && $this->sPostcode) {
494 $sSQL = 'SELECT place_id FROM placex';
495 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
496 $sSQL .= " AND postcode = '".$this->sPostcode."'";
497 if (CONST_Debug) var_dump($sSQL);
498 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
499 if ($aFilteredPlaceIDs) {
500 $aPlaceIDs = $aFilteredPlaceIDs;
502 echo "<br><b>Place IDs after postcode filtering:</b> ";
503 var_Dump($aPlaceIDs);
508 return array('IDs' => $aPlaceIDs, 'houseNumber' => $iHousenumber);
512 private function queryCountry(&$oDB)
514 $sSQL = 'SELECT place_id FROM placex ';
515 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
516 $sSQL .= ' AND rank_search = 4';
517 if ($this->oContext->bViewboxBounded) {
518 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
520 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
522 if (CONST_Debug) var_dump($sSQL);
524 return chksql($oDB->getCol($sSQL));
527 private function queryNearbyPoi(&$oDB, $iLimit)
529 if (!$this->sClass) {
533 $sPoiTable = $this->poiTable();
535 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
536 if (chksql($oDB->getOne($sSQL))) {
537 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
538 if ($this->oContext->sqlCountryList) {
539 $sSQL .= ' JOIN placex USING (place_id)';
541 if ($this->oContext->hasNearPoint()) {
542 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
543 } elseif ($this->oContext->bViewboxBounded) {
544 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
546 if ($this->oContext->sqlCountryList) {
547 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
549 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
550 if ($this->oContext->sqlViewboxCentre) {
551 $sSQL .= ' ORDER BY ST_Distance(';
552 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
553 } elseif ($this->oContext->hasNearPoint()) {
554 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
556 $sSQL .= " limit $iLimit";
557 if (CONST_Debug) var_dump($sSQL);
558 return chksql($oDB->getCol($sSQL));
561 if ($this->oContext->hasNearPoint()) {
562 $sSQL = 'SELECT place_id FROM placex WHERE ';
563 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
564 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
565 $sSQL .= ' AND linked_place_id is null';
566 if ($this->oContext->sqlCountryList) {
567 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
569 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
570 $sSQL .= " LIMIT $iLimit";
571 if (CONST_Debug) var_dump($sSQL);
572 return chksql($oDB->getCol($sSQL));
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);
598 return chksql($oDB->getCol($sSQL));
601 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
606 if ($this->sHouseNumber && sizeof($this->aAddress)) {
607 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
609 $aOrder[0] .= 'EXISTS(';
610 $aOrder[0] .= ' SELECT place_id';
611 $aOrder[0] .= ' FROM placex';
612 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
613 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
614 $aOrder[0] .= ' LIMIT 1';
616 // also housenumbers from interpolation lines table are needed
617 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
618 $iHouseNumber = intval($this->sHouseNumber);
619 $aOrder[0] .= 'OR EXISTS(';
620 $aOrder[0] .= ' SELECT place_id ';
621 $aOrder[0] .= ' FROM location_property_osmline ';
622 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
623 $aOrder[0] .= ' AND startnumber is not NULL';
624 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
625 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
626 $aOrder[0] .= ' LIMIT 1';
629 $aOrder[0] .= ') DESC';
632 if (sizeof($this->aName)) {
633 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
635 if (sizeof($this->aAddress)) {
636 // For infrequent name terms disable index usage for address
637 if (CONST_Search_NameOnlySearchFrequencyThreshold
638 && sizeof($this->aName) == 1
639 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
640 < CONST_Search_NameOnlySearchFrequencyThreshold
642 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
644 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
648 $sCountryTerm = $this->countryCodeSQL('country_code');
650 $aTerms[] = $sCountryTerm;
653 if ($this->sHouseNumber) {
654 $aTerms[] = "address_rank between 16 and 27";
655 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
656 if ($iMinAddressRank > 0) {
657 $aTerms[] = "address_rank >= ".$iMinAddressRank;
659 if ($iMaxAddressRank < 30) {
660 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
664 if ($this->oContext->hasNearPoint()) {
665 $aTerms[] = $this->oContext->withinSQL('centroid');
666 $aOrder[] = $this->oContext->distanceSQL('centroid');
667 } elseif ($this->sPostcode) {
668 if (!sizeof($this->aAddress)) {
669 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
671 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
675 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
677 $aTerms[] = $sExcludeSQL;
680 if ($this->oContext->bViewboxBounded) {
681 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
684 if ($this->oContext->hasNearPoint()) {
685 $aOrder[] = $this->oContext->distanceSQL('centroid');
688 if ($this->sHouseNumber) {
689 $sImportanceSQL = '- abs(26 - address_rank) + 3';
691 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
693 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
694 $aOrder[] = "$sImportanceSQL DESC";
696 if (sizeof($this->aFullNameAddress)) {
697 $sExactMatchSQL = ' ( ';
698 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
699 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
700 $sExactMatchSQL .= ' INTERSECT ';
701 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
702 $sExactMatchSQL .= ' ) s';
703 $sExactMatchSQL .= ') as exactmatch';
704 $aOrder[] = 'exactmatch DESC';
706 $sExactMatchSQL = '0::int as exactmatch';
709 if ($this->sHouseNumber || $this->sClass) {
713 if (sizeof($aTerms)) {
714 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
715 $sSQL .= ' FROM search_name';
716 $sSQL .= ' WHERE '.join(' and ', $aTerms);
717 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
718 $sSQL .= ' LIMIT '.$iLimit;
720 if (CONST_Debug) var_dump($sSQL);
724 "Could not get places for search terms."
731 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
733 $sPlaceIDs = join(',', $aRoadPlaceIDs);
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 $aPlaceIDs = chksql($oDB->getCol($sSQL));
746 if (sizeof($aPlaceIDs)) {
747 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
750 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
751 $iHousenumber = intval($this->sHouseNumber);
752 if ($bIsIntHouseNumber) {
753 // if nothing found, search in the interpolation line table
754 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
755 $sSQL .= ' WHERE startnumber is not NULL';
756 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
757 if ($iHousenumber % 2 == 0) {
758 // If housenumber is even, look for housenumber in streets
759 // with interpolationtype even or all.
760 $sSQL .= "interpolationtype='even'";
762 // Else look for housenumber with interpolationtype odd or all.
763 $sSQL .= "interpolationtype='odd'";
765 $sSQL .= " or interpolationtype='all') and ";
766 $sSQL .= $iHousenumber.">=startnumber and ";
767 $sSQL .= $iHousenumber."<=endnumber";
768 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
769 $sSQL .= " limit $iLimit";
771 if (CONST_Debug) var_dump($sSQL);
773 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
775 if (sizeof($aPlaceIDs)) {
776 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
780 // If nothing found try the aux fallback table
781 if (CONST_Use_Aux_Location_data) {
782 $sSQL = 'SELECT place_id FROM location_property_aux';
783 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
784 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
785 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
786 $sSQL .= " limit $iLimit";
788 if (CONST_Debug) var_dump($sSQL);
790 $aPlaceIDs = chksql($oDB->getCol($sSQL));
792 if (sizeof($aPlaceIDs)) {
793 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
797 // If nothing found then search in Tiger data (location_property_tiger)
798 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber) {
799 $sSQL = 'SELECT distinct place_id FROM location_property_tiger';
800 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
801 if ($iHousenumber % 2 == 0) {
802 $sSQL .= "interpolationtype='even'";
804 $sSQL .= "interpolationtype='odd'";
806 $sSQL .= " or interpolationtype='all') and ";
807 $sSQL .= $iHousenumber.">=startnumber and ";
808 $sSQL .= $iHousenumber."<=endnumber";
809 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
810 $sSQL .= " limit $iLimit";
812 if (CONST_Debug) var_dump($sSQL);
814 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
816 if (sizeof($aPlaceIDs)) {
817 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
825 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
827 $sPlaceIDs = join(',', $aParentIDs);
828 $aClassPlaceIDs = array();
830 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
831 // If they were searching for a named class (i.e. 'Kings Head pub')
832 // then we might have an extra match
833 $sSQL = 'SELECT place_id FROM placex ';
834 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
835 $sSQL .= " AND class='".$this->sClass."' ";
836 $sSQL .= " AND type='".$this->sType."'";
837 $sSQL .= " AND linked_place_id is null";
838 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
839 $sSQL .= " ORDER BY rank_search ASC ";
840 $sSQL .= " LIMIT $iLimit";
842 if (CONST_Debug) var_dump($sSQL);
844 $aClassPlaceIDs = chksql($oDB->getCol($sSQL));
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 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
926 if ($this->oContext->hasNearPoint()) {
927 $fRange = $this->oContext->nearRadius();
931 if ($this->oContext->hasNearPoint()) {
932 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
934 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
937 $sSQL = 'SELECT distinct l.place_id';
939 $sSQL .= ','.$sOrderBySQL.' as orderterm';
941 $sSQL .= ' FROM placex as l, placex as f';
942 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
943 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
944 $sSQL .= " AND l.class='".$this->sClass."'";
945 $sSQL .= " AND l.type='".$this->sType."'";
946 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
948 $sSQL .= "ORDER BY orderterm ASC";
950 $sSQL .= " limit $iLimit";
952 if (CONST_Debug) var_dump($sSQL);
954 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
959 return $aClassPlaceIDs;
962 private function poiTable()
964 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
967 private function countryCodeSQL($sVar)
969 if ($this->sCountryCode) {
970 return $sVar.' = \''.$this->sCountryCode."'";
972 if ($this->oContext->sqlCountryList) {
973 return $sVar.' in '.$this->oContext->sqlCountryList;
979 /////////// Sort functions
982 public static function bySearchRank($a, $b)
984 if ($a->iSearchRank == $b->iSearchRank) {
985 return $a->iOperator + strlen($a->sHouseNumber)
986 - $b->iOperator - strlen($b->sHouseNumber);
989 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
992 //////////// Debugging functions
995 public function dumpAsHtmlTableRow(&$aWordIDs)
997 $kf = function ($k) use (&$aWordIDs) {
998 return $aWordIDs[$k];
1002 echo "<td>$this->iSearchRank</td>";
1003 echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
1004 echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
1005 echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
1006 echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
1007 echo "<td>".$this->sCountryCode."</td>";
1008 echo "<td>".Operator::toString($this->iOperator)."</td>";
1009 echo "<td>".$this->sClass."</td>";
1010 echo "<td>".$this->sType."</td>";
1011 echo "<td>".$this->sPostcode."</td>";
1012 echo "<td>".$this->sHouseNumber."</td>";