]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/icu_tokenizer.php
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / lib-php / tokenizer / icu_tokenizer.php
1 <?php
2
3 namespace Nominatim;
4
5 require_once(CONST_LibDir.'/SimpleWordList.php');
6
7 class Tokenizer
8 {
9     private $oDB;
10
11     private $oNormalizer;
12     private $oTransliterator;
13
14     public function __construct(&$oDB)
15     {
16         $this->oDB =& $oDB;
17         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
18         $this->oTransliterator = \Transliterator::createFromRules(CONST_Transliteration);
19     }
20
21     public function checkStatus()
22     {
23         $sSQL = 'SELECT word_id FROM word WHERE word_id is not null limit 1';
24         $iWordID = $this->oDB->getOne($sSQL);
25         if ($iWordID === false) {
26             throw new \Exception('Query failed', 703);
27         }
28         if (!$iWordID) {
29             throw new \Exception('No value', 704);
30         }
31     }
32
33
34     public function normalizeString($sTerm)
35     {
36         if ($this->oNormalizer === null) {
37             return $sTerm;
38         }
39
40         return $this->oNormalizer->transliterate($sTerm);
41     }
42
43
44     public function mostFrequentWords($iNum)
45     {
46         $sSQL = "SELECT word FROM word WHERE type = 'W'";
47         $sSQL .= "ORDER BY info->'count' DESC LIMIT ".$iNum;
48         return $this->oDB->getCol($sSQL);
49     }
50
51
52     private function makeStandardWord($sTerm)
53     {
54         return trim($this->oTransliterator->transliterate(' '.$sTerm.' '));
55     }
56
57
58     public function tokensForSpecialTerm($sTerm)
59     {
60         $aResults = array();
61
62         $sSQL = "SELECT word_id, info->>'class' as class, info->>'type' as type ";
63         $sSQL .= '   FROM word WHERE word_token = :term and type = \'S\'';
64
65         Debug::printVar('Term', $sTerm);
66         Debug::printSQL($sSQL);
67         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $this->makeStandardWord($sTerm)));
68
69         Debug::printVar('Results', $aSearchWords);
70
71         foreach ($aSearchWords as $aSearchTerm) {
72             $aResults[] = new \Nominatim\Token\SpecialTerm(
73                 $aSearchTerm['word_id'],
74                 $aSearchTerm['class'],
75                 $aSearchTerm['type'],
76                 \Nominatim\Operator::TYPE
77             );
78         }
79
80         Debug::printVar('Special term tokens', $aResults);
81
82         return $aResults;
83     }
84
85
86     public function extractTokensFromPhrases(&$aPhrases)
87     {
88         $sNormQuery = '';
89         $aWordLists = array();
90         $aTokens = array();
91         foreach ($aPhrases as $iPhrase => $oPhrase) {
92             $sNormPhrase = $this->normalizeString($oPhrase->getPhrase());
93             Debug::printVar('Phrase', $sNormPhrase);
94
95             $oWordList = new SimpleWordList($sNormPhrase);
96
97             foreach ($oWordList->getTokens() as $sToken) {
98                 $sTransToken = $this->makeStandardWord($sToken);
99                 if (!isset($aTokens[$sTransToken])) {
100                     $aTokens[$sTransToken] = array();
101                 }
102                 $aTokens[$sTransToken][$sToken] = $sToken;
103             }
104
105             $aWordLists[] = $oWordList;
106         }
107
108         Debug::printVar('Tokens', $aTokens);
109         Debug::printVar('WordLists', $aWordLists);
110
111         $oValidTokens = $this->computeValidTokens($aTokens);
112
113         foreach ($aPhrases as $iPhrase => $oPhrase) {
114             $oPhrase->setWordSets($aWordLists[$iPhrase]->getWordSets($oValidTokens));
115         }
116
117         return $oValidTokens;
118     }
119
120
121     private function computeValidTokens($aTokens)
122     {
123         $oValidTokens = new TokenList();
124
125         if (!empty($aTokens)) {
126             $this->addTokensFromDB($oValidTokens, $aTokens);
127
128             // Try more interpretations for Tokens that could not be matched.
129             foreach ($aTokens as $sToken => $aNormalized) {
130                 if (!$oValidTokens->contains($sToken)) {
131                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
132                         // US ZIP+4 codes - merge in the 5-digit ZIP code
133                         $oValidTokens->addToken(
134                             $sToken,
135                             new Token\Postcode(null, $aData[1], 'us')
136                         );
137                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
138                         // Unknown single word token with a number.
139                         // Assume it is a house number.
140                         $oValidTokens->addToken(
141                             $sToken,
142                             new Token\HouseNumber(null, trim($sToken))
143                         );
144                     }
145                 }
146             }
147         }
148
149         return $oValidTokens;
150     }
151
152
153     private function addTokensFromDB(&$oValidTokens, $aTokens)
154     {
155         // Check which tokens we have, get the ID numbers
156         $sSQL = 'SELECT word_id, word_token, type, word,';
157         $sSQL .= "      info->>'op' as operator,";
158         $sSQL .= "      info->>'class' as class, info->>'type' as ctype,";
159         $sSQL .= "      info->>'count' as count";
160         $sSQL .= ' FROM word WHERE word_token in (';
161         $sSQL .= join(',', $this->oDB->getDBQuotedList(array_keys($aTokens))).')';
162
163         Debug::printSQL($sSQL);
164
165         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
166
167         foreach ($aDBWords as $aWord) {
168             $iId = (int) $aWord['word_id'];
169             $sTok = $aWord['word_token'];
170             $aNorms = $aTokens[$sTok];
171
172             switch ($aWord['type']) {
173                 case 'C':  // country name tokens
174                     if ($aWord['word'] !== null) {
175                         foreach ($aNorms as $sNorm) {
176                             $oValidTokens->addToken(
177                                 $sNorm,
178                                 new Token\Country($iId, $aWord['word'])
179                             );
180                         }
181                     }
182                     break;
183                 case 'H':  // house number tokens
184                     foreach ($aNorms as $sNorm) {
185                         $oValidTokens->addToken($sNorm, new Token\HouseNumber($iId, $aWord['word_token']));
186                     }
187                     break;
188                 case 'P':  // postcode tokens
189                     // Postcodes are not normalized, so they may have content
190                     // that makes SQL injection possible. Reject postcodes
191                     // that would need special escaping.
192                     if ($aWord['word'] !== null
193                         && pg_escape_string($aWord['word']) == $aWord['word']
194                     ) {
195                         $sNormPostcode = $this->normalizeString($aWord['word']);
196                         foreach ($aNorms as $sNorm) {
197                             if ($sNormPostcode == $sNorm) {
198                                 $oValidTokens->addToken(
199                                     $sNorm,
200                                     new Token\Postcode($iId, $aWord['word'], null)
201                                 );
202                             }
203                         }
204                     }
205                     break;
206                 case 'S':  // tokens for classification terms (special phrases)
207                     if ($aWord['class'] !== null && $aWord['ctype'] !== null) {
208                         foreach ($aNorms as $sNorm) {
209                             if ($aWord['word'] == $sNorm) {
210                                 $oValidTokens->addToken($sTok, new Token\SpecialTerm(
211                                     $iId,
212                                     $aWord['class'],
213                                     $aWord['ctype'],
214                                     (isset($aWord['operator'])) ? Operator::NEAR : Operator::NONE
215                                 ));
216                             }
217                         }
218                     }
219                     break;
220                 case 'W': // full-word tokens
221                     foreach ($aNorms as $sNorm) {
222                         $oValidTokens->addToken($sNorm, new Token\Word(
223                             $iId,
224                             (int) $aWord['count'],
225                             substr_count($aWord['word_token'], ' ') + 1,
226                             levenshtein($aWord['word'], $sNorm) + 1
227                         ));
228                     }
229                     break;
230                 case 'w':  // partial word terms
231                     foreach ($aNorms as $sNorm) {
232                         $oValidTokens->addToken($sNorm, new Token\Partial(
233                             $iId,
234                             $aWord['word_token'],
235                             (int) $aWord['count']
236                         ));
237                     }
238                     break;
239                 default:
240                     break;
241             }
242         }
243     }
244 }