]> git.openstreetmap.org Git - nominatim.git/blob - lib-php/setup/SetupClass.php
cf2ac6da29ff0749c58f9cb92fa31725ca0e9e83
[nominatim.git] / lib-php / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 require_once(CONST_LibDir.'/Shell.php');
6
7 class SetupFunctions
8 {
9     protected $iInstances;
10     protected $aDSNInfo;
11     protected $bQuiet;
12     protected $bVerbose;
13     protected $sIgnoreErrors;
14     protected $bEnableDiffUpdates;
15     protected $bEnableDebugStatements;
16     protected $bDrop;
17     protected $oDB = null;
18     protected $oNominatimCmd;
19
20     public function __construct(array $aCMDResult)
21     {
22         // by default, use all but one processor, but never more than 15.
23         $this->iInstances = isset($aCMDResult['threads'])
24             ? $aCMDResult['threads']
25             : (min(16, getProcessorCount()) - 1);
26
27         if ($this->iInstances < 1) {
28             $this->iInstances = 1;
29             warn('resetting threads to '.$this->iInstances);
30         }
31
32         // parse database string
33         $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
34         if (!isset($this->aDSNInfo['port'])) {
35             $this->aDSNInfo['port'] = 5432;
36         }
37
38         // setting member variables based on command line options stored in $aCMDResult
39         $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
40         $this->bVerbose = $aCMDResult['verbose'];
41
42         //setting default values which are not set by the update.php array
43         if (isset($aCMDResult['ignore-errors'])) {
44             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
45         } else {
46             $this->sIgnoreErrors = false;
47         }
48         if (isset($aCMDResult['enable-debug-statements'])) {
49             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
50         } else {
51             $this->bEnableDebugStatements = false;
52         }
53         if (isset($aCMDResult['enable-diff-updates'])) {
54             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
55         } else {
56             $this->bEnableDiffUpdates = false;
57         }
58
59         $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
60
61         $this->oNominatimCmd = new \Nominatim\Shell(getSetting('NOMINATIM_TOOL'));
62         if ($this->bQuiet) {
63             $this->oNominatimCmd->addParams('--quiet');
64         }
65         if ($this->bVerbose) {
66             $this->oNominatimCmd->addParams('--verbose');
67         }
68     }
69
70     public function calculatePostcodes($bCMDResultAll)
71     {
72         info('Calculate Postcodes');
73         $this->pgsqlRunScriptFile(CONST_SqlDir.'/postcode_tables.sql');
74
75         $sPostcodeFilename = CONST_InstallDir.'/gb_postcode_data.sql.gz';
76         if (file_exists($sPostcodeFilename)) {
77             $this->pgsqlRunScriptFile($sPostcodeFilename);
78         } else {
79             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
80         }
81
82         $sPostcodeFilename = CONST_InstallDir.'/us_postcode_data.sql.gz';
83         if (file_exists($sPostcodeFilename)) {
84             $this->pgsqlRunScriptFile($sPostcodeFilename);
85         } else {
86             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
87         }
88
89
90         $this->db()->exec('TRUNCATE location_postcode');
91
92         $sSQL  = 'INSERT INTO location_postcode';
93         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
94         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
95         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
96         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
97         $sSQL .= '  FROM placex';
98         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
99         $sSQL .= '       AND geometry IS NOT null';
100         $sSQL .= ' GROUP BY country_code, pc';
101         $this->db()->exec($sSQL);
102
103         // only add postcodes that are not yet available in OSM
104         $sSQL  = 'INSERT INTO location_postcode';
105         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
106         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
107         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
108         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
109         $sSQL .= '        (SELECT postcode FROM location_postcode';
110         $sSQL .= "          WHERE country_code = 'us')";
111         $this->db()->exec($sSQL);
112
113         // add missing postcodes for GB (if available)
114         $sSQL  = 'INSERT INTO location_postcode';
115         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
116         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
117         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
118         $sSQL .= '           (SELECT postcode FROM location_postcode';
119         $sSQL .= "             WHERE country_code = 'gb')";
120         $this->db()->exec($sSQL);
121
122         if (!$bCMDResultAll) {
123             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
124             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
125             $this->db()->exec($sSQL);
126         }
127
128         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
129         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
130         $this->db()->exec($sSQL);
131     }
132
133     public function createCountryNames()
134     {
135         info('Create search index for default country names');
136
137         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
138         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
139         $this->pgsqlRunScript('select count(*) from (select getorcreate_country(make_standard_name(country_code), country_code) from country_name where country_code is not null) as x');
140         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
141         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
142             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
143         $sLanguages = getSetting('LANGUAGES');
144         if ($sLanguages) {
145             $sSQL .= 'in ';
146             $sDelim = '(';
147             foreach (explode(',', $sLanguages) as $sLang) {
148                 $sSQL .= $sDelim."'name:$sLang'";
149                 $sDelim = ',';
150             }
151             $sSQL .= ')';
152         } else {
153             // all include all simple name tags
154             $sSQL .= "like 'name:%'";
155         }
156         $sSQL .= ') v';
157         $this->pgsqlRunScript($sSQL);
158     }
159
160     /**
161      * Return the connection to the database.
162      *
163      * @return Database object.
164      *
165      * Creates a new connection if none exists yet. Otherwise reuses the
166      * already established connection.
167      */
168     private function db()
169     {
170         if (is_null($this->oDB)) {
171             $this->oDB = new \Nominatim\DB();
172             $this->oDB->connect();
173         }
174
175         return $this->oDB;
176     }
177
178     private function pgsqlRunScript($sScript, $bfatal = true)
179     {
180         runSQLScript(
181             $sScript,
182             $bfatal,
183             $this->bVerbose,
184             $this->sIgnoreErrors
185         );
186     }
187
188     public function createSqlFunctions()
189     {
190         $oCmd = (clone($this->oNominatimCmd))
191                 ->addParams('refresh', '--functions');
192
193         if (!$this->bEnableDiffUpdates) {
194             $oCmd->addParams('--no-diff-updates');
195         }
196
197         if ($this->bEnableDebugStatements) {
198             $oCmd->addParams('--enable-debug-statements');
199         }
200
201         $oCmd->run(!$this->sIgnoreErrors);
202     }
203
204     private function pgsqlRunScriptFile($sFilename)
205     {
206         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
207
208         $oCmd = (new \Nominatim\Shell('psql'))
209                 ->addParams('--port', $this->aDSNInfo['port'])
210                 ->addParams('--dbname', $this->aDSNInfo['database']);
211
212         if (!$this->bVerbose) {
213             $oCmd->addParams('--quiet');
214         }
215         if (isset($this->aDSNInfo['hostspec'])) {
216             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
217         }
218         if (isset($this->aDSNInfo['username'])) {
219             $oCmd->addParams('--username', $this->aDSNInfo['username']);
220         }
221         if (isset($this->aDSNInfo['password'])) {
222             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
223         }
224         $ahGzipPipes = null;
225         if (preg_match('/\\.gz$/', $sFilename)) {
226             $aDescriptors = array(
227                              0 => array('pipe', 'r'),
228                              1 => array('pipe', 'w'),
229                              2 => array('file', '/dev/null', 'a')
230                             );
231             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
232
233             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
234             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
235             $aReadPipe = $ahGzipPipes[1];
236             fclose($ahGzipPipes[0]);
237         } else {
238             $oCmd->addParams('--file', $sFilename);
239             $aReadPipe = array('pipe', 'r');
240         }
241         $aDescriptors = array(
242                          0 => $aReadPipe,
243                          1 => array('pipe', 'w'),
244                          2 => array('file', '/dev/null', 'a')
245                         );
246         $ahPipes = null;
247
248         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
249         if (!is_resource($hProcess)) fail('unable to start pgsql');
250         // TODO: error checking
251         while (!feof($ahPipes[1])) {
252             echo fread($ahPipes[1], 4096);
253         }
254         fclose($ahPipes[1]);
255         $iReturn = proc_close($hProcess);
256         if ($iReturn > 0) {
257             fail("pgsql returned with error code ($iReturn)");
258         }
259         if ($ahGzipPipes) {
260             fclose($ahGzipPipes[1]);
261             proc_close($hGzipProcess);
262         }
263     }
264
265     private function replaceSqlPatterns($sSql)
266     {
267         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
268
269         $aPatterns = array(
270                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
271                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
272                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
273                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
274                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
275                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
276         );
277
278         foreach ($aPatterns as $sPattern => $sTablespace) {
279             if ($sTablespace) {
280                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
281             } else {
282                 $sSql = str_replace($sPattern, '', $sSql);
283             }
284         }
285
286         return $sSql;
287     }
288 }