]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_icu_tokenizer.php
ef79769c76bb2a7063cbb86dff67b3d09357e9f3
[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 limit 1';
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, info->>'class' as class, info->>'type' as type ";
59         $sSQL .= '   FROM word WHERE word_token = :term and type = \'S\'';
60
61         Debug::printVar('Term', $sTerm);
62         Debug::printSQL($sSQL);
63         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $this->makeStandardWord($sTerm)));
64
65         Debug::printVar('Results', $aSearchWords);
66
67         foreach ($aSearchWords as $aSearchTerm) {
68             $aResults[] = new \Nominatim\Token\SpecialTerm(
69                 $aSearchTerm['word_id'],
70                 $aSearchTerm['class'],
71                 $aSearchTerm['type'],
72                 \Nominatim\Operator::TYPE
73             );
74         }
75
76         Debug::printVar('Special term tokens', $aResults);
77
78         return $aResults;
79     }
80
81
82     public function extractTokensFromPhrases(&$aPhrases)
83     {
84         $sNormQuery = '';
85         $aWordLists = array();
86         $aTokens = array();
87         foreach ($aPhrases as $iPhrase => $oPhrase) {
88             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
89             $sPhrase = $this->makeStandardWord($oPhrase->getPhrase());
90             Debug::printVar('Phrase', $sPhrase);
91             if (strlen($sPhrase) > 0) {
92                 $aWords = explode(' ', $sPhrase);
93                 Tokenizer::addTokens($aTokens, $aWords);
94                 $aWordLists[] = $aWords;
95             } else {
96                 $aWordLists[] = array();
97             }
98         }
99
100         Debug::printVar('Tokens', $aTokens);
101         Debug::printVar('WordLists', $aWordLists);
102
103         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
104
105         foreach ($aPhrases as $iPhrase => $oPhrase) {
106             $oPhrase->computeWordSets($aWordLists[$iPhrase], $oValidTokens);
107         }
108
109         return $oValidTokens;
110     }
111
112
113     private function computeValidTokens($aTokens, $sNormQuery)
114     {
115         $oValidTokens = new TokenList();
116
117         if (!empty($aTokens)) {
118             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
119
120             // Try more interpretations for Tokens that could not be matched.
121             foreach ($aTokens as $sToken) {
122                 if ($sToken[0] != ' ' && !$oValidTokens->contains($sToken)) {
123                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
124                         // US ZIP+4 codes - merge in the 5-digit ZIP code
125                         $oValidTokens->addToken(
126                             $sToken,
127                             new Token\Postcode(null, $aData[1], 'us')
128                         );
129                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
130                         // Unknown single word token with a number.
131                         // Assume it is a house number.
132                         $oValidTokens->addToken(
133                             $sToken,
134                             new Token\HouseNumber(null, trim($sToken))
135                         );
136                     }
137                 }
138             }
139         }
140
141         return $oValidTokens;
142     }
143
144
145     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
146     {
147         // Check which tokens we have, get the ID numbers
148         $sSQL = 'SELECT word_id, word_token, type, word,';
149         $sSQL .= "      info->>'op' as operator,";
150         $sSQL .= "      info->>'class' as class, info->>'type' as ctype,";
151         $sSQL .= "      info->>'count' 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             $iId = (int) $aWord['word_id'];
161             $sTok = $aWord['word_token'];
162
163             switch ($aWord['type']) {
164                 case 'C':  // country name tokens
165                     if ($aWord['word'] !== null
166                         && (!$this->aCountryRestriction
167                             || in_array($aWord['word'], $this->aCountryRestriction))
168                     ) {
169                         $oValidTokens->addToken(
170                             $sTok,
171                             new Token\Country($iId, $aWord['word'])
172                         );
173                     }
174                     break;
175                 case 'H':  // house number tokens
176                     $oValidTokens->addToken($sTok, new Token\HouseNumber($iId, $aWord['word_token']));
177                     break;
178                 case 'P':  // postcode tokens
179                     // Postcodes are not normalized, so they may have content
180                     // that makes SQL injection possible. Reject postcodes
181                     // that would need special escaping.
182                     if ($aWord['word'] !== null
183                         && pg_escape_string($aWord['word']) == $aWord['word']
184                     ) {
185                         $sNormPostcode = $this->normalizeString($aWord['word']);
186                         if (strpos($sNormQuery, $sNormPostcode) !== false) {
187                             $oValidTokens->addToken(
188                                 $sTok,
189                                 new Token\Postcode($iId, $aWord['word'], null)
190                             );
191                         }
192                     }
193                     break;
194                 case 'S':  // tokens for classification terms (special phrases)
195                     if ($aWord['class'] !== null && $aWord['ctype'] !== null) {
196                         $oValidTokens->addToken($sTok, new Token\SpecialTerm(
197                             $iId,
198                             $aWord['class'],
199                             $aWord['ctype'],
200                             (isset($aWord['operator'])) ? Operator::NEAR : Operator::NONE
201                         ));
202                     }
203                     break;
204                 case 'W': // full-word tokens
205                     $oValidTokens->addToken($sTok, new Token\Word(
206                         $iId,
207                         (int) $aWord['count'],
208                         substr_count($aWord['word_token'], ' ')
209                     ));
210                     break;
211                 case 'w':  // partial word terms
212                     $oValidTokens->addToken($sTok, new Token\Partial(
213                         $iId,
214                         $aWord['word_token'],
215                         (int) $aWord['count']
216                     ));
217                     break;
218                 default:
219                     break;
220             }
221         }
222     }
223
224
225     /**
226      * Add the tokens from this phrase to the given list of tokens.
227      *
228      * @param string[] $aTokens List of tokens to append.
229      *
230      * @return void
231      */
232     private static function addTokens(&$aTokens, $aWords)
233     {
234         $iNumWords = count($aWords);
235
236         for ($i = 0; $i < $iNumWords; $i++) {
237             $sPhrase = $aWords[$i];
238             $aTokens[$sPhrase] = $sPhrase;
239
240             for ($j = $i + 1; $j < $iNumWords; $j++) {
241                 $sPhrase .= ' '.$aWords[$j];
242                 $aTokens[$sPhrase] = $sPhrase;
243             }
244         }
245     }
246 }