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