]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/tokenizer/legacy_tokenizer.php
Merge remote-tracking branch 'upstream/master'
[nominatim.git] / lib-php / tokenizer / legacy_tokenizer.php
1 <?php
2 /**
3  * SPDX-License-Identifier: GPL-2.0-only
4  *
5  * This file is part of Nominatim. (https://nominatim.org)
6  *
7  * Copyright (C) 2022 by the Nominatim developer community.
8  * For a full list of authors see the git log.
9  */
10
11 namespace Nominatim;
12
13 require_once(CONST_LibDir.'/SimpleWordList.php');
14
15 class Tokenizer
16 {
17     private $oDB;
18
19     private $oNormalizer = null;
20
21     public function __construct(&$oDB)
22     {
23         $this->oDB =& $oDB;
24         $this->oNormalizer = \Transliterator::createFromRules(CONST_Term_Normalization_Rules);
25     }
26
27     public function checkStatus()
28     {
29         $sStandardWord = $this->oDB->getOne("SELECT make_standard_name('a')");
30         if ($sStandardWord === false) {
31             throw new \Exception('Module failed', 701);
32         }
33
34         if ($sStandardWord != 'a') {
35             throw new \Exception('Module call failed', 702);
36         }
37
38         $sSQL = "SELECT word_id FROM word WHERE word_token IN (' a')";
39         $iWordID = $this->oDB->getOne($sSQL);
40         if ($iWordID === false) {
41             throw new \Exception('Query failed', 703);
42         }
43         if (!$iWordID) {
44             throw new \Exception('No value', 704);
45         }
46     }
47
48
49     public function normalizeString($sTerm)
50     {
51         if ($this->oNormalizer === null) {
52             return $sTerm;
53         }
54
55         return $this->oNormalizer->transliterate($sTerm);
56     }
57
58
59     public function mostFrequentWords($iNum)
60     {
61         $sSQL = 'SELECT word FROM word WHERE word is not null ';
62         $sSQL .= 'ORDER BY search_name_count DESC LIMIT '.$iNum;
63         return $this->oDB->getCol($sSQL);
64     }
65
66
67     public function tokensForSpecialTerm($sTerm)
68     {
69         $aResults = array();
70
71         $sSQL = 'SELECT word_id, class, type FROM word ';
72         $sSQL .= '   WHERE word_token = \' \' || make_standard_name(:term)';
73         $sSQL .= '   AND class is not null AND class not in (\'place\')';
74
75         Debug::printVar('Term', $sTerm);
76         Debug::printSQL($sSQL);
77         $aSearchWords = $this->oDB->getAll($sSQL, array(':term' => $sTerm));
78
79         Debug::printVar('Results', $aSearchWords);
80
81         foreach ($aSearchWords as $aSearchTerm) {
82             $aResults[] = new \Nominatim\Token\SpecialTerm(
83                 $aSearchTerm['word_id'],
84                 $aSearchTerm['class'],
85                 $aSearchTerm['type'],
86                 \Nominatim\Operator::TYPE
87             );
88         }
89
90         Debug::printVar('Special term tokens', $aResults);
91
92         return $aResults;
93     }
94
95
96     public function extractTokensFromPhrases(&$aPhrases)
97     {
98         // First get the normalized version of all phrases
99         $sNormQuery = '';
100         $sSQL = 'SELECT ';
101         $aParams = array();
102         foreach ($aPhrases as $iPhrase => $oPhrase) {
103             $sNormQuery .= ','.$this->normalizeString($oPhrase->getPhrase());
104             $sSQL .= 'make_standard_name(:' .$iPhrase.') as p'.$iPhrase.',';
105             $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
106
107             // Conflicts between US state abbreviations and various words
108             // for 'the' in different languages
109             switch (strtolower($oPhrase->getPhrase())) {
110                 case 'il':
111                     $aParams[':'.$iPhrase] = 'illinois';
112                     break;
113                 case 'al':
114                     $aParams[':'.$iPhrase] = 'alabama';
115                     break;
116                 case 'la':
117                     $aParams[':'.$iPhrase] = 'louisiana';
118                     break;
119                 default:
120                     $aParams[':'.$iPhrase] = $oPhrase->getPhrase();
121                     break;
122             }
123         }
124         $sSQL = substr($sSQL, 0, -1);
125
126         Debug::printSQL($sSQL);
127         Debug::printVar('SQL parameters', $aParams);
128
129         $aNormPhrases = $this->oDB->getRow($sSQL, $aParams);
130
131         Debug::printVar('SQL result', $aNormPhrases);
132
133         // now compute all possible tokens
134         $aWordLists = array();
135         $aTokens = array();
136         foreach ($aNormPhrases as $sPhrase) {
137             $oWordList = new SimpleWordList($sPhrase);
138
139             foreach ($oWordList->getTokens() as $sToken) {
140                 $aTokens[' '.$sToken] = ' '.$sToken;
141                 $aTokens[$sToken] = $sToken;
142             }
143
144             $aWordLists[] = $oWordList;
145         }
146
147         Debug::printVar('Tokens', $aTokens);
148         Debug::printVar('WordLists', $aWordLists);
149
150         $oValidTokens = $this->computeValidTokens($aTokens, $sNormQuery);
151
152         foreach ($aPhrases as $iPhrase => $oPhrase) {
153             $oPhrase->setWordSets($aWordLists[$iPhrase]->getWordSets($oValidTokens));
154         }
155
156         return $oValidTokens;
157     }
158
159
160     private function computeValidTokens($aTokens, $sNormQuery)
161     {
162         $oValidTokens = new TokenList();
163
164         if (!empty($aTokens)) {
165             $this->addTokensFromDB($oValidTokens, $aTokens, $sNormQuery);
166
167             // Try more interpretations for Tokens that could not be matched.
168             foreach ($aTokens as $sToken) {
169                 if ($sToken[0] != ' ' && !$oValidTokens->contains($sToken)) {
170                     if (preg_match('/^([0-9]{5}) [0-9]{4}$/', $sToken, $aData)) {
171                         // US ZIP+4 codes - merge in the 5-digit ZIP code
172                         $oValidTokens->addToken(
173                             $sToken,
174                             new Token\Postcode(null, $aData[1], 'us')
175                         );
176                     } elseif (preg_match('/^[0-9]+$/', $sToken)) {
177                         // Unknown single word token with a number.
178                         // Assume it is a house number.
179                         $oValidTokens->addToken(
180                             $sToken,
181                             new Token\HouseNumber(null, trim($sToken))
182                         );
183                     }
184                 }
185             }
186         }
187
188         return $oValidTokens;
189     }
190
191
192     private function addTokensFromDB(&$oValidTokens, $aTokens, $sNormQuery)
193     {
194         // Check which tokens we have, get the ID numbers
195         $sSQL = 'SELECT word_id, word_token, word, class, type, country_code,';
196         $sSQL .= ' operator, coalesce(search_name_count, 0) as count';
197         $sSQL .= ' FROM word WHERE word_token in (';
198         $sSQL .= join(',', $this->oDB->getDBQuotedList($aTokens)).')';
199
200         Debug::printSQL($sSQL);
201
202         $aDBWords = $this->oDB->getAll($sSQL, null, 'Could not get word tokens.');
203
204         foreach ($aDBWords as $aWord) {
205             $oToken = null;
206             $iId = (int) $aWord['word_id'];
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                 $oToken = new Token\Country($iId, $aWord['country_code']);
239             } elseif ($aWord['word_token'][0] == ' ') {
240                 $oToken = new Token\Word(
241                     $iId,
242                     (int) $aWord['count'],
243                     substr_count($aWord['word_token'], ' ')
244                 );
245             // For backward compatibility: ignore all partial tokens with more
246             // than one word.
247             } elseif (strpos($aWord['word_token'], ' ') === false) {
248                 $oToken = new Token\Partial(
249                     $iId,
250                     $aWord['word_token'],
251                     (int) $aWord['count']
252                 );
253             }
254
255             if ($oToken) {
256                 // remove any leading spaces
257                 if ($aWord['word_token'][0] == ' ') {
258                     $oValidTokens->addToken(substr($aWord['word_token'], 1), $oToken);
259                 } else {
260                     $oValidTokens->addToken($aWord['word_token'], $oToken);
261                 }
262             }
263         }
264     }
265 }