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 * @param string[] $aCountryCodes List of country codes.
160 * @return bool True, if the search looks valid.
162 public function isValidSearch(&$aCountryCodes)
164 if (!sizeof($this->aName)) {
165 if ($this->sHouseNumber) {
170 && $this->sCountryCode
171 && !in_array($this->sCountryCode, $aCountryCodes)
179 /////////// Search building functions
183 * Derive new searches by adding a full term to the existing search.
185 * @param mixed[] $aSearchTerm Description of the token.
186 * @param bool $bWordInQuery True, if the normalised version of the word
187 * is contained in the query.
188 * @param bool $bHasPartial True if there are also tokens of partial terms
189 * with the same name.
190 * @param string $sPhraseType Type of phrase the token is contained in.
191 * @param bool $bFirstToken True if the token is at the beginning of the
193 * @param bool $bFirstPhrase True if the token is in the first phrase of
195 * @param bool $bLastToken True if the token is at the end of the query.
196 * @param integer $iGlobalRank Changable ranking of all searches in the
199 * @return SearchDescription[] List of derived search descriptions.
201 public function extendWithFullTerm($aSearchTerm, $bWordInQuery, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken, &$iGlobalRank)
203 $aNewSearches = array();
205 if (($sPhraseType == '' || $sPhraseType == 'country')
206 && !empty($aSearchTerm['country_code'])
207 && $aSearchTerm['country_code'] != '0'
209 if (!$this->sCountryCode) {
210 $oSearch = clone $this;
211 $oSearch->iSearchRank++;
212 $oSearch->sCountryCode = $aSearchTerm['country_code'];
213 // Country is almost always at the end of the string
214 // - increase score for finding it anywhere else (optimisation)
216 $oSearch->iSearchRank += 5;
218 $aNewSearches[] = $oSearch;
220 // If it is at the beginning, we can be almost sure that
221 // the terms are in the wrong order. Increase score for all searches.
226 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
227 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
229 // We need to try the case where the postal code is the primary element
230 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
232 if (!$this->sPostcode && $bWordInQuery
233 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
235 // If we have structured search or this is the first term,
236 // make the postcode the primary search element.
237 if ($this->iOperator == Operator::NONE
238 && ($sPhraseType == 'postalcode' || $bFirstToken)
240 $oSearch = clone $this;
241 $oSearch->iSearchRank++;
242 $oSearch->iOperator = Operator::POSTCODE;
243 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
245 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
246 $aNewSearches[] = $oSearch;
249 // If we have a structured search or this is not the first term,
250 // add the postcode as an addendum.
251 if ($this->iOperator != Operator::POSTCODE
252 && ($sPhraseType == 'postalcode' || sizeof($this->aName))
254 $oSearch = clone $this;
255 $oSearch->iSearchRank++;
256 $oSearch->sPostcode = $aSearchTerm['word'];
257 $aNewSearches[] = $oSearch;
260 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
261 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
263 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
264 $oSearch = clone $this;
265 $oSearch->iSearchRank++;
266 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
267 // sanity check: if the housenumber is not mainly made
268 // up of numbers, add a penalty
269 if (preg_match_all("/[^0-9]/", $oSearch->sHouseNumber, $aMatches) > 2) {
270 $oSearch->iSearchRank++;
272 if (!isset($aSearchTerm['word_id'])) {
273 $oSearch->iSearchRank++;
275 // also must not appear in the middle of the address
276 if (sizeof($this->aAddress) || sizeof($this->aAddressNonSearch)) {
277 $oSearch->iSearchRank++;
279 $aNewSearches[] = $oSearch;
281 } elseif ($sPhraseType == ''
282 && $aSearchTerm['class'] !== '' && $aSearchTerm['class'] !== null
284 // require a normalized exact match of the term
285 // if we have the normalizer version of the query
287 if ($this->iOperator == Operator::NONE
288 && (isset($aSearchTerm['word']) && $aSearchTerm['word'])
291 $oSearch = clone $this;
292 $oSearch->iSearchRank++;
294 $iOp = Operator::NEAR; // near == in for the moment
295 if ($aSearchTerm['operator'] == '') {
296 if (sizeof($this->aName)) {
297 $iOp = Operator::NAME;
299 $oSearch->iSearchRank += 2;
302 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
303 $aNewSearches[] = $oSearch;
305 } elseif (isset($aSearchTerm['word_id']) && $aSearchTerm['word_id']) {
306 $iWordID = $aSearchTerm['word_id'];
307 if (sizeof($this->aName)) {
308 if (($sPhraseType == '' || !$bFirstPhrase)
309 && $sPhraseType != 'country'
312 $oSearch = clone $this;
313 $oSearch->iSearchRank++;
314 $oSearch->aAddress[$iWordID] = $iWordID;
315 $aNewSearches[] = $oSearch;
317 $this->aFullNameAddress[$iWordID] = $iWordID;
320 $oSearch = clone $this;
321 $oSearch->iSearchRank++;
322 $oSearch->aName = array($iWordID => $iWordID);
323 $aNewSearches[] = $oSearch;
327 return $aNewSearches;
331 * Derive new searches by adding a partial term to the existing search.
333 * @param mixed[] $aSearchTerm Description of the token.
334 * @param bool $bStructuredPhrases True if the search is structured.
335 * @param integer $iPhrase Number of the phrase the token is in.
336 * @param array[] $aFullTokens List of full term tokens with the
339 * @return SearchDescription[] List of derived search descriptions.
341 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
343 // Only allow name terms.
344 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
348 $aNewSearches = array();
349 $iWordID = $aSearchTerm['word_id'];
351 if ((!$bStructuredPhrases || $iPhrase > 0)
352 && sizeof($this->aName)
353 && strpos($aSearchTerm['word_token'], ' ') === false
355 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
356 $oSearch = clone $this;
357 $oSearch->iSearchRank++;
358 $oSearch->aAddress[$iWordID] = $iWordID;
359 $aNewSearches[] = $oSearch;
361 $oSearch = clone $this;
362 $oSearch->iSearchRank++;
363 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
364 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
365 $oSearch->iSearchRank += 2;
367 if (sizeof($aFullTokens)) {
368 $oSearch->iSearchRank++;
370 $aNewSearches[] = $oSearch;
372 // revert to the token version?
373 foreach ($aFullTokens as $aSearchTermToken) {
374 if (empty($aSearchTermToken['country_code'])
375 && empty($aSearchTermToken['lat'])
376 && empty($aSearchTermToken['class'])
378 $oSearch = clone $this;
379 $oSearch->iSearchRank++;
380 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
381 $aNewSearches[] = $oSearch;
387 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
388 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
390 $oSearch = clone $this;
391 $oSearch->iSearchRank++;
392 if (!sizeof($this->aName)) {
393 $oSearch->iSearchRank += 1;
395 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
396 $oSearch->iSearchRank += 2;
398 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
399 $oSearch->aName[$iWordID] = $iWordID;
401 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
403 $oSearch->iNamePhrase = $iPhrase;
404 $aNewSearches[] = $oSearch;
407 return $aNewSearches;
410 /////////// Query functions
414 * Query database for places that match this search.
416 * @param object $oDB Database connection to use.
417 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
418 * overall in a planet database.
419 * @param mixed[] $aExactMatchCache Saves number of exact matches.
420 * @param integer $iMinRank Minimum address rank to restrict
422 * @param integer $iMaxRank Maximum address rank to restrict
424 * @param integer $iLimit Maximum number of results.
426 * @return mixed[] An array with two fields: IDs contains the list of
427 * matching place IDs and houseNumber the houseNumber
428 * if appicable or -1 if not.
430 public function query(&$oDB, &$aWordFrequencyScores, &$aExactMatchCache, $iMinRank, $iMaxRank, $iLimit)
432 $aPlaceIDs = array();
435 if ($this->sCountryCode
436 && !sizeof($this->aName)
439 && !$this->oContext->hasNearPoint()
441 // Just looking for a country - look it up
442 if (4 >= $iMinRank && 4 <= $iMaxRank) {
443 $aPlaceIDs = $this->queryCountry($oDB);
445 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
446 // Neither name nor address? Then we must be
447 // looking for a POI in a geographic area.
448 if ($this->oContext->isBoundedSearch()) {
449 $aPlaceIDs = $this->queryNearbyPoi($oDB, $iLimit);
451 } elseif ($this->iOperator == Operator::POSTCODE) {
452 // looking for postcode
453 $aPlaceIDs = $this->queryPostcode($oDB, $iLimit);
456 // First search for places according to name and address.
457 $aNamedPlaceIDs = $this->queryNamedPlace(
459 $aWordFrequencyScores,
465 if (sizeof($aNamedPlaceIDs)) {
466 foreach ($aNamedPlaceIDs as $aRow) {
467 $aPlaceIDs[] = $aRow['place_id'];
468 $aExactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
472 //now search for housenumber, if housenumber provided
473 if ($this->sHouseNumber && sizeof($aPlaceIDs)) {
474 $aResult = $this->queryHouseNumber($oDB, $aPlaceIDs, $iLimit);
476 if (sizeof($aResult)) {
477 $iHousenumber = $aResult['iHouseNumber'];
478 $aPlaceIDs = $aResult['aPlaceIDs'];
479 } elseif (!$this->looksLikeFullAddress()) {
480 $aPlaceIDs = array();
484 // finally get POIs if requested
485 if ($this->sClass && sizeof($aPlaceIDs)) {
486 $aPlaceIDs = $this->queryPoiByOperator($oDB, $aPlaceIDs, $iLimit);
491 echo "<br><b>Place IDs:</b> ";
492 var_Dump($aPlaceIDs);
495 if (sizeof($aPlaceIDs) && $this->sPostcode) {
496 $sSQL = 'SELECT place_id FROM placex';
497 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
498 $sSQL .= " AND postcode = '".$this->sPostcode."'";
499 if (CONST_Debug) var_dump($sSQL);
500 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
501 if ($aFilteredPlaceIDs) {
502 $aPlaceIDs = $aFilteredPlaceIDs;
504 echo "<br><b>Place IDs after postcode filtering:</b> ";
505 var_Dump($aPlaceIDs);
510 return array('IDs' => $aPlaceIDs, 'houseNumber' => $iHousenumber);
514 private function queryCountry(&$oDB)
516 $sSQL = 'SELECT place_id FROM placex ';
517 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
518 $sSQL .= ' AND rank_search = 4';
519 if ($this->oContext->bViewboxBounded) {
520 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
522 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
524 if (CONST_Debug) var_dump($sSQL);
526 return chksql($oDB->getCol($sSQL));
529 private function queryNearbyPoi(&$oDB, $iLimit)
531 if (!$this->sClass) {
535 $sPoiTable = $this->poiTable();
537 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
538 if (chksql($oDB->getOne($sSQL))) {
539 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
540 if ($this->oContext->sqlCountryList) {
541 $sSQL .= ' JOIN placex USING (place_id)';
543 if ($this->oContext->hasNearPoint()) {
544 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
545 } elseif ($this->oContext->bViewboxBounded) {
546 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
548 if ($this->oContext->sqlCountryList) {
549 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
551 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
552 if ($this->oContext->sqlViewboxCentre) {
553 $sSQL .= ' ORDER BY ST_Distance(';
554 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
555 } elseif ($this->oContext->hasNearPoint()) {
556 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
558 $sSQL .= " limit $iLimit";
559 if (CONST_Debug) var_dump($sSQL);
560 return chksql($oDB->getCol($sSQL));
563 if ($this->oContext->hasNearPoint()) {
564 $sSQL = 'SELECT place_id FROM placex WHERE ';
565 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
566 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
567 $sSQL .= ' AND linked_place_id is null';
568 if ($this->oContext->sqlCountryList) {
569 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
571 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
572 $sSQL .= " LIMIT $iLimit";
573 if (CONST_Debug) var_dump($sSQL);
574 return chksql($oDB->getCol($sSQL));
580 private function queryPostcode(&$oDB, $iLimit)
582 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
584 if (sizeof($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 .= ' @> '.getArraySQL($this->aAddress).' AND ';
593 $sSQL .= "p.postcode = '".reset($this->aName)."'";
594 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
595 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
596 $sSQL .= " LIMIT $iLimit";
598 if (CONST_Debug) var_dump($sSQL);
600 return chksql($oDB->getCol($sSQL));
603 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
608 if ($this->sHouseNumber && sizeof($this->aAddress)) {
609 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
611 $aOrder[0] .= 'EXISTS(';
612 $aOrder[0] .= ' SELECT place_id';
613 $aOrder[0] .= ' FROM placex';
614 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
615 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
616 $aOrder[0] .= ' LIMIT 1';
618 // also housenumbers from interpolation lines table are needed
619 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
620 $iHouseNumber = intval($this->sHouseNumber);
621 $aOrder[0] .= 'OR EXISTS(';
622 $aOrder[0] .= ' SELECT place_id ';
623 $aOrder[0] .= ' FROM location_property_osmline ';
624 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
625 $aOrder[0] .= ' AND startnumber is not NULL';
626 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
627 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
628 $aOrder[0] .= ' LIMIT 1';
631 $aOrder[0] .= ') DESC';
634 if (sizeof($this->aName)) {
635 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
637 if (sizeof($this->aAddress)) {
638 // For infrequent name terms disable index usage for address
639 if (CONST_Search_NameOnlySearchFrequencyThreshold
640 && sizeof($this->aName) == 1
641 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
642 < CONST_Search_NameOnlySearchFrequencyThreshold
644 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
646 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
650 $sCountryTerm = $this->countryCodeSQL('country_code');
652 $aTerms[] = $sCountryTerm;
655 if ($this->sHouseNumber) {
656 $aTerms[] = "address_rank between 16 and 27";
657 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
658 if ($iMinAddressRank > 0) {
659 $aTerms[] = "address_rank >= ".$iMinAddressRank;
661 if ($iMaxAddressRank < 30) {
662 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
666 if ($this->oContext->hasNearPoint()) {
667 $aTerms[] = $this->oContext->withinSQL('centroid');
668 $aOrder[] = $this->oContext->distanceSQL('centroid');
669 } elseif ($this->sPostcode) {
670 if (!sizeof($this->aAddress)) {
671 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
673 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
677 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
679 $aTerms[] = $sExcludeSQL;
682 if ($this->oContext->bViewboxBounded) {
683 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
686 if ($this->oContext->hasNearPoint()) {
687 $aOrder[] = $this->oContext->distanceSQL('centroid');
690 if ($this->sHouseNumber) {
691 $sImportanceSQL = '- abs(26 - address_rank) + 3';
693 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
695 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
696 $aOrder[] = "$sImportanceSQL DESC";
698 if (sizeof($this->aFullNameAddress)) {
699 $sExactMatchSQL = ' ( ';
700 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
701 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
702 $sExactMatchSQL .= ' INTERSECT ';
703 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
704 $sExactMatchSQL .= ' ) s';
705 $sExactMatchSQL .= ') as exactmatch';
706 $aOrder[] = 'exactmatch DESC';
708 $sExactMatchSQL = '0::int as exactmatch';
711 if ($this->sHouseNumber || $this->sClass) {
715 if (sizeof($aTerms)) {
716 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
717 $sSQL .= ' FROM search_name';
718 $sSQL .= ' WHERE '.join(' and ', $aTerms);
719 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
720 $sSQL .= ' LIMIT '.$iLimit;
722 if (CONST_Debug) var_dump($sSQL);
726 "Could not get places for search terms."
733 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
735 $sPlaceIDs = join(',', $aRoadPlaceIDs);
737 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
738 $sSQL = 'SELECT place_id FROM placex ';
739 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
740 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
741 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
742 $sSQL .= " LIMIT $iLimit";
744 if (CONST_Debug) var_dump($sSQL);
746 $aPlaceIDs = chksql($oDB->getCol($sSQL));
748 if (sizeof($aPlaceIDs)) {
749 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
752 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
753 $iHousenumber = intval($this->sHouseNumber);
754 if ($bIsIntHouseNumber) {
755 // if nothing found, search in the interpolation line table
756 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
757 $sSQL .= ' WHERE startnumber is not NULL';
758 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
759 if ($iHousenumber % 2 == 0) {
760 // If housenumber is even, look for housenumber in streets
761 // with interpolationtype even or all.
762 $sSQL .= "interpolationtype='even'";
764 // Else look for housenumber with interpolationtype odd or all.
765 $sSQL .= "interpolationtype='odd'";
767 $sSQL .= " or interpolationtype='all') and ";
768 $sSQL .= $iHousenumber.">=startnumber and ";
769 $sSQL .= $iHousenumber."<=endnumber";
770 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
771 $sSQL .= " limit $iLimit";
773 if (CONST_Debug) var_dump($sSQL);
775 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
777 if (sizeof($aPlaceIDs)) {
778 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
782 // If nothing found try the aux fallback table
783 if (CONST_Use_Aux_Location_data) {
784 $sSQL = 'SELECT place_id FROM location_property_aux';
785 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
786 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
787 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
788 $sSQL .= " limit $iLimit";
790 if (CONST_Debug) var_dump($sSQL);
792 $aPlaceIDs = chksql($oDB->getCol($sSQL));
794 if (sizeof($aPlaceIDs)) {
795 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
799 // If nothing found then search in Tiger data (location_property_tiger)
800 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber) {
801 $sSQL = 'SELECT distinct place_id FROM location_property_tiger';
802 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
803 if ($iHousenumber % 2 == 0) {
804 $sSQL .= "interpolationtype='even'";
806 $sSQL .= "interpolationtype='odd'";
808 $sSQL .= " or interpolationtype='all') and ";
809 $sSQL .= $iHousenumber.">=startnumber and ";
810 $sSQL .= $iHousenumber."<=endnumber";
811 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
812 $sSQL .= " limit $iLimit";
814 if (CONST_Debug) var_dump($sSQL);
816 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
818 if (sizeof($aPlaceIDs)) {
819 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
827 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
829 $sPlaceIDs = join(',', $aParentIDs);
830 $aClassPlaceIDs = array();
832 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
833 // If they were searching for a named class (i.e. 'Kings Head pub')
834 // then we might have an extra match
835 $sSQL = 'SELECT place_id FROM placex ';
836 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
837 $sSQL .= " AND class='".$this->sClass."' ";
838 $sSQL .= " AND type='".$this->sType."'";
839 $sSQL .= " AND linked_place_id is null";
840 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
841 $sSQL .= " ORDER BY rank_search ASC ";
842 $sSQL .= " LIMIT $iLimit";
844 if (CONST_Debug) var_dump($sSQL);
846 $aClassPlaceIDs = chksql($oDB->getCol($sSQL));
849 // NEAR and IN are handled the same
850 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
851 $sClassTable = $this->poiTable();
852 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
853 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
855 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
856 if (CONST_Debug) var_dump($sSQL);
857 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
859 // For state / country level searches the normal radius search doesn't work very well
861 if ($iMaxRank < 9 && $bCacheTable) {
862 // Try and get a polygon to search in instead
863 $sSQL = 'SELECT geometry FROM placex';
864 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
865 $sSQL .= " AND rank_search < $iMaxRank + 5";
866 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
867 $sSQL .= " ORDER BY rank_search ASC ";
869 if (CONST_Debug) var_dump($sSQL);
870 $sPlaceGeom = chksql($oDB->getOne($sSQL));
877 $sSQL = 'SELECT place_id FROM placex';
878 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
879 if (CONST_Debug) var_dump($sSQL);
880 $aPlaceIDs = chksql($oDB->getCol($sSQL));
881 $sPlaceIDs = join(',', $aPlaceIDs);
884 if ($sPlaceIDs || $sPlaceGeom) {
887 // More efficient - can make the range bigger
891 if ($this->oContext->hasNearPoint()) {
892 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
893 } elseif ($sPlaceIDs) {
894 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
895 } elseif ($sPlaceGeom) {
896 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
899 $sSQL = 'SELECT distinct i.place_id';
901 $sSQL .= ', i.order_term';
903 $sSQL .= ' from (SELECT l.place_id';
905 $sSQL .= ','.$sOrderBySQL.' as order_term';
907 $sSQL .= ' from '.$sClassTable.' as l';
910 $sSQL .= ",placex as f WHERE ";
911 $sSQL .= "f.place_id in ($sPlaceIDs) ";
912 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
913 } elseif ($sPlaceGeom) {
914 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
917 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
918 $sSQL .= 'limit 300) i ';
920 $sSQL .= 'order by order_term asc';
922 $sSQL .= " limit $iLimit";
924 if (CONST_Debug) var_dump($sSQL);
926 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
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 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
961 return $aClassPlaceIDs;
964 private function poiTable()
966 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
969 private function countryCodeSQL($sVar)
971 if ($this->sCountryCode) {
972 return $sVar.' = \''.$this->sCountryCode."'";
974 if ($this->oContext->sqlCountryList) {
975 return $sVar.' in '.$this->oContext->sqlCountryList;
981 /////////// Sort functions
984 public static function bySearchRank($a, $b)
986 if ($a->iSearchRank == $b->iSearchRank) {
987 return $a->iOperator + strlen($a->sHouseNumber)
988 - $b->iOperator - strlen($b->sHouseNumber);
991 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
994 //////////// Debugging functions
997 public function dumpAsHtmlTableRow(&$aWordIDs)
999 $kf = function ($k) use (&$aWordIDs) {
1000 return $aWordIDs[$k];
1004 echo "<td>$this->iSearchRank</td>";
1005 echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
1006 echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
1007 echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
1008 echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
1009 echo "<td>".$this->sCountryCode."</td>";
1010 echo "<td>".Operator::toString($this->iOperator)."</td>";
1011 echo "<td>".$this->sClass."</td>";
1012 echo "<td>".$this->sType."</td>";
1013 echo "<td>".$this->sPostcode."</td>";
1014 echo "<td>".$this->sHouseNumber."</td>";