]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_tokenizer.php
allow relative paths for log files
[nominatim.git] / lib-php / tokenizer / legacy_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 = null;
12
13     public function __construct(&$oDB)
14     {
15         $this->oDB =& $oDB;
16         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
17     }
18
19     public function checkStatus()
20     {
21         $sStandardWord = $this->oDB->getOne("SELECT make_standard_name('a')");
22         if ($sStandardWord === false) {
23             throw new \Exception('Module failed', 701);
24         }
25
26         if ($sStandardWord != 'a') {
27             throw new \Exception('Module call failed', 702);
28         }
29
30         $sSQL = "SELECT word_id FROM word WHERE word_token IN (' a')";
31         $iWordID = $this->oDB->getOne($sSQL);
32         if ($iWordID === false) {
33             throw new \Exception('Query failed', 703);
34         }
35         if (!$iWordID) {
36             throw new \Exception('No value', 704);
37         }
38     }
39
40
41     public function normalizeString($sTerm)
42     {
43         if ($this->oNormalizer === null) {
44             return $sTerm;
45         }
46
47         return $this->oNormalizer->transliterate($sTerm);
48     }
49
50
51     public function tokensForSpecialTerm($sTerm)
52     {
53         $aResults = array();
54
55         $sSQL = 'SELECT word_id, class, type FROM word ';
56         $sSQL .= '   WHERE word_token = \' \' || make_standard_name(:term)';
57         $sSQL .= '   AND class is not null AND class not in (\'place\')';
58
59         Debug::printVar('Term', $sTerm);
60         Debug::printSQL($sSQL);
61         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $sTerm));
62
63         Debug::printVar('Results', $aSearchWords);
64
65         foreach ($aSearchWords as $aSearchTerm) {
66             $aResults[] = new \Nominatim\Token\SpecialTerm(
67                 $aSearchTerm['word_id'],
68                 $aSearchTerm['class'],
69                 $aSearchTerm['type'],
70                 \Nominatim\Operator::TYPE
71             );
72         }
73
74         Debug::printVar('Special term tokens', $aResults);
75
76         return $aResults;
77     }
78
79
80     public function extractTokensFromPhrases(&$aPhrases)
81     {
82         // First get the normalized version of all phrases
83         $sNormQuery = '';
84         $sSQL = 'SELECT ';
85         $aParams = array();
86         foreach ($aPhrases as $iPhrase => $oPhrase) {
87             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
88             $sSQL .= 'make_standard_name(:' .$iPhrase.') as p'.$iPhrase.',';
89             $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
90
91             // Conflicts between US state abbreviations and various words
92             // for 'the' in different languages
93             switch (strtolower($oPhrase->getPhrase())) {
94                 case 'il':
95                     $aParams[':'.$iPhrase] = 'illinois';
96                     break;
97                 case 'al':
98                     $aParams[':'.$iPhrase] = 'alabama';
99                     break;
100                 case 'la':
101                     $aParams[':'.$iPhrase] = 'louisiana';
102                     break;
103                 default:
104                     $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
105                     break;
106             }
107         }
108         $sSQL = substr($sSQL, 0, -1);
109
110         Debug::printSQL($sSQL);
111         Debug::printVar('SQL parameters', $aParams);
112
113         $aNormPhrases = $this->oDB->getRow($sSQL, $aParams);
114
115         Debug::printVar('SQL result', $aNormPhrases);
116
117         // now compute all possible tokens
118         $aWordLists = array();
119         $aTokens = array();
120         foreach ($aNormPhrases as $sPhrase) {
121             $oWordList = new SimpleWordList($sPhrase);
122
123             foreach ($oWordList->getTokens() as $sToken) {
124                 $aTokens[' '.$sToken] = ' '.$sToken;
125                 $aTokens[$sToken] = $sToken;
126             }
127
128             $aWordLists[] = $oWordList;
129         }
130
131         Debug::printVar('Tokens', $aTokens);
132         Debug::printVar('WordLists', $aWordLists);
133
134         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
135
136         foreach ($aPhrases as $iPhrase => $oPhrase) {
137             $oPhrase->setWordSets($aWordLists[$iPhrase]->getWordSets($oValidTokens));
138         }
139
140         return $oValidTokens;
141     }
142
143
144     private function computeValidTokens($aTokens, $sNormQuery)
145     {
146         $oValidTokens = new TokenList();
147
148         if (!empty($aTokens)) {
149             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
150
151             // Try more interpretations for Tokens that could not be matched.
152             foreach ($aTokens as $sToken) {
153                 if ($sToken[0] != ' ' && !$oValidTokens->contains($sToken)) {
154                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
155                         // US ZIP+4 codes - merge in the 5-digit ZIP code
156                         $oValidTokens->addToken(
157                             $sToken,
158                             new Token\Postcode(null, $aData[1], 'us')
159                         );
160                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
161                         // Unknown single word token with a number.
162                         // Assume it is a house number.
163                         $oValidTokens->addToken(
164                             $sToken,
165                             new Token\HouseNumber(null, trim($sToken))
166                         );
167                     }
168                 }
169             }
170         }
171
172         return $oValidTokens;
173     }
174
175
176     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
177     {
178         // Check which tokens we have, get the ID numbers
179         $sSQL = 'SELECT word_id, word_token, word, class, type, country_code,';
180         $sSQL .= ' operator, coalesce(search_name_count, 0) as count';
181         $sSQL .= ' FROM word WHERE word_token in (';
182         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
183
184         Debug::printSQL($sSQL);
185
186         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
187
188         foreach ($aDBWords as $aWord) {
189             $oToken = null;
190             $iId = (int) $aWord['word_id'];
191
192             if ($aWord['class']) {
193                 // Special terms need to appear in their normalized form.
194                 // (postcodes are not normalized in the word table)
195                 $sNormWord = $this->normalizeString($aWord['word']);
196                 if ($aWord['word'] && strpos($sNormQuery, $sNormWord) === false) {
197                     continue;
198                 }
199
200                 if ($aWord['class'] == 'place' && $aWord['type'] == 'house') {
201                     $oToken = new Token\HouseNumber($iId, trim($aWord['word_token']));
202                 } elseif ($aWord['class'] == 'place' && $aWord['type'] == 'postcode') {
203                     if ($aWord['word']
204                         && pg_escape_string($aWord['word']) == $aWord['word']
205                     ) {
206                         $oToken = new Token\Postcode(
207                             $iId,
208                             $aWord['word'],
209                             $aWord['country_code']
210                         );
211                     }
212                 } else {
213                     // near and in operator the same at the moment
214                     $oToken = new Token\SpecialTerm(
215                         $iId,
216                         $aWord['class'],
217                         $aWord['type'],
218                         $aWord['operator'] ? Operator::NEAR : Operator::NONE
219                     );
220                 }
221             } elseif ($aWord['country_code']) {
222                 $oToken = new Token\Country($iId, $aWord['country_code']);
223             } elseif ($aWord['word_token'][0] == ' ') {
224                 $oToken = new Token\Word(
225                     $iId,
226                     (int) $aWord['count'],
227                     substr_count($aWord['word_token'], ' ')
228                 );
229             // For backward compatibility: ignore all partial tokens with more
230             // than one word.
231             } elseif (strpos($aWord['word_token'], ' ') === false) {
232                 $oToken = new Token\Partial(
233                     $iId,
234                     $aWord['word_token'],
235                     (int) $aWord['count']
236                 );
237             }
238
239             if ($oToken) {
240                 // remove any leading spaces
241                 if ($aWord['word_token'][0] == ' ') {
242                     $oValidTokens->addToken(substr($aWord['word_token'], 1), $oToken);
243                 } else {
244                     $oValidTokens->addToken($aWord['word_token'], $oToken);
245                 }
246             }
247         }
248     }
249 }