]> git.openstreetmap.org Git - nominatim.git/blob - lib/setup/SetupClass.php
Merge pull request #2115 from lonvia/use-dotenv
[nominatim.git] / lib / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 require_once(CONST_LibDir.'/setup/AddressLevelParser.php');
6 require_once(CONST_LibDir.'/Shell.php');
7
8 class SetupFunctions
9 {
10     protected $iCacheMemory;
11     protected $iInstances;
12     protected $sModulePath;
13     protected $aDSNInfo;
14     protected $bQuiet;
15     protected $bVerbose;
16     protected $sIgnoreErrors;
17     protected $bEnableDiffUpdates;
18     protected $bEnableDebugStatements;
19     protected $bNoPartitions;
20     protected $bDrop;
21     protected $oDB = null;
22
23     public function __construct(array $aCMDResult)
24     {
25         // by default, use all but one processor, but never more than 15.
26         $this->iInstances = isset($aCMDResult['threads'])
27             ? $aCMDResult['threads']
28             : (min(16, getProcessorCount()) - 1);
29
30         if ($this->iInstances < 1) {
31             $this->iInstances = 1;
32             warn('resetting threads to '.$this->iInstances);
33         }
34
35         if (isset($aCMDResult['osm2pgsql-cache'])) {
36             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
37         } elseif (getSetting('FLATNODE_FILE')) {
38             // When flatnode files are enabled then disable cache per default.
39             $this->iCacheMemory = 0;
40         } else {
41             // Otherwise: Assume we can steal all the cache memory in the box.
42             $this->iCacheMemory = getCacheMemoryMB();
43         }
44
45         $this->sModulePath = getSetting('DATABASE_MODULE_PATH', CONST_InstallDir.'/module');
46         info('module path: ' . $this->sModulePath);
47
48         // parse database string
49         $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
50         if (!isset($this->aDSNInfo['port'])) {
51             $this->aDSNInfo['port'] = 5432;
52         }
53
54         // setting member variables based on command line options stored in $aCMDResult
55         $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
56         $this->bVerbose = $aCMDResult['verbose'];
57
58         //setting default values which are not set by the update.php array
59         if (isset($aCMDResult['ignore-errors'])) {
60             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
61         } else {
62             $this->sIgnoreErrors = false;
63         }
64         if (isset($aCMDResult['enable-debug-statements'])) {
65             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
66         } else {
67             $this->bEnableDebugStatements = false;
68         }
69         if (isset($aCMDResult['no-partitions'])) {
70             $this->bNoPartitions = $aCMDResult['no-partitions'];
71         } else {
72             $this->bNoPartitions = false;
73         }
74         if (isset($aCMDResult['enable-diff-updates'])) {
75             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
76         } else {
77             $this->bEnableDiffUpdates = false;
78         }
79
80         $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
81     }
82
83     public function createDB()
84     {
85         info('Create DB');
86         $oDB = new \Nominatim\DB;
87
88         if ($oDB->checkConnection()) {
89             fail('database already exists ('.getSetting('DATABASE_DSN').')');
90         }
91
92         $oCmd = (new \Nominatim\Shell('createdb'))
93                 ->addParams('-E', 'UTF-8')
94                 ->addParams('-p', $this->aDSNInfo['port']);
95
96         if (isset($this->aDSNInfo['username'])) {
97             $oCmd->addParams('-U', $this->aDSNInfo['username']);
98         }
99         if (isset($this->aDSNInfo['password'])) {
100             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
101         }
102         if (isset($this->aDSNInfo['hostspec'])) {
103             $oCmd->addParams('-h', $this->aDSNInfo['hostspec']);
104         }
105         $oCmd->addParams($this->aDSNInfo['database']);
106
107         $result = $oCmd->run();
108         if ($result != 0) fail('Error executing external command: '.$oCmd->escapedCmd());
109     }
110
111     public function setupDB()
112     {
113         info('Setup DB');
114
115         $fPostgresVersion = $this->db()->getPostgresVersion();
116         echo 'Postgres version found: '.$fPostgresVersion."\n";
117
118         if ($fPostgresVersion < 9.03) {
119             fail('Minimum supported version of Postgresql is 9.3.');
120         }
121
122         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
123         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
124
125         $fPostgisVersion = $this->db()->getPostgisVersion();
126         echo 'Postgis version found: '.$fPostgisVersion."\n";
127
128         if ($fPostgisVersion < 2.2) {
129             echo "Minimum required Postgis version 2.2\n";
130             exit(1);
131         }
132
133         $sPgUser = getSetting('DATABASE_WEBUSER');
134         $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
135         if ($i == 0) {
136             echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
137             echo "\n          createuser ".$sPgUser."\n\n";
138             exit(1);
139         }
140
141         // Try accessing the C module, so we know early if something is wrong
142         $this->checkModulePresence(); // raises exception on failure
143
144         if (!file_exists(CONST_DataDir.'/data/country_osm_grid.sql.gz')) {
145             echo 'Error: you need to download the country_osm_grid first:';
146             echo "\n    wget -O ".CONST_DataDir."/data/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
147             exit(1);
148         }
149         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_name.sql');
150         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_osm_grid.sql.gz');
151         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/gb_postcode_table.sql');
152         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/us_postcode_table.sql');
153
154         $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
155         if (file_exists($sPostcodeFilename)) {
156             $this->pgsqlRunScriptFile($sPostcodeFilename);
157         } else {
158             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
159         }
160
161         $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
162         if (file_exists($sPostcodeFilename)) {
163             $this->pgsqlRunScriptFile($sPostcodeFilename);
164         } else {
165             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
166         }
167
168         if ($this->bNoPartitions) {
169             $this->pgsqlRunScript('update country_name set partition = 0');
170         }
171     }
172
173     public function importData($sOSMFile)
174     {
175         info('Import data');
176
177         if (!file_exists(getOsm2pgsqlBinary())) {
178             echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
179             echo "Normally you should not need to set this manually.\n";
180             fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
181         }
182
183         $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
184         $oCmd->addParams('--style', getImportStyle());
185
186         if (getSetting('FLATNODE_FILE')) {
187             $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
188         }
189         if (getSetting('TABLESPACE_OSM_DATA')) {
190             $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
191         }
192         if (getSetting('TABLESPACE_OSM_INDEX')) {
193             $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
194         }
195         if (getSetting('TABLESPACE_PLACE_DATA')) {
196             $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
197         }
198         if (getSetting('TABLESPACE_PLACE_INDEX')) {
199             $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
200         }
201         $oCmd->addParams('--latlong', '--slim', '--create');
202         $oCmd->addParams('--output', 'gazetteer');
203         $oCmd->addParams('--hstore');
204         $oCmd->addParams('--number-processes', 1);
205         $oCmd->addParams('--with-forward-dependencies', 'false');
206         $oCmd->addParams('--log-progress', 'true');
207         $oCmd->addParams('--cache', $this->iCacheMemory);
208         $oCmd->addParams('--port', $this->aDSNInfo['port']);
209
210         if (isset($this->aDSNInfo['username'])) {
211             $oCmd->addParams('--username', $this->aDSNInfo['username']);
212         }
213         if (isset($this->aDSNInfo['password'])) {
214             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
215         }
216         if (isset($this->aDSNInfo['hostspec'])) {
217             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
218         }
219         $oCmd->addParams('--database', $this->aDSNInfo['database']);
220         $oCmd->addParams($sOSMFile);
221         $oCmd->run();
222
223         if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
224             fail('No Data');
225         }
226
227         if ($this->bDrop) {
228             $this->dropTable('planet_osm_nodes');
229             $this->removeFlatnodeFile();
230         }
231     }
232
233     public function createFunctions()
234     {
235         info('Create Functions');
236
237         // Try accessing the C module, so we know early if something is wrong
238         $this->checkModulePresence(); // raises exception on failure
239
240         $this->createSqlFunctions();
241     }
242
243     public function createTables($bReverseOnly = false)
244     {
245         info('Create Tables');
246
247         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
248         $sTemplate = $this->replaceSqlPatterns($sTemplate);
249
250         $this->pgsqlRunScript($sTemplate, false);
251
252         if ($bReverseOnly) {
253             $this->dropTable('search_name');
254         }
255
256         $oAlParser = new AddressLevelParser(getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json'));
257         $oAlParser->createTable($this->db(), 'address_levels');
258     }
259
260     public function createTableTriggers()
261     {
262         info('Create Tables');
263
264         $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
265         $sTemplate = $this->replaceSqlPatterns($sTemplate);
266
267         $this->pgsqlRunScript($sTemplate, false);
268     }
269
270     public function createPartitionTables()
271     {
272         info('Create Partition Tables');
273
274         $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
275         $sTemplate = $this->replaceSqlPatterns($sTemplate);
276
277         $this->pgsqlRunPartitionScript($sTemplate);
278     }
279
280     public function createPartitionFunctions()
281     {
282         info('Create Partition Functions');
283
284         $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
285         $this->pgsqlRunPartitionScript($sTemplate);
286     }
287
288     public function importWikipediaArticles()
289     {
290         $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
291         $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
292         if (file_exists($sWikiArticlesFile)) {
293             info('Importing wikipedia articles and redirects');
294             $this->dropTable('wikipedia_article');
295             $this->dropTable('wikipedia_redirect');
296             $this->pgsqlRunScriptFile($sWikiArticlesFile);
297         } else {
298             warn('wikipedia importance dump file not found - places will have default importance');
299         }
300     }
301
302     public function loadData($bDisableTokenPrecalc)
303     {
304         info('Drop old Data');
305
306         $oDB = $this->db();
307
308         $oDB->exec('TRUNCATE word');
309         echo '.';
310         $oDB->exec('TRUNCATE placex');
311         echo '.';
312         $oDB->exec('TRUNCATE location_property_osmline');
313         echo '.';
314         $oDB->exec('TRUNCATE place_addressline');
315         echo '.';
316         $oDB->exec('TRUNCATE location_area');
317         echo '.';
318         if (!$this->dbReverseOnly()) {
319             $oDB->exec('TRUNCATE search_name');
320             echo '.';
321         }
322         $oDB->exec('TRUNCATE search_name_blank');
323         echo '.';
324         $oDB->exec('DROP SEQUENCE seq_place');
325         echo '.';
326         $oDB->exec('CREATE SEQUENCE seq_place start 100000');
327         echo '.';
328
329         $sSQL = 'select distinct partition from country_name';
330         $aPartitions = $oDB->getCol($sSQL);
331
332         if (!$this->bNoPartitions) $aPartitions[] = 0;
333         foreach ($aPartitions as $sPartition) {
334             $oDB->exec('TRUNCATE location_road_'.$sPartition);
335             echo '.';
336         }
337
338         // used by getorcreate_word_id to ignore frequent partial words
339         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
340         $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
341         $oDB->exec($sSQL);
342         echo ".\n";
343
344         // pre-create the word list
345         if (!$bDisableTokenPrecalc) {
346             info('Loading word list');
347             $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
348         }
349
350         info('Load Data');
351         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
352
353         $aDBInstances = array();
354         $iLoadThreads = max(1, $this->iInstances - 1);
355         for ($i = 0; $i < $iLoadThreads; $i++) {
356             // https://secure.php.net/manual/en/function.pg-connect.php
357             $DSN = getSetting('DATABASE_DSN');
358             $DSN = preg_replace('/^pgsql:/', '', $DSN);
359             $DSN = preg_replace('/;/', ' ', $DSN);
360             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
361             pg_ping($aDBInstances[$i]);
362         }
363
364         for ($i = 0; $i < $iLoadThreads; $i++) {
365             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
366             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
367             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
368             $sSQL .= ' and ST_IsValid(geometry)';
369             if ($this->bVerbose) echo "$sSQL\n";
370             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
371                 fail(pg_last_error($aDBInstances[$i]));
372             }
373         }
374
375         // last thread for interpolation lines
376         // https://secure.php.net/manual/en/function.pg-connect.php
377         $DSN = getSetting('DATABASE_DSN');
378         $DSN = preg_replace('/^pgsql:/', '', $DSN);
379         $DSN = preg_replace('/;/', ' ', $DSN);
380         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
381         pg_ping($aDBInstances[$iLoadThreads]);
382         $sSQL = 'insert into location_property_osmline';
383         $sSQL .= ' (osm_id, address, linegeo)';
384         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
385         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
386         if ($this->bVerbose) echo "$sSQL\n";
387         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
388             fail(pg_last_error($aDBInstances[$iLoadThreads]));
389         }
390
391         $bFailed = false;
392         for ($i = 0; $i <= $iLoadThreads; $i++) {
393             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
394                 $resultStatus = pg_result_status($hPGresult);
395                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
396                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
397                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
398                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
399                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
400                     $resultError = pg_result_error($hPGresult);
401                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
402                     $bFailed = true;
403                 }
404             }
405         }
406         if ($bFailed) {
407             fail('SQL errors loading placex and/or location_property_osmline tables');
408         }
409
410         for ($i = 0; $i < $this->iInstances; $i++) {
411             pg_close($aDBInstances[$i]);
412         }
413
414         echo "\n";
415         info('Reanalysing database');
416         $this->pgsqlRunScript('ANALYSE');
417
418         $sDatabaseDate = getDatabaseDate($oDB);
419         $oDB->exec('TRUNCATE import_status');
420         if (!$sDatabaseDate) {
421             warn('could not determine database date.');
422         } else {
423             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
424             $oDB->exec($sSQL);
425             echo "Latest data imported from $sDatabaseDate.\n";
426         }
427     }
428
429     public function importTigerData($sTigerPath)
430     {
431         info('Import Tiger data');
432
433         $aFilenames = glob($sTigerPath.'/*.sql');
434         info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
435         if (empty($aFilenames)) {
436             warn('Tiger data import selected but no files found in path '.$sTigerPath);
437             return;
438         }
439         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
440         $sTemplate = $this->replaceSqlPatterns($sTemplate);
441
442         $this->pgsqlRunScript($sTemplate, false);
443
444         $aDBInstances = array();
445         for ($i = 0; $i < $this->iInstances; $i++) {
446             // https://secure.php.net/manual/en/function.pg-connect.php
447             $DSN = getSetting('DATABASE_DSN');
448             $DSN = preg_replace('/^pgsql:/', '', $DSN);
449             $DSN = preg_replace('/;/', ' ', $DSN);
450             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
451             pg_ping($aDBInstances[$i]);
452         }
453
454         foreach ($aFilenames as $sFile) {
455             echo $sFile.': ';
456             $hFile = fopen($sFile, 'r');
457             $sSQL = fgets($hFile, 100000);
458             $iLines = 0;
459             while (true) {
460                 for ($i = 0; $i < $this->iInstances; $i++) {
461                     if (!pg_connection_busy($aDBInstances[$i])) {
462                         while (pg_get_result($aDBInstances[$i]));
463                         $sSQL = fgets($hFile, 100000);
464                         if (!$sSQL) break 2;
465                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
466                         $iLines++;
467                         if ($iLines == 1000) {
468                             echo '.';
469                             $iLines = 0;
470                         }
471                     }
472                 }
473                 usleep(10);
474             }
475             fclose($hFile);
476
477             $bAnyBusy = true;
478             while ($bAnyBusy) {
479                 $bAnyBusy = false;
480                 for ($i = 0; $i < $this->iInstances; $i++) {
481                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
482                 }
483                 usleep(10);
484             }
485             echo "\n";
486         }
487
488         for ($i = 0; $i < $this->iInstances; $i++) {
489             pg_close($aDBInstances[$i]);
490         }
491
492         info('Creating indexes on Tiger data');
493         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
494         $sTemplate = $this->replaceSqlPatterns($sTemplate);
495
496         $this->pgsqlRunScript($sTemplate, false);
497     }
498
499     public function calculatePostcodes($bCMDResultAll)
500     {
501         info('Calculate Postcodes');
502         $this->db()->exec('TRUNCATE location_postcode');
503
504         $sSQL  = 'INSERT INTO location_postcode';
505         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
506         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
507         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
508         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
509         $sSQL .= '  FROM placex';
510         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
511         $sSQL .= '       AND geometry IS NOT null';
512         $sSQL .= ' GROUP BY country_code, pc';
513         $this->db()->exec($sSQL);
514
515         // only add postcodes that are not yet available in OSM
516         $sSQL  = 'INSERT INTO location_postcode';
517         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
518         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
519         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
520         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
521         $sSQL .= '        (SELECT postcode FROM location_postcode';
522         $sSQL .= "          WHERE country_code = 'us')";
523         $this->db()->exec($sSQL);
524
525         // add missing postcodes for GB (if available)
526         $sSQL  = 'INSERT INTO location_postcode';
527         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
528         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
529         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
530         $sSQL .= '           (SELECT postcode FROM location_postcode';
531         $sSQL .= "             WHERE country_code = 'gb')";
532         $this->db()->exec($sSQL);
533
534         if (!$bCMDResultAll) {
535             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
536             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
537             $this->db()->exec($sSQL);
538         }
539
540         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
541         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
542         $this->db()->exec($sSQL);
543     }
544
545     public function index($bIndexNoanalyse)
546     {
547         $this->checkModulePresence(); // raises exception on failure
548
549         $oBaseCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
550                     ->addParams('--database', $this->aDSNInfo['database'])
551                     ->addParams('--port', $this->aDSNInfo['port'])
552                     ->addParams('--threads', $this->iInstances);
553
554         if (!$this->bQuiet) {
555             $oBaseCmd->addParams('-v');
556         }
557         if ($this->bVerbose) {
558             $oBaseCmd->addParams('-v');
559         }
560         if (isset($this->aDSNInfo['hostspec'])) {
561             $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
562         }
563         if (isset($this->aDSNInfo['username'])) {
564             $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
565         }
566         if (isset($this->aDSNInfo['password'])) {
567             $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
568         }
569
570         info('Index ranks 0 - 4');
571         $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
572         echo $oCmd->escapedCmd();
573
574         $iStatus = $oCmd->run();
575         if ($iStatus != 0) {
576             fail('error status ' . $iStatus . ' running nominatim!');
577         }
578         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
579
580         info('Index administrative boundaries');
581         $oCmd = (clone $oBaseCmd)->addParams('-b');
582         $iStatus = $oCmd->run();
583         if ($iStatus != 0) {
584             fail('error status ' . $iStatus . ' running nominatim!');
585         }
586
587         info('Index ranks 5 - 25');
588         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
589         $iStatus = $oCmd->run();
590         if ($iStatus != 0) {
591             fail('error status ' . $iStatus . ' running nominatim!');
592         }
593
594         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
595
596         info('Index ranks 26 - 30');
597         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
598         $iStatus = $oCmd->run();
599         if ($iStatus != 0) {
600             fail('error status ' . $iStatus . ' running nominatim!');
601         }
602
603         info('Index postcodes');
604         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
605         $this->db()->exec($sSQL);
606     }
607
608     public function createSearchIndices()
609     {
610         info('Create Search indices');
611
612         $sSQL = 'SELECT relname FROM pg_class, pg_index ';
613         $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
614         $aInvalidIndices = $this->db()->getCol($sSQL);
615
616         foreach ($aInvalidIndices as $sIndexName) {
617             info("Cleaning up invalid index $sIndexName");
618             $this->db()->exec("DROP INDEX $sIndexName;");
619         }
620
621         $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
622         if (!$this->bDrop) {
623             $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
624         }
625         if (!$this->dbReverseOnly()) {
626             $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
627         }
628         $sTemplate = $this->replaceSqlPatterns($sTemplate);
629
630         $this->pgsqlRunScript($sTemplate);
631     }
632
633     public function createCountryNames()
634     {
635         info('Create search index for default country names');
636
637         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
638         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
639         $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');
640         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
641         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
642             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
643         $sLanguages = getSetting('LANGUAGES');
644         if ($sLanguages) {
645             $sSQL .= 'in ';
646             $sDelim = '(';
647             foreach (explode(',', $sLanguages) as $sLang) {
648                 $sSQL .= $sDelim."'name:$sLang'";
649                 $sDelim = ',';
650             }
651             $sSQL .= ')';
652         } else {
653             // all include all simple name tags
654             $sSQL .= "like 'name:%'";
655         }
656         $sSQL .= ') v';
657         $this->pgsqlRunScript($sSQL);
658     }
659
660     public function drop()
661     {
662         info('Drop tables only required for updates');
663
664         // The implementation is potentially a bit dangerous because it uses
665         // a positive selection of tables to keep, and deletes everything else.
666         // Including any tables that the unsuspecting user might have manually
667         // created. USE AT YOUR OWN PERIL.
668         // tables we want to keep. everything else goes.
669         $aKeepTables = array(
670                         '*columns',
671                         'import_polygon_*',
672                         'import_status',
673                         'place_addressline',
674                         'location_postcode',
675                         'location_property*',
676                         'placex',
677                         'search_name',
678                         'seq_*',
679                         'word',
680                         'query_log',
681                         'new_query_log',
682                         'spatial_ref_sys',
683                         'country_name',
684                         'place_classtype_*',
685                         'country_osm_grid'
686                        );
687
688         $aDropTables = array();
689         $aHaveTables = $this->db()->getListOfTables();
690
691         foreach ($aHaveTables as $sTable) {
692             $bFound = false;
693             foreach ($aKeepTables as $sKeep) {
694                 if (fnmatch($sKeep, $sTable)) {
695                     $bFound = true;
696                     break;
697                 }
698             }
699             if (!$bFound) array_push($aDropTables, $sTable);
700         }
701         foreach ($aDropTables as $sDrop) {
702             $this->dropTable($sDrop);
703         }
704
705         $this->removeFlatnodeFile();
706     }
707
708     /**
709      * Setup the directory for the API scripts.
710      *
711      * @return null
712      */
713     public function setupWebsite()
714     {
715         if (!is_dir(CONST_InstallDir.'/website')) {
716             info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
717             mkdir(CONST_InstallDir.'/website');
718         }
719
720         $aScripts = array(
721           'deletable.php',
722           'details.php',
723           'lookup.php',
724           'polygons.php',
725           'reverse.php',
726           'search.php',
727           'status.php'
728         );
729
730         foreach ($aScripts as $sScript) {
731             $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
732
733             fwrite($rFile, "<?php\n\n");
734             fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
735
736             fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
737             fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
738             fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
739
740             fwrite($rFile, "if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));\n\n");
741
742             fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
743             fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
744             fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
745             fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
746             fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
747             fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
748             fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
749             fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
750             fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
751             fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
752             fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
753             fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
754             fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
755             fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
756
757             // XXX scripts should go into the library.
758             fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
759             fclose($rFile);
760
761             chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
762         }
763     }
764
765     /**
766      * Return the connection to the database.
767      *
768      * @return Database object.
769      *
770      * Creates a new connection if none exists yet. Otherwise reuses the
771      * already established connection.
772      */
773     private function db()
774     {
775         if (is_null($this->oDB)) {
776             $this->oDB = new \Nominatim\DB();
777             $this->oDB->connect();
778         }
779
780         return $this->oDB;
781     }
782
783     private function removeFlatnodeFile()
784     {
785         $sFName = getSetting('FLATNODE_FILE');
786         if ($sFName && file_exists($sFName)) {
787             if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
788             unlink($sFName);
789         }
790     }
791
792     private function pgsqlRunScript($sScript, $bfatal = true)
793     {
794         runSQLScript(
795             $sScript,
796             $bfatal,
797             $this->bVerbose,
798             $this->sIgnoreErrors
799         );
800     }
801
802     private function createSqlFunctions()
803     {
804         $sBasePath = CONST_DataDir.'/sql/functions/';
805         $sTemplate = file_get_contents($sBasePath.'utils.sql');
806         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
807         $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
808         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
809         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
810         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
811         if ($this->db()->tableExists('place')) {
812             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
813         }
814         if ($this->db()->tableExists('placex')) {
815             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
816         }
817         if ($this->db()->tableExists('location_postcode')) {
818             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
819         }
820         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
821         if ($this->bEnableDiffUpdates) {
822             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
823         }
824         if ($this->bEnableDebugStatements) {
825             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
826         }
827         if (getSettingBool('LIMIT_REINDEXING')) {
828             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
829         }
830         if (!getSettingBool('USE_US_TIGER_DATA')) {
831             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
832         }
833         if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
834             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
835         }
836
837         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
838         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
839
840         $this->pgsqlRunScript($sTemplate);
841     }
842
843     private function pgsqlRunPartitionScript($sTemplate)
844     {
845         $sSQL = 'select distinct partition from country_name';
846         $aPartitions = $this->db()->getCol($sSQL);
847         if (!$this->bNoPartitions) $aPartitions[] = 0;
848
849         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
850         foreach ($aMatches as $aMatch) {
851             $sResult = '';
852             foreach ($aPartitions as $sPartitionName) {
853                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
854             }
855             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
856         }
857
858         $this->pgsqlRunScript($sTemplate);
859     }
860
861     private function pgsqlRunScriptFile($sFilename)
862     {
863         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
864
865         $oCmd = (new \Nominatim\Shell('psql'))
866                 ->addParams('--port', $this->aDSNInfo['port'])
867                 ->addParams('--dbname', $this->aDSNInfo['database']);
868
869         if (!$this->bVerbose) {
870             $oCmd->addParams('--quiet');
871         }
872         if (isset($this->aDSNInfo['hostspec'])) {
873             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
874         }
875         if (isset($this->aDSNInfo['username'])) {
876             $oCmd->addParams('--username', $this->aDSNInfo['username']);
877         }
878         if (isset($this->aDSNInfo['password'])) {
879             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
880         }
881         $ahGzipPipes = null;
882         if (preg_match('/\\.gz$/', $sFilename)) {
883             $aDescriptors = array(
884                              0 => array('pipe', 'r'),
885                              1 => array('pipe', 'w'),
886                              2 => array('file', '/dev/null', 'a')
887                             );
888             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
889
890             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
891             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
892             $aReadPipe = $ahGzipPipes[1];
893             fclose($ahGzipPipes[0]);
894         } else {
895             $oCmd->addParams('--file', $sFilename);
896             $aReadPipe = array('pipe', 'r');
897         }
898         $aDescriptors = array(
899                          0 => $aReadPipe,
900                          1 => array('pipe', 'w'),
901                          2 => array('file', '/dev/null', 'a')
902                         );
903         $ahPipes = null;
904
905         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
906         if (!is_resource($hProcess)) fail('unable to start pgsql');
907         // TODO: error checking
908         while (!feof($ahPipes[1])) {
909             echo fread($ahPipes[1], 4096);
910         }
911         fclose($ahPipes[1]);
912         $iReturn = proc_close($hProcess);
913         if ($iReturn > 0) {
914             fail("pgsql returned with error code ($iReturn)");
915         }
916         if ($ahGzipPipes) {
917             fclose($ahGzipPipes[1]);
918             proc_close($hGzipProcess);
919         }
920     }
921
922     private function replaceSqlPatterns($sSql)
923     {
924         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
925
926         $aPatterns = array(
927                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
928                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
929                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
930                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
931                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
932                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
933         );
934
935         foreach ($aPatterns as $sPattern => $sTablespace) {
936             if ($sTablespace) {
937                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
938             } else {
939                 $sSql = str_replace($sPattern, '', $sSql);
940             }
941         }
942
943         return $sSql;
944     }
945
946     /**
947      * Drop table with the given name if it exists.
948      *
949      * @param string $sName Name of table to remove.
950      *
951      * @return null
952      */
953     private function dropTable($sName)
954     {
955         if ($this->bVerbose) echo "Dropping table $sName\n";
956         $this->db()->deleteTable($sName);
957     }
958
959     /**
960      * Check if the database is in reverse-only mode.
961      *
962      * @return True if there is no search_name table and infrastructure.
963      */
964     private function dbReverseOnly()
965     {
966         return !($this->db()->tableExists('search_name'));
967     }
968
969     /**
970      * Try accessing the C module, so we know early if something is wrong.
971      *
972      * Raises Nominatim\DatabaseError on failure
973      */
974     private function checkModulePresence()
975     {
976         $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
977         $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
978         $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
979
980         $oDB = new \Nominatim\DB();
981         $oDB->connect();
982         $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');
983     }
984 }