]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_tokenizer.php
introduce a separate token type for partials
[nominatim.git] / lib-php / tokenizer / legacy_tokenizer.php
1 <?php
2
3 namespace Nominatim;
4
5 class Tokenizer
6 {
7     private $oDB;
8
9     private $oNormalizer = null;
10     private $aCountryRestriction = null;
11
12     public function __construct(&$oDB)
13     {
14         $this->oDB =& $oDB;
15         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
16     }
17
18     public function checkStatus()
19     {
20         $sStandardWord = $this->oDB->getOne("SELECT make_standard_name('a')");
21         if ($sStandardWord === false) {
22             throw new Exception('Module failed', 701);
23         }
24
25         if ($sStandardWord != 'a') {
26             throw new Exception('Module call failed', 702);
27         }
28
29         $sSQL = "SELECT word_id FROM word WHERE word_token IN (' a')";
30         $iWordID = $this->oDB->getOne($sSQL);
31         if ($iWordID === false) {
32             throw new Exception('Query failed', 703);
33         }
34         if (!$iWordID) {
35             throw new Exception('No value', 704);
36         }
37     }
38
39
40     public function setCountryRestriction($aCountries)
41     {
42         $this->aCountryRestriction = $aCountries;
43     }
44
45
46     public function normalizeString($sTerm)
47     {
48         if ($this->oNormalizer === null) {
49             return $sTerm;
50         }
51
52         return $this->oNormalizer->transliterate($sTerm);
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 = \' \' || make_standard_name(: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' => $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         // First get the normalized version of all phrases
88         $sNormQuery = '';
89         $sSQL = 'SELECT ';
90         $aParams = array();
91         foreach ($aPhrases as $iPhrase => $oPhrase) {
92             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
93             $sSQL .= 'make_standard_name(:' .$iPhrase.') as p'.$iPhrase.',';
94             $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
95         }
96         $sSQL = substr($sSQL, 0, -1);
97
98         Debug::printSQL($sSQL);
99         Debug::printVar('SQL parameters', $aParams);
100
101         $aNormPhrases = $this->oDB->getRow($sSQL, $aParams);
102
103         Debug::printVar('SQL result', $aNormPhrases);
104
105         // now compute all possible tokens
106         $aWordLists = array();
107         $aTokens = array();
108         foreach ($aNormPhrases as $sPhrase) {
109             if (strlen($sPhrase) > 0) {
110                 $aWords = explode(' ', $sPhrase);
111                 Tokenizer::addTokens($aTokens, $aWords);
112                 $aWordLists[] = $aWords;
113             } else {
114                 $aWordLists[] = array();
115             }
116         }
117
118         Debug::printVar('Tokens', $aTokens);
119         Debug::printVar('WordLists', $aWordLists);
120
121         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
122
123         foreach ($aPhrases as $iPhrase => $oPhrase) {
124             $oPhrase->computeWordSets($aWordLists[$iPhrase], $oValidTokens);
125         }
126
127         return $oValidTokens;
128     }
129
130
131     private function computeValidTokens($aTokens, $sNormQuery)
132     {
133         $oValidTokens = new TokenList();
134
135         if (!empty($aTokens)) {
136             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
137
138             // Try more interpretations for Tokens that could not be matched.
139             foreach ($aTokens as $sToken) {
140                 if ($sToken[0] == ' ' && !$oValidTokens->contains($sToken)) {
141                     if (preg_match('/^ ([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
142                         // US ZIP+4 codes - merge in the 5-digit ZIP code
143                         $oValidTokens->addToken(
144                             $sToken,
145                             new Token\Postcode(null, $aData[1], 'us')
146                         );
147                     } elseif (preg_match('/^ [0-9]+$/', $sToken)) {
148                         // Unknown single word token with a number.
149                         // Assume it is a house number.
150                         $oValidTokens->addToken(
151                             $sToken,
152                             new Token\HouseNumber(null, trim($sToken))
153                         );
154                     }
155                 }
156             }
157         }
158
159         return $oValidTokens;
160     }
161
162
163     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
164     {
165         // Check which tokens we have, get the ID numbers
166         $sSQL = 'SELECT word_id, word_token, word, class, type, country_code,';
167         $sSQL .= ' operator, coalesce(search_name_count, 0) as count';
168         $sSQL .= ' FROM word WHERE word_token in (';
169         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
170
171         Debug::printSQL($sSQL);
172
173         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
174
175         foreach ($aDBWords as $aWord) {
176             $oToken = null;
177             $iId = (int) $aWord['word_id'];
178
179             if ($aWord['class']) {
180                 // Special terms need to appear in their normalized form.
181                 // (postcodes are not normalized in the word table)
182                 $sNormWord = $this->normalizeString($aWord['word']);
183                 if ($aWord['word'] && strpos($sNormQuery, $sNormWord) === false) {
184                     continue;
185                 }
186
187                 if ($aWord['class'] == 'place' && $aWord['type'] == 'house') {
188                     $oToken = new Token\HouseNumber($iId, trim($aWord['word_token']));
189                 } elseif ($aWord['class'] == 'place' && $aWord['type'] == 'postcode') {
190                     if ($aWord['word']
191                         && pg_escape_string($aWord['word']) == $aWord['word']
192                     ) {
193                         $oToken = new Token\Postcode(
194                             $iId,
195                             $aWord['word'],
196                             $aWord['country_code']
197                         );
198                     }
199                 } else {
200                     // near and in operator the same at the moment
201                     $oToken = new Token\SpecialTerm(
202                         $iId,
203                         $aWord['class'],
204                         $aWord['type'],
205                         $aWord['operator'] ? Operator::NEAR : Operator::NONE
206                     );
207                 }
208             } elseif ($aWord['country_code']) {
209                 // Filter country tokens that do not match restricted countries.
210                 if (!$this->aCountryRestriction
211                     || in_array($aWord['country_code'], $this->aCountryRestriction)
212                 ) {
213                     $oToken = new Token\Country($iId, $aWord['country_code']);
214                 }
215             } elseif ($aWord['word_token'][0] == ' ') {
216                 $oToken = new Token\Word(
217                     $iId,
218                     (int) $aWord['count'],
219                     substr_count($aWord['word_token'], ' ')
220                 );
221             } else {
222                 $oToken = new Token\Partial(
223                     $iId,
224                     (int) $aWord['count']
225                 );
226             }
227
228             if ($oToken) {
229                 // remove any leading spaces
230                 if ($aWord['word_token'][0] == ' ') {
231                     $oValidTokens->addToken(substr($aWord['word_token'], 1), $oToken);
232                 } else {
233                     $oValidTokens->addToken($aWord['word_token'], $oToken);
234                 }
235             }
236         }
237     }
238
239
240     /**
241      * Add the tokens from this phrase to the given list of tokens.
242      *
243      * @param string[] $aTokens List of tokens to append.
244      *
245      * @return void
246      */
247     private static function addTokens(&$aTokens, $aWords)
248     {
249         $iNumWords = count($aWords);
250
251         for ($i = 0; $i < $iNumWords; $i++) {
252             $sPhrase = $aWords[$i];
253             $aTokens[' '.$sPhrase] = ' '.$sPhrase;
254             $aTokens[$sPhrase] = $sPhrase;
255
256             for ($j = $i + 1; $j < $iNumWords; $j++) {
257                 $sPhrase .= ' '.$aWords[$j];
258                 $aTokens[' '.$sPhrase] = ' '.$sPhrase;
259                 $aTokens[$sPhrase] = $sPhrase;
260             }
261         }
262     }
263 }