3  * SPDX-License-Identifier: GPL-2.0-only
 
   5  * This file is part of Nominatim. (https://nominatim.org)
 
   7  * Copyright (C) 2022 by the Nominatim developer community.
 
   8  * For a full list of authors see the git log.
 
  13 require_once(CONST_LibDir.'/SimpleWordList.php');
 
  19     private $oNormalizer = null;
 
  21     public function __construct(&$oDB)
 
  24         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
 
  27     public function checkStatus()
 
  29         $sStandardWord = $this->oDB->getOne("SELECT make_standard_name('a')");
 
  30         if ($sStandardWord === false) {
 
  31             throw new \Exception('Module failed', 701);
 
  34         if ($sStandardWord != 'a') {
 
  35             throw new \Exception('Module call failed', 702);
 
  38         $sSQL = "SELECT word_id FROM word WHERE word_token IN (' a')";
 
  39         $iWordID = $this->oDB->getOne($sSQL);
 
  40         if ($iWordID === false) {
 
  41             throw new \Exception('Query failed', 703);
 
  44             throw new \Exception('No value', 704);
 
  49     public function normalizeString($sTerm)
 
  51         if ($this->oNormalizer === null) {
 
  55         return $this->oNormalizer->transliterate($sTerm);
 
  59     public function mostFrequentWords($iNum)
 
  61         $sSQL = 'SELECT word FROM word WHERE word is not null ';
 
  62         $sSQL .= 'ORDER BY search_name_count DESC LIMIT '.$iNum;
 
  63         return $this->oDB->getCol($sSQL);
 
  67     public function tokensForSpecialTerm($sTerm)
 
  71         $sSQL = 'SELECT word_id, class, type FROM word ';
 
  72         $sSQL .= '   WHERE word_token = \' \' || make_standard_name(:term)';
 
  73         $sSQL .= '   AND class is not null AND class not in (\'place\')';
 
  75         Debug::printVar('Term', $sTerm);
 
  76         Debug::printSQL($sSQL);
 
  77         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $sTerm));
 
  79         Debug::printVar('Results', $aSearchWords);
 
  81         foreach ($aSearchWords as $aSearchTerm) {
 
  82             $aResults[] = new \Nominatim\Token\SpecialTerm(
 
  83                 $aSearchTerm['word_id'],
 
  84                 $aSearchTerm['class'],
 
  86                 \Nominatim\Operator::TYPE
 
  90         Debug::printVar('Special term tokens', $aResults);
 
  96     public function extractTokensFromPhrases(&$aPhrases)
 
  98         // First get the normalized version of all phrases
 
 102         foreach ($aPhrases as $iPhrase => $oPhrase) {
 
 103             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
 
 104             $sSQL .= 'make_standard_name(:' .$iPhrase.') as p'.$iPhrase.',';
 
 105             $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
 
 107             // Conflicts between US state abbreviations and various words
 
 108             // for 'the' in different languages
 
 109             switch (strtolower($oPhrase->getPhrase())) {
 
 111                     $aParams[':'.$iPhrase] = 'illinois';
 
 114                     $aParams[':'.$iPhrase] = 'alabama';
 
 117                     $aParams[':'.$iPhrase] = 'louisiana';
 
 120                     $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
 
 124         $sSQL = substr($sSQL, 0, -1);
 
 126         Debug::printSQL($sSQL);
 
 127         Debug::printVar('SQL parameters', $aParams);
 
 129         $aNormPhrases = $this->oDB->getRow($sSQL, $aParams);
 
 131         Debug::printVar('SQL result', $aNormPhrases);
 
 133         // now compute all possible tokens
 
 134         $aWordLists = array();
 
 136         foreach ($aNormPhrases as $sPhrase) {
 
 137             $oWordList = new SimpleWordList($sPhrase);
 
 139             foreach ($oWordList->getTokens() as $sToken) {
 
 140                 $aTokens[' '.$sToken] = ' '.$sToken;
 
 141                 $aTokens[$sToken] = $sToken;
 
 144             $aWordLists[] = $oWordList;
 
 147         Debug::printVar('Tokens', $aTokens);
 
 148         Debug::printVar('WordLists', $aWordLists);
 
 150         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
 
 152         foreach ($aPhrases as $iPhrase => $oPhrase) {
 
 153             $oPhrase->setWordSets($aWordLists[$iPhrase]->getWordSets($oValidTokens));
 
 156         return $oValidTokens;
 
 160     private function computeValidTokens($aTokens, $sNormQuery)
 
 162         $oValidTokens = new TokenList();
 
 164         if (!empty($aTokens)) {
 
 165             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
 
 167             // Try more interpretations for Tokens that could not be matched.
 
 168             foreach ($aTokens as $sToken) {
 
 169                 if ($sToken[0] != ' ' && !$oValidTokens->contains($sToken)) {
 
 170                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
 
 171                         // US ZIP+4 codes - merge in the 5-digit ZIP code
 
 172                         $oValidTokens->addToken(
 
 174                             new Token\Postcode(null, $aData[1], 'us')
 
 176                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
 
 177                         // Unknown single word token with a number.
 
 178                         // Assume it is a house number.
 
 179                         $oValidTokens->addToken(
 
 181                             new Token\HouseNumber(null, trim($sToken))
 
 188         return $oValidTokens;
 
 192     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
 
 194         // Check which tokens we have, get the ID numbers
 
 195         $sSQL = 'SELECT word_id, word_token, word, class, type, country_code,';
 
 196         $sSQL .= ' operator, coalesce(search_name_count, 0) as count';
 
 197         $sSQL .= ' FROM word WHERE word_token in (';
 
 198         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
 
 200         Debug::printSQL($sSQL);
 
 202         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
 
 204         foreach ($aDBWords as $aWord) {
 
 206             $iId = (int) $aWord['word_id'];
 
 208             if ($aWord['class']) {
 
 209                 // Special terms need to appear in their normalized form.
 
 210                 // (postcodes are not normalized in the word table)
 
 211                 $sNormWord = $this->normalizeString($aWord['word']);
 
 212                 if ($aWord['word'] && strpos($sNormQuery, $sNormWord) === false) {
 
 216                 if ($aWord['class'] == 'place' && $aWord['type'] == 'house') {
 
 217                     $oToken = new Token\HouseNumber($iId, trim($aWord['word_token']));
 
 218                 } elseif ($aWord['class'] == 'place' && $aWord['type'] == 'postcode') {
 
 220                         && pg_escape_string($aWord['word']) == $aWord['word']
 
 222                         $oToken = new Token\Postcode(
 
 225                             $aWord['country_code']
 
 229                     // near and in operator the same at the moment
 
 230                     $oToken = new Token\SpecialTerm(
 
 234                         $aWord['operator'] ? Operator::NEAR : Operator::NONE
 
 237             } elseif ($aWord['country_code']) {
 
 238                 $oToken = new Token\Country($iId, $aWord['country_code']);
 
 239             } elseif ($aWord['word_token'][0] == ' ') {
 
 240                 $oToken = new Token\Word(
 
 242                     (int) $aWord['count'],
 
 243                     substr_count($aWord['word_token'], ' ')
 
 245             // For backward compatibility: ignore all partial tokens with more
 
 247             } elseif (strpos($aWord['word_token'], ' ') === false) {
 
 248                 $oToken = new Token\Partial(
 
 250                     $aWord['word_token'],
 
 251                     (int) $aWord['count']
 
 256                 // remove any leading spaces
 
 257                 if ($aWord['word_token'][0] == ' ') {
 
 258                     $oValidTokens->addToken(substr($aWord['word_token'], 1), $oToken);
 
 260                     $oValidTokens->addToken($aWord['word_token'], $oToken);