]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_icu_tokenizer.php
Merge pull request #2314 from lonvia/fix-status-no-import-date
[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         $sNorm = ' '.$this->oTransliterator->transliterate($sTerm).' ';
51
52         return trim(str_replace(CONST_Abbreviations[0], CONST_Abbreviations[1], $sNorm));
53     }
54
55
56     public function tokensForSpecialTerm($sTerm)
57     {
58         $aResults = array();
59
60         $sSQL = 'SELECT word_id, class, type FROM word ';
61         $sSQL .= '   WHERE word_token = \' \' || :term';
62         $sSQL .= '   AND class is not null AND class not in (\'place\')';
63
64         Debug::printVar('Term', $sTerm);
65         Debug::printSQL($sSQL);
66         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $this->makeStandardWord($sTerm)));
67
68         Debug::printVar('Results', $aSearchWords);
69
70         foreach ($aSearchWords as $aSearchTerm) {
71             $aResults[] = new \Nominatim\Token\SpecialTerm(
72                 $aSearchTerm['word_id'],
73                 $aSearchTerm['class'],
74                 $aSearchTerm['type'],
75                 \Nominatim\Operator::TYPE
76             );
77         }
78
79         Debug::printVar('Special term tokens', $aResults);
80
81         return $aResults;
82     }
83
84
85     public function extractTokensFromPhrases(&$aPhrases)
86     {
87         $sNormQuery = '';
88         $aWordLists = array();
89         $aTokens = array();
90         foreach ($aPhrases as $iPhrase => $oPhrase) {
91             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
92             $sPhrase = $this->makeStandardWord($oPhrase->getPhrase());
93             if (strlen($sPhrase) > 0) {
94                 $aWords = explode(' ', $sPhrase);
95                 Tokenizer::addTokens($aTokens, $aWords);
96                 $aWordLists[] = $aWords;
97             } else {
98                 $aWordLists[] = array();
99             }
100         }
101
102         Debug::printVar('Tokens', $aTokens);
103         Debug::printVar('WordLists', $aWordLists);
104
105         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
106
107         foreach ($aPhrases as $iPhrase => $oPhrase) {
108             $oPhrase->computeWordSets($aWordLists[$iPhrase], $oValidTokens);
109         }
110
111         return $oValidTokens;
112     }
113
114
115     private function computeValidTokens($aTokens, $sNormQuery)
116     {
117         $oValidTokens = new TokenList();
118
119         if (!empty($aTokens)) {
120             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
121
122             // Try more interpretations for Tokens that could not be matched.
123             foreach ($aTokens as $sToken) {
124                 if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
125                     if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
126                         // US ZIP+4 codes - merge in the 5-digit ZIP code
127                         $oValidTokens->addToken(
128                             $sToken,
129                             new Token\Postcode(null, $aData[1], 'us')
130                         );
131                     } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
132                         // Unknown single word token with a number.
133                         // Assume it is a house number.
134                         $oValidTokens->addToken(
135                             $sToken,
136                             new Token\HouseNumber(null, trim($sToken))
137                         );
138                     }
139                 }
140             }
141         }
142
143         return $oValidTokens;
144     }
145
146
147     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
148     {
149         // Check which tokens we have, get the ID numbers
150         $sSQL = 'SELECT word_id, word_token, word, class, type, country_code,';
151         $sSQL .= ' operator, coalesce(search_name_count, 0) as count';
152         $sSQL .= ' FROM word WHERE word_token in (';
153         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
154
155         Debug::printSQL($sSQL);
156
157         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
158
159         foreach ($aDBWords as $aWord) {
160             $oToken = null;
161             $iId = (int) $aWord['word_id'];
162
163             if ($aWord['class']) {
164                 // Special terms need to appear in their normalized form.
165                 // (postcodes are not normalized in the word table)
166                 $sNormWord = $this->normalizeString($aWord['word']);
167                 if ($aWord['word'] && strpos($sNormQuery, $sNormWord) === false) {
168                     continue;
169                 }
170
171                 if ($aWord['class'] == 'place' && $aWord['type'] == 'house') {
172                     $oToken = new Token\HouseNumber($iId, trim($aWord['word_token']));
173                 } elseif ($aWord['class'] == 'place' && $aWord['type'] == 'postcode') {
174                     if ($aWord['word']
175                         && pg_escape_string($aWord['word']) == $aWord['word']
176                     ) {
177                         $oToken = new Token\Postcode(
178                             $iId,
179                             $aWord['word'],
180                             $aWord['country_code']
181                         );
182                     }
183                 } else {
184                     // near and in operator the same at the moment
185                     $oToken = new Token\SpecialTerm(
186                         $iId,
187                         $aWord['class'],
188                         $aWord['type'],
189                         $aWord['operator'] ? Operator::NEAR : Operator::NONE
190                     );
191                 }
192             } elseif ($aWord['country_code']) {
193                 // Filter country tokens that do not match restricted countries.
194                 if (!$this->aCountryRestriction
195                     || in_array($aWord['country_code'], $this->aCountryRestriction)
196                 ) {
197                     $oToken = new Token\Country($iId, $aWord['country_code']);
198                 }
199             } else {
200                 $oToken = new Token\Word(
201                     $iId,
202                     $aWord['word_token'][0] != ' ',
203                     (int) $aWord['count'],
204                     substr_count($aWord['word_token'], ' ')
205                 );
206             }
207
208             if ($oToken) {
209                 $oValidTokens->addToken($aWord['word_token'], $oToken);
210             }
211         }
212     }
213
214
215     /**
216      * Add the tokens from this phrase to the given list of tokens.
217      *
218      * @param string[] $aTokens List of tokens to append.
219      *
220      * @return void
221      */
222     private static function addTokens(&$aTokens, $aWords)
223     {
224         $iNumWords = count($aWords);
225
226         for ($i = 0; $i < $iNumWords; $i++) {
227             $sPhrase = $aWords[$i];
228             $aTokens[' '.$sPhrase] = ' '.$sPhrase;
229             $aTokens[$sPhrase] = $sPhrase;
230
231             for ($j = $i + 1; $j < $iNumWords; $j++) {
232                 $sPhrase .= ' '.$aWords[$j];
233                 $aTokens[' '.$sPhrase] = ' '.$sPhrase;
234                 $aTokens[$sPhrase] = $sPhrase;
235             }
236         }
237     }
238 }