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 $bHasPartial True if there are also tokens of partial terms
182 * with the same name.
183 * @param string $sPhraseType Type of phrase the token is contained in.
184 * @param bool $bFirstToken True if the token is at the beginning of the
186 * @param bool $bFirstPhrase True if the token is in the first phrase of
188 * @param bool $bLastToken True if the token is at the end of the query.
189 * @param integer $iGlobalRank Changable ranking of all searches in the
192 * @return SearchDescription[] List of derived search descriptions.
194 public function extendWithFullTerm($aSearchTerm, $bHasPartial, $sPhraseType, $bFirstToken, $bFirstPhrase, $bLastToken, &$iGlobalRank)
196 $aNewSearches = array();
198 if (($sPhraseType == '' || $sPhraseType == 'country')
199 && !empty($aSearchTerm['country_code'])
200 && $aSearchTerm['country_code'] != '0'
202 if (!$this->sCountryCode) {
203 $oSearch = clone $this;
204 $oSearch->iSearchRank++;
205 $oSearch->sCountryCode = $aSearchTerm['country_code'];
206 // Country is almost always at the end of the string
207 // - increase score for finding it anywhere else (optimisation)
209 $oSearch->iSearchRank += 5;
211 $aNewSearches[] = $oSearch;
213 // If it is at the beginning, we can be almost sure that
214 // the terms are in the wrong order. Increase score for all searches.
219 } elseif (($sPhraseType == '' || $sPhraseType == 'postalcode')
220 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'postcode'
222 // We need to try the case where the postal code is the primary element
223 // (i.e. no way to tell if it is (postalcode, city) OR (city, postalcode)
225 if (!$this->sPostcode
226 && $aSearchTerm['word']
227 && pg_escape_string($aSearchTerm['word']) == $aSearchTerm['word']
229 // If we have structured search or this is the first term,
230 // make the postcode the primary search element.
231 if ($this->iOperator == Operator::NONE
232 && ($sPhraseType == 'postalcode' || $bFirstToken)
234 $oSearch = clone $this;
235 $oSearch->iSearchRank++;
236 $oSearch->iOperator = Operator::POSTCODE;
237 $oSearch->aAddress = array_merge($this->aAddress, $this->aName);
239 array($aSearchTerm['word_id'] => $aSearchTerm['word']);
240 $aNewSearches[] = $oSearch;
243 // If we have a structured search or this is not the first term,
244 // add the postcode as an addendum.
245 if ($this->iOperator != Operator::POSTCODE
246 && ($sPhraseType == 'postalcode' || sizeof($this->aName))
248 $oSearch = clone $this;
249 $oSearch->iSearchRank++;
250 $oSearch->sPostcode = $aSearchTerm['word'];
251 $aNewSearches[] = $oSearch;
254 } elseif (($sPhraseType == '' || $sPhraseType == 'street')
255 && $aSearchTerm['class'] == 'place' && $aSearchTerm['type'] == 'house'
257 if (!$this->sHouseNumber && $this->iOperator != Operator::POSTCODE) {
258 $oSearch = clone $this;
259 $oSearch->iSearchRank++;
260 $oSearch->sHouseNumber = trim($aSearchTerm['word_token']);
261 // sanity check: if the housenumber is not mainly made
262 // up of numbers, add a penalty
263 if (preg_match_all("/[^0-9]/", $oSearch->sHouseNumber, $aMatches) > 2) {
264 $oSearch->iSearchRank++;
266 if (!isset($aSearchTerm['word_id'])) {
267 $oSearch->iSearchRank++;
269 // also must not appear in the middle of the address
270 if (sizeof($this->aAddress) || sizeof($this->aAddressNonSearch)) {
271 $oSearch->iSearchRank++;
273 $aNewSearches[] = $oSearch;
275 } elseif ($sPhraseType == '' && $aSearchTerm['class']) {
276 if ($this->iOperator == Operator::NONE) {
277 $oSearch = clone $this;
278 $oSearch->iSearchRank++;
280 $iOp = Operator::NEAR; // near == in for the moment
281 if ($aSearchTerm['operator'] == '') {
282 if (sizeof($this->aName)) {
283 $iOp = Operator::NAME;
285 $oSearch->iSearchRank += 2;
288 $oSearch->setPoiSearch($iOp, $aSearchTerm['class'], $aSearchTerm['type']);
289 $aNewSearches[] = $oSearch;
291 } elseif (isset($aSearchTerm['word_id'])
292 && $aSearchTerm['word_id']
293 && $sPhraseType != 'country'
295 $iWordID = $aSearchTerm['word_id'];
296 if (sizeof($this->aName)) {
297 if (($sPhraseType == '' || !$bFirstPhrase)
298 && $sPhraseType != 'country'
301 $oSearch = clone $this;
302 $oSearch->iSearchRank++;
303 $oSearch->aAddress[$iWordID] = $iWordID;
304 $aNewSearches[] = $oSearch;
306 $this->aFullNameAddress[$iWordID] = $iWordID;
309 $oSearch = clone $this;
310 $oSearch->iSearchRank++;
311 $oSearch->aName = array($iWordID => $iWordID);
312 $aNewSearches[] = $oSearch;
316 return $aNewSearches;
320 * Derive new searches by adding a partial term to the existing search.
322 * @param mixed[] $aSearchTerm Description of the token.
323 * @param bool $bStructuredPhrases True if the search is structured.
324 * @param integer $iPhrase Number of the phrase the token is in.
325 * @param array[] $aFullTokens List of full term tokens with the
328 * @return SearchDescription[] List of derived search descriptions.
330 public function extendWithPartialTerm($aSearchTerm, $bStructuredPhrases, $iPhrase, $aFullTokens)
332 // Only allow name terms.
333 if (!(isset($aSearchTerm['word_id']) && $aSearchTerm['word_id'])) {
337 $aNewSearches = array();
338 $iWordID = $aSearchTerm['word_id'];
340 if ((!$bStructuredPhrases || $iPhrase > 0)
341 && sizeof($this->aName)
342 && strpos($aSearchTerm['word_token'], ' ') === false
344 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
345 $oSearch = clone $this;
346 $oSearch->iSearchRank++;
347 $oSearch->aAddress[$iWordID] = $iWordID;
348 $aNewSearches[] = $oSearch;
350 $oSearch = clone $this;
351 $oSearch->iSearchRank++;
352 $oSearch->aAddressNonSearch[$iWordID] = $iWordID;
353 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
354 $oSearch->iSearchRank += 2;
356 if (sizeof($aFullTokens)) {
357 $oSearch->iSearchRank++;
359 $aNewSearches[] = $oSearch;
361 // revert to the token version?
362 foreach ($aFullTokens as $aSearchTermToken) {
363 if (empty($aSearchTermToken['country_code'])
364 && empty($aSearchTermToken['lat'])
365 && empty($aSearchTermToken['class'])
367 $oSearch = clone $this;
368 $oSearch->iSearchRank++;
369 $oSearch->aAddress[$aSearchTermToken['word_id']] = $aSearchTermToken['word_id'];
370 $aNewSearches[] = $oSearch;
376 if ((!$this->sPostcode && !$this->aAddress && !$this->aAddressNonSearch)
377 && (!sizeof($this->aName) || $this->iNamePhrase == $iPhrase)
379 $oSearch = clone $this;
380 $oSearch->iSearchRank++;
381 if (!sizeof($this->aName)) {
382 $oSearch->iSearchRank += 1;
384 if (preg_match('#^[0-9]+$#', $aSearchTerm['word_token'])) {
385 $oSearch->iSearchRank += 2;
387 if ($aSearchTerm['search_name_count'] + 1 < CONST_Max_Word_Frequency) {
388 $oSearch->aName[$iWordID] = $iWordID;
390 $oSearch->aNameNonSearch[$iWordID] = $iWordID;
392 $oSearch->iNamePhrase = $iPhrase;
393 $aNewSearches[] = $oSearch;
396 return $aNewSearches;
399 /////////// Query functions
403 * Query database for places that match this search.
405 * @param object $oDB Database connection to use.
406 * @param mixed[] $aWordFrequencyScores Number of times tokens appears
407 * overall in a planet database.
408 * @param mixed[] $aExactMatchCache Saves number of exact matches.
409 * @param integer $iMinRank Minimum address rank to restrict
411 * @param integer $iMaxRank Maximum address rank to restrict
413 * @param integer $iLimit Maximum number of results.
415 * @return mixed[] An array with two fields: IDs contains the list of
416 * matching place IDs and houseNumber the houseNumber
417 * if appicable or -1 if not.
419 public function query(&$oDB, &$aWordFrequencyScores, &$aExactMatchCache, $iMinRank, $iMaxRank, $iLimit)
421 $aPlaceIDs = array();
424 if ($this->sCountryCode
425 && !sizeof($this->aName)
428 && !$this->oContext->hasNearPoint()
430 // Just looking for a country - look it up
431 if (4 >= $iMinRank && 4 <= $iMaxRank) {
432 $aPlaceIDs = $this->queryCountry($oDB);
434 } elseif (!sizeof($this->aName) && !sizeof($this->aAddress)) {
435 // Neither name nor address? Then we must be
436 // looking for a POI in a geographic area.
437 if ($this->oContext->isBoundedSearch()) {
438 $aPlaceIDs = $this->queryNearbyPoi($oDB, $iLimit);
440 } elseif ($this->iOperator == Operator::POSTCODE) {
441 // looking for postcode
442 $aPlaceIDs = $this->queryPostcode($oDB, $iLimit);
445 // First search for places according to name and address.
446 $aNamedPlaceIDs = $this->queryNamedPlace(
448 $aWordFrequencyScores,
454 if (sizeof($aNamedPlaceIDs)) {
455 foreach ($aNamedPlaceIDs as $aRow) {
456 $aPlaceIDs[] = $aRow['place_id'];
457 $aExactMatchCache[$aRow['place_id']] = $aRow['exactmatch'];
461 //now search for housenumber, if housenumber provided
462 if ($this->sHouseNumber && sizeof($aPlaceIDs)) {
463 $aResult = $this->queryHouseNumber($oDB, $aPlaceIDs, $iLimit);
465 if (sizeof($aResult)) {
466 $iHousenumber = $aResult['iHouseNumber'];
467 $aPlaceIDs = $aResult['aPlaceIDs'];
468 } elseif (!$this->looksLikeFullAddress()) {
469 $aPlaceIDs = array();
473 // finally get POIs if requested
474 if ($this->sClass && sizeof($aPlaceIDs)) {
475 $aPlaceIDs = $this->queryPoiByOperator($oDB, $aPlaceIDs, $iLimit);
480 echo "<br><b>Place IDs:</b> ";
481 var_Dump($aPlaceIDs);
484 if (sizeof($aPlaceIDs) && $this->sPostcode) {
485 $sSQL = 'SELECT place_id FROM placex';
486 $sSQL .= ' WHERE place_id in ('.join(',', $aPlaceIDs).')';
487 $sSQL .= " AND postcode = '".$this->sPostcode."'";
488 if (CONST_Debug) var_dump($sSQL);
489 $aFilteredPlaceIDs = chksql($oDB->getCol($sSQL));
490 if ($aFilteredPlaceIDs) {
491 $aPlaceIDs = $aFilteredPlaceIDs;
493 echo "<br><b>Place IDs after postcode filtering:</b> ";
494 var_Dump($aPlaceIDs);
499 return array('IDs' => $aPlaceIDs, 'houseNumber' => $iHousenumber);
503 private function queryCountry(&$oDB)
505 $sSQL = 'SELECT place_id FROM placex ';
506 $sSQL .= "WHERE country_code='".$this->sCountryCode."'";
507 $sSQL .= ' AND rank_search = 4';
508 if ($this->oContext->bViewboxBounded) {
509 $sSQL .= ' AND ST_Intersects('.$this->oContext->sqlViewboxSmall.', geometry)';
511 $sSQL .= " ORDER BY st_area(geometry) DESC LIMIT 1";
513 if (CONST_Debug) var_dump($sSQL);
515 return chksql($oDB->getCol($sSQL));
518 private function queryNearbyPoi(&$oDB, $iLimit)
520 if (!$this->sClass) {
524 $sPoiTable = $this->poiTable();
526 $sSQL = 'SELECT count(*) FROM pg_tables WHERE tablename = \''.$sPoiTable."'";
527 if (chksql($oDB->getOne($sSQL))) {
528 $sSQL = 'SELECT place_id FROM '.$sPoiTable.' ct';
529 if ($this->oContext->sqlCountryList) {
530 $sSQL .= ' JOIN placex USING (place_id)';
532 if ($this->oContext->hasNearPoint()) {
533 $sSQL .= ' WHERE '.$this->oContext->withinSQL('ct.centroid');
534 } elseif ($this->oContext->bViewboxBounded) {
535 $sSQL .= ' WHERE ST_Contains('.$this->oContext->sqlViewboxSmall.', ct.centroid)';
537 if ($this->oContext->sqlCountryList) {
538 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
540 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
541 if ($this->oContext->sqlViewboxCentre) {
542 $sSQL .= ' ORDER BY ST_Distance(';
543 $sSQL .= $this->oContext->sqlViewboxCentre.', ct.centroid) ASC';
544 } elseif ($this->oContext->hasNearPoint()) {
545 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('ct.centroid').' ASC';
547 $sSQL .= " limit $iLimit";
548 if (CONST_Debug) var_dump($sSQL);
549 return chksql($oDB->getCol($sSQL));
552 if ($this->oContext->hasNearPoint()) {
553 $sSQL = 'SELECT place_id FROM placex WHERE ';
554 $sSQL .= 'class=\''.$this->sClass."' and type='".$this->sType."'";
555 $sSQL .= ' AND '.$this->oContext->withinSQL('geometry');
556 $sSQL .= ' AND linked_place_id is null';
557 if ($this->oContext->sqlCountryList) {
558 $sSQL .= ' AND country_code in '.$this->oContext->sqlCountryList;
560 $sSQL .= ' ORDER BY '.$this->oContext->distanceSQL('centroid')." ASC";
561 $sSQL .= " LIMIT $iLimit";
562 if (CONST_Debug) var_dump($sSQL);
563 return chksql($oDB->getCol($sSQL));
569 private function queryPostcode(&$oDB, $iLimit)
571 $sSQL = 'SELECT p.place_id FROM location_postcode p ';
573 if (sizeof($this->aAddress)) {
574 $sSQL .= ', search_name s ';
575 $sSQL .= 'WHERE s.place_id = p.parent_place_id ';
576 $sSQL .= 'AND array_cat(s.nameaddress_vector, s.name_vector)';
577 $sSQL .= ' @> '.getArraySQL($this->aAddress).' AND ';
582 $sSQL .= "p.postcode = '".reset($this->aName)."'";
583 $sSQL .= $this->countryCodeSQL(' AND p.country_code');
584 $sSQL .= $this->oContext->excludeSQL(' AND p.place_id');
585 $sSQL .= " LIMIT $iLimit";
587 if (CONST_Debug) var_dump($sSQL);
589 return chksql($oDB->getCol($sSQL));
592 private function queryNamedPlace(&$oDB, $aWordFrequencyScores, $iMinAddressRank, $iMaxAddressRank, $iLimit)
597 if ($this->sHouseNumber && sizeof($this->aAddress)) {
598 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
600 $aOrder[0] .= 'EXISTS(';
601 $aOrder[0] .= ' SELECT place_id';
602 $aOrder[0] .= ' FROM placex';
603 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
604 $aOrder[0] .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
605 $aOrder[0] .= ' LIMIT 1';
607 // also housenumbers from interpolation lines table are needed
608 if (preg_match('/[0-9]+/', $this->sHouseNumber)) {
609 $iHouseNumber = intval($this->sHouseNumber);
610 $aOrder[0] .= 'OR EXISTS(';
611 $aOrder[0] .= ' SELECT place_id ';
612 $aOrder[0] .= ' FROM location_property_osmline ';
613 $aOrder[0] .= ' WHERE parent_place_id = search_name.place_id';
614 $aOrder[0] .= ' AND startnumber is not NULL';
615 $aOrder[0] .= ' AND '.$iHouseNumber.'>=startnumber ';
616 $aOrder[0] .= ' AND '.$iHouseNumber.'<=endnumber ';
617 $aOrder[0] .= ' LIMIT 1';
620 $aOrder[0] .= ') DESC';
623 if (sizeof($this->aName)) {
624 $aTerms[] = 'name_vector @> '.getArraySQL($this->aName);
626 if (sizeof($this->aAddress)) {
627 // For infrequent name terms disable index usage for address
628 if (CONST_Search_NameOnlySearchFrequencyThreshold
629 && sizeof($this->aName) == 1
630 && $aWordFrequencyScores[$this->aName[reset($this->aName)]]
631 < CONST_Search_NameOnlySearchFrequencyThreshold
633 $aTerms[] = 'array_cat(nameaddress_vector,ARRAY[]::integer[]) @> '.getArraySQL($this->aAddress);
635 $aTerms[] = 'nameaddress_vector @> '.getArraySQL($this->aAddress);
639 $sCountryTerm = $this->countryCodeSQL('country_code');
641 $aTerms[] = $sCountryTerm;
644 if ($this->sHouseNumber) {
645 $aTerms[] = "address_rank between 16 and 27";
646 } elseif (!$this->sClass || $this->iOperator == Operator::NAME) {
647 if ($iMinAddressRank > 0) {
648 $aTerms[] = "address_rank >= ".$iMinAddressRank;
650 if ($iMaxAddressRank < 30) {
651 $aTerms[] = "address_rank <= ".$iMaxAddressRank;
655 if ($this->oContext->hasNearPoint()) {
656 $aTerms[] = $this->oContext->withinSQL('centroid');
657 $aOrder[] = $this->oContext->distanceSQL('centroid');
658 } elseif ($this->sPostcode) {
659 if (!sizeof($this->aAddress)) {
660 $aTerms[] = "EXISTS(SELECT place_id FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."' AND ST_DWithin(search_name.centroid, p.geometry, 0.1))";
662 $aOrder[] = "(SELECT min(ST_Distance(search_name.centroid, p.geometry)) FROM location_postcode p WHERE p.postcode = '".$this->sPostcode."')";
666 $sExcludeSQL = $this->oContext->excludeSQL('place_id');
668 $aTerms[] = $sExcludeSQL;
671 if ($this->oContext->bViewboxBounded) {
672 $aTerms[] = 'centroid && '.$this->oContext->sqlViewboxSmall;
675 if ($this->oContext->hasNearPoint()) {
676 $aOrder[] = $this->oContext->distanceSQL('centroid');
679 if ($this->sHouseNumber) {
680 $sImportanceSQL = '- abs(26 - address_rank) + 3';
682 $sImportanceSQL = '(CASE WHEN importance = 0 OR importance IS NULL THEN 0.75-(search_rank::float/40) ELSE importance END)';
684 $sImportanceSQL .= $this->oContext->viewboxImportanceSQL('centroid');
685 $aOrder[] = "$sImportanceSQL DESC";
687 if (sizeof($this->aFullNameAddress)) {
688 $sExactMatchSQL = ' ( ';
689 $sExactMatchSQL .= ' SELECT count(*) FROM ( ';
690 $sExactMatchSQL .= ' SELECT unnest('.getArraySQL($this->aFullNameAddress).')';
691 $sExactMatchSQL .= ' INTERSECT ';
692 $sExactMatchSQL .= ' SELECT unnest(nameaddress_vector)';
693 $sExactMatchSQL .= ' ) s';
694 $sExactMatchSQL .= ') as exactmatch';
695 $aOrder[] = 'exactmatch DESC';
697 $sExactMatchSQL = '0::int as exactmatch';
700 if ($this->sHouseNumber || $this->sClass) {
704 if (sizeof($aTerms)) {
705 $sSQL = 'SELECT place_id,'.$sExactMatchSQL;
706 $sSQL .= ' FROM search_name';
707 $sSQL .= ' WHERE '.join(' and ', $aTerms);
708 $sSQL .= ' ORDER BY '.join(', ', $aOrder);
709 $sSQL .= ' LIMIT '.$iLimit;
711 if (CONST_Debug) var_dump($sSQL);
715 "Could not get places for search terms."
722 private function queryHouseNumber(&$oDB, $aRoadPlaceIDs, $iLimit)
724 $sPlaceIDs = join(',', $aRoadPlaceIDs);
726 $sHouseNumberRegex = '\\\\m'.$this->sHouseNumber.'\\\\M';
727 $sSQL = 'SELECT place_id FROM placex ';
728 $sSQL .= 'WHERE parent_place_id in ('.$sPlaceIDs.')';
729 $sSQL .= " AND transliteration(housenumber) ~* E'".$sHouseNumberRegex."'";
730 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
731 $sSQL .= " LIMIT $iLimit";
733 if (CONST_Debug) var_dump($sSQL);
735 $aPlaceIDs = chksql($oDB->getCol($sSQL));
737 if (sizeof($aPlaceIDs)) {
738 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
741 $bIsIntHouseNumber= (bool) preg_match('/[0-9]+/', $this->sHouseNumber);
742 $iHousenumber = intval($this->sHouseNumber);
743 if ($bIsIntHouseNumber) {
744 // if nothing found, search in the interpolation line table
745 $sSQL = 'SELECT distinct place_id FROM location_property_osmline';
746 $sSQL .= ' WHERE startnumber is not NULL';
747 $sSQL .= ' AND parent_place_id in ('.$sPlaceIDs.') AND (';
748 if ($iHousenumber % 2 == 0) {
749 // If housenumber is even, look for housenumber in streets
750 // with interpolationtype even or all.
751 $sSQL .= "interpolationtype='even'";
753 // Else look for housenumber with interpolationtype odd or all.
754 $sSQL .= "interpolationtype='odd'";
756 $sSQL .= " or interpolationtype='all') and ";
757 $sSQL .= $iHousenumber.">=startnumber and ";
758 $sSQL .= $iHousenumber."<=endnumber";
759 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
760 $sSQL .= " limit $iLimit";
762 if (CONST_Debug) var_dump($sSQL);
764 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
766 if (sizeof($aPlaceIDs)) {
767 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
771 // If nothing found try the aux fallback table
772 if (CONST_Use_Aux_Location_data) {
773 $sSQL = 'SELECT place_id FROM location_property_aux';
774 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.')';
775 $sSQL .= " AND housenumber = '".$this->sHouseNumber."'";
776 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
777 $sSQL .= " limit $iLimit";
779 if (CONST_Debug) var_dump($sSQL);
781 $aPlaceIDs = chksql($oDB->getCol($sSQL));
783 if (sizeof($aPlaceIDs)) {
784 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => -1);
788 // If nothing found then search in Tiger data (location_property_tiger)
789 if (CONST_Use_US_Tiger_Data && $bIsIntHouseNumber) {
790 $sSQL = 'SELECT distinct place_id FROM location_property_tiger';
791 $sSQL .= ' WHERE parent_place_id in ('.$sPlaceIDs.') and (';
792 if ($iHousenumber % 2 == 0) {
793 $sSQL .= "interpolationtype='even'";
795 $sSQL .= "interpolationtype='odd'";
797 $sSQL .= " or interpolationtype='all') and ";
798 $sSQL .= $iHousenumber.">=startnumber and ";
799 $sSQL .= $iHousenumber."<=endnumber";
800 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
801 $sSQL .= " limit $iLimit";
803 if (CONST_Debug) var_dump($sSQL);
805 $aPlaceIDs = chksql($oDB->getCol($sSQL, 0));
807 if (sizeof($aPlaceIDs)) {
808 return array('aPlaceIDs' => $aPlaceIDs, 'iHouseNumber' => $iHousenumber);
816 private function queryPoiByOperator(&$oDB, $aParentIDs, $iLimit)
818 $sPlaceIDs = join(',', $aParentIDs);
819 $aClassPlaceIDs = array();
821 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NAME) {
822 // If they were searching for a named class (i.e. 'Kings Head pub')
823 // then we might have an extra match
824 $sSQL = 'SELECT place_id FROM placex ';
825 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
826 $sSQL .= " AND class='".$this->sClass."' ";
827 $sSQL .= " AND type='".$this->sType."'";
828 $sSQL .= " AND linked_place_id is null";
829 $sSQL .= $this->oContext->excludeSQL(' AND place_id');
830 $sSQL .= " ORDER BY rank_search ASC ";
831 $sSQL .= " LIMIT $iLimit";
833 if (CONST_Debug) var_dump($sSQL);
835 $aClassPlaceIDs = chksql($oDB->getCol($sSQL));
838 // NEAR and IN are handled the same
839 if ($this->iOperator == Operator::TYPE || $this->iOperator == Operator::NEAR) {
840 $sClassTable = $this->poiTable();
841 $sSQL = "SELECT count(*) FROM pg_tables WHERE tablename = '$sClassTable'";
842 $bCacheTable = (bool) chksql($oDB->getOne($sSQL));
844 $sSQL = "SELECT min(rank_search) FROM placex WHERE place_id in ($sPlaceIDs)";
845 if (CONST_Debug) var_dump($sSQL);
846 $iMaxRank = (int)chksql($oDB->getOne($sSQL));
848 // For state / country level searches the normal radius search doesn't work very well
850 if ($iMaxRank < 9 && $bCacheTable) {
851 // Try and get a polygon to search in instead
852 $sSQL = 'SELECT geometry FROM placex';
853 $sSQL .= " WHERE place_id in ($sPlaceIDs)";
854 $sSQL .= " AND rank_search < $iMaxRank + 5";
855 $sSQL .= " AND ST_GeometryType(geometry) in ('ST_Polygon','ST_MultiPolygon')";
856 $sSQL .= " ORDER BY rank_search ASC ";
858 if (CONST_Debug) var_dump($sSQL);
859 $sPlaceGeom = chksql($oDB->getOne($sSQL));
866 $sSQL = 'SELECT place_id FROM placex';
867 $sSQL .= " WHERE place_id in ($sPlaceIDs) and rank_search < $iMaxRank";
868 if (CONST_Debug) var_dump($sSQL);
869 $aPlaceIDs = chksql($oDB->getCol($sSQL));
870 $sPlaceIDs = join(',', $aPlaceIDs);
873 if ($sPlaceIDs || $sPlaceGeom) {
876 // More efficient - can make the range bigger
880 if ($this->oContext->hasNearPoint()) {
881 $sOrderBySQL = $this->oContext->distanceSQL('l.centroid');
882 } elseif ($sPlaceIDs) {
883 $sOrderBySQL = "ST_Distance(l.centroid, f.geometry)";
884 } elseif ($sPlaceGeom) {
885 $sOrderBySQL = "ST_Distance(st_centroid('".$sPlaceGeom."'), l.centroid)";
888 $sSQL = 'SELECT distinct i.place_id';
890 $sSQL .= ', i.order_term';
892 $sSQL .= ' from (SELECT l.place_id';
894 $sSQL .= ','.$sOrderBySQL.' as order_term';
896 $sSQL .= ' from '.$sClassTable.' as l';
899 $sSQL .= ",placex as f WHERE ";
900 $sSQL .= "f.place_id in ($sPlaceIDs) ";
901 $sSQL .= " AND ST_DWithin(l.centroid, f.centroid, $fRange)";
902 } elseif ($sPlaceGeom) {
903 $sSQL .= " WHERE ST_Contains('$sPlaceGeom', l.centroid)";
906 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
907 $sSQL .= 'limit 300) i ';
909 $sSQL .= 'order by order_term asc';
911 $sSQL .= " limit $iLimit";
913 if (CONST_Debug) var_dump($sSQL);
915 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
917 if ($this->oContext->hasNearPoint()) {
918 $fRange = $this->oContext->nearRadius();
922 if ($this->oContext->hasNearPoint()) {
923 $sOrderBySQL = $this->oContext->distanceSQL('l.geometry');
925 $sOrderBySQL = "ST_Distance(l.geometry, f.geometry)";
928 $sSQL = 'SELECT distinct l.place_id';
930 $sSQL .= ','.$sOrderBySQL.' as orderterm';
932 $sSQL .= ' FROM placex as l, placex as f';
933 $sSQL .= " WHERE f.place_id in ($sPlaceIDs)";
934 $sSQL .= " AND ST_DWithin(l.geometry, f.centroid, $fRange)";
935 $sSQL .= " AND l.class='".$this->sClass."'";
936 $sSQL .= " AND l.type='".$this->sType."'";
937 $sSQL .= $this->oContext->excludeSQL(' AND l.place_id');
939 $sSQL .= "ORDER BY orderterm ASC";
941 $sSQL .= " limit $iLimit";
943 if (CONST_Debug) var_dump($sSQL);
945 $aClassPlaceIDs = array_merge($aClassPlaceIDs, chksql($oDB->getCol($sSQL)));
950 return $aClassPlaceIDs;
953 private function poiTable()
955 return 'place_classtype_'.$this->sClass.'_'.$this->sType;
958 private function countryCodeSQL($sVar)
960 if ($this->sCountryCode) {
961 return $sVar.' = \''.$this->sCountryCode."'";
963 if ($this->oContext->sqlCountryList) {
964 return $sVar.' in '.$this->oContext->sqlCountryList;
970 /////////// Sort functions
973 public static function bySearchRank($a, $b)
975 if ($a->iSearchRank == $b->iSearchRank) {
976 return $a->iOperator + strlen($a->sHouseNumber)
977 - $b->iOperator - strlen($b->sHouseNumber);
980 return $a->iSearchRank < $b->iSearchRank ? -1 : 1;
983 //////////// Debugging functions
986 public function dumpAsHtmlTableRow(&$aWordIDs)
988 $kf = function ($k) use (&$aWordIDs) {
989 return $aWordIDs[$k];
993 echo "<td>$this->iSearchRank</td>";
994 echo "<td>".join(', ', array_map($kf, $this->aName))."</td>";
995 echo "<td>".join(', ', array_map($kf, $this->aNameNonSearch))."</td>";
996 echo "<td>".join(', ', array_map($kf, $this->aAddress))."</td>";
997 echo "<td>".join(', ', array_map($kf, $this->aAddressNonSearch))."</td>";
998 echo "<td>".$this->sCountryCode."</td>";
999 echo "<td>".Operator::toString($this->iOperator)."</td>";
1000 echo "<td>".$this->sClass."</td>";
1001 echo "<td>".$this->sType."</td>";
1002 echo "<td>".$this->sPostcode."</td>";
1003 echo "<td>".$this->sHouseNumber."</td>";