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