]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_icu_tokenizer.php
70358976f15a0e7f6a67d485d8fe5eb6977bb1bb
[nominatim.git] / lib-php / tokenizer / legacy_icu_tokenizer.php
1 <?php
2
3 namespace Nominatim;
4
5 class Tokenizer
6 {
7     private $oDB;
8
9     private $oNormalizer;
10     private $oTransliterator;
11     private $aCountryRestriction;
12
13     public function __construct(&$oDB)
14     {
15         $this->oDB =& $oDB;
16         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
17         $this->oTransliterator = \Transliterator::createFromRules(CONST_Transliteration);
18     }
19
20     public function checkStatus()
21     {
22         $sSQL = "SELECT word_id FROM word WHERE word_token IN (' a')";
23         $iWordID = $this->oDB->getOne($sSQL);
24         if ($iWordID === false) {
25             throw new Exception('Query failed', 703);
26         }
27         if (!$iWordID) {
28             throw new Exception('No value', 704);
29         }
30     }
31
32
33     public function setCountryRestriction($aCountries)
34     {
35         $this->aCountryRestriction = $aCountries;
36     }
37
38
39     public function normalizeString($sTerm)
40     {
41         if ($this->oNormalizer === null) {
42             return $sTerm;
43         }
44
45         return $this->oNormalizer->transliterate($sTerm);
46     }
47
48     private function makeStandardWord($sTerm)
49     {
50         return trim($this->oTransliterator->transliterate(' '.$sTerm.' '));
51     }
52
53
54     public function tokensForSpecialTerm($sTerm)
55     {
56         $aResults = array();
57
58         $sSQL = 'SELECT word_id, class, type FROM word ';
59         $sSQL .= '   WHERE word_token = \' \' || :term';
60         $sSQL .= '   AND class is not null AND class not in (\'place\')';
61
62         Debug::printVar('Term', $sTerm);
63         Debug::printSQL($sSQL);
64         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $this->makeStandardWord($sTerm)));
65
66         Debug::printVar('Results', $aSearchWords);
67
68         foreach ($aSearchWords as $aSearchTerm) {
69             $aResults[] = new \Nominatim\Token\SpecialTerm(
70                 $aSearchTerm['word_id'],
71                 $aSearchTerm['class'],
72                 $aSearchTerm['type'],
73                 \Nominatim\Operator::TYPE
74             );
75         }
76
77         Debug::printVar('Special term tokens', $aResults);
78
79         return $aResults;
80     }
81
82
83     public function extractTokensFromPhrases(&$aPhrases)
84     {
85         $sNormQuery = '';
86         $aWordLists = array();
87         $aTokens = array();
88         foreach ($aPhrases as $iPhrase => $oPhrase) {
89             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
90             $sPhrase = $this->makeStandardWord($oPhrase->getPhrase());
91             Debug::printVar('Phrase', $sPhrase);
92             if (strlen($sPhrase) > 0) {
93                 $aWords = explode(' ', $sPhrase);
94                 Tokenizer::addTokens($aTokens, $aWords);
95                 $aWordLists[] = $aWords;
96             } else {
97                 $aWordLists[] = array();
98             }
99         }
100
101         Debug::printVar('Tokens', $aTokens);
102         Debug::printVar('WordLists', $aWordLists);
103
104         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
105
106         foreach ($aPhrases as $iPhrase => $oPhrase) {
107             $oPhrase->computeWordSets($aWordLists[$iPhrase], $oValidTokens);
108         }
109
110         return $oValidTokens;
111     }
112
113
114     private function computeValidTokens($aTokens, $sNormQuery)
115     {
116         $oValidTokens = new TokenList();
117
118         if (!empty($aTokens)) {
119             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
120
121             // Try more interpretations for Tokens that could not be matched.
122             foreach ($aTokens as $sToken) {
123                 if ($sToken[0] != ' ' && !$oValidTokens->contains($sToken)) {
124                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
125                         // US ZIP+4 codes - merge in the 5-digit ZIP code
126                         $oValidTokens->addToken(
127                             $sToken,
128                             new Token\Postcode(null, $aData[1], 'us')
129                         );
130                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
131                         // Unknown single word token with a number.
132                         // Assume it is a house number.
133                         $oValidTokens->addToken(
134                             $sToken,
135                             new Token\HouseNumber(null, trim($sToken))
136                         );
137                     }
138                 }
139             }
140         }
141
142         return $oValidTokens;
143     }
144
145
146     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
147     {
148         // Check which tokens we have, get the ID numbers
149         $sSQL = 'SELECT word_id, word_token, type';
150         $sSQL .= "      info->>'cc' as country, info->>'postcode' as postcode,";
151         $sSQL .= "      info->>'word' as word, info->>'op' as operator,";
152         $sSQL .= "      info->>'class' as class, info->>'type' as type";
153         $sSQL .= ' FROM word WHERE word_token in (';
154         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
155
156         Debug::printSQL($sSQL);
157
158         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
159
160         foreach ($aDBWords as $aWord) {
161             $iId = (int) $aWord['word_id'];
162
163             switch ($aWord['type']) {
164                 'C':  // country name tokens
165                     if ($aWord['country'] === null
166                         || ($this->aCountryRestriction
167                             && !in_array($aWord['country'], $this->aCountryRestriction))
168                     ) {
169                         continue;
170                     }
171                     $oToken = new Token\Country($iId, $aWord['country'])
172                     break;
173                 'H':  // house number tokens
174                     $oToken = new Token\HouseNumber($iId, $aWord['word_token']);
175                     break;
176                 'P':  // postcode tokens
177                     // Postcodes are not normalized, so they may have content
178                     // that makes SQL injection possible. Reject postcodes
179                     // that would need special escaping.
180                     if ($aWord['postcode'] === null
181                         || pg_escape_string($aWord['postcode']) == $aWord['postcode']
182                     ) {
183                        continue;
184                     }
185                     $sNormPostcode = $this->normalizeString($aWord['postcode']);
186                     if (strpos($sNormQuery, $sNormPostcode) === false) {
187                         continue;
188                     }
189                     $oToken = new Token\Postcode($iId, $aWord['postcode'], null);
190                     break;
191                 'S':  // tokens for classification terms (special phrases)
192                     if ($aWord['class'] === null || $aWord['type'] === null
193                         || $aWord['word'] === null
194                         || strpos($sNormQuery, $aWord['word']) === false
195                     ) {
196                         continue;
197                     }
198                     $oToken = new Token\SpecialTerm(
199                         $iId,
200                         $aWord['class'],
201                         $aWord['type'],
202                         $aWord['op'] ? Operator::NEAR : Operator::NONE
203                     );
204                     break;
205                 default:
206                     continue;
207             }
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) {
213                     continue;
214                 }
215
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') {
219                     if ($aWord['word']
220                         && pg_escape_string($aWord['word']) == $aWord['word']
221                     ) {
222                         $oToken = new Token\Postcode(
223                             $iId,
224                             $aWord['word'],
225                             $aWord['country_code']
226                         );
227                     }
228                 } else {
229                     // near and in operator the same at the moment
230                     $oToken = new Token\SpecialTerm(
231                         $iId,
232                         $aWord['class'],
233                         $aWord['type'],
234                         $aWord['operator'] ? Operator::NEAR : Operator::NONE
235                     );
236                 }
237             } elseif ($aWord['country_code']) {
238                 // Filter country tokens that do not match restricted countries.
239                 if (!$this->aCountryRestriction
240                     || in_array($aWord['country_code'], $this->aCountryRestriction)
241                 ) {
242                     $oToken = new Token\Country($iId, $aWord['country_code']);
243                 }
244             } elseif ($aWord['word_token'][0] == ' ') {
245                  $oToken = new Token\Word(
246                      $iId,
247                      (int) $aWord['count'],
248                      substr_count($aWord['word_token'], ' ')
249                  );
250             } else {
251                 $oToken = new Token\Partial(
252                     $iId,
253                     $aWord['word_token'],
254                     (int) $aWord['count']
255                 );
256             }*/
257
258             $oValidTokens->addToken($aWord['word_token'], $oToken);
259         }
260     }
261
262
263     /**
264      * Add the tokens from this phrase to the given list of tokens.
265      *
266      * @param string[] $aTokens List of tokens to append.
267      *
268      * @return void
269      */
270     private static function addTokens(&$aTokens, $aWords)
271     {
272         $iNumWords = count($aWords);
273
274         for ($i = 0; $i < $iNumWords; $i++) {
275             $sPhrase = $aWords[$i];
276             $aTokens[$sPhrase] = $sPhrase;
277
278             for ($j = $i + 1; $j < $iNumWords; $j++) {
279                 $sPhrase .= ' '.$aWords[$j];
280                 $aTokens[$sPhrase] = $sPhrase;
281             }
282         }
283     }
284 }