]> git.openstreetmap.org Git - nominatim.git/blob - lib/setup/SetupClass.php
16c4872982a0413d039c205153164a6510287ab7
[nominatim.git] / lib / setup / SetupClass.php
1 <?php
2
3 namespace Nominatim\Setup;
4
5 require_once(CONST_BasePath.'/lib/setup/AddressLevelParser.php');
6 require_once(CONST_BasePath.'/lib/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 (!is_null(CONST_Osm2pgsql_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 = CONST_Database_Module_Path;
46         info('module path: ' . $this->sModulePath);
47
48         // parse database string
49         $this->aDSNInfo = \Nominatim\DB::parseDSN(CONST_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 ('.CONST_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 connect()
112     {
113         $this->oDB = new \Nominatim\DB();
114         $this->oDB->connect();
115     }
116
117     public function setupDB()
118     {
119         info('Setup DB');
120
121         $fPostgresVersion = $this->oDB->getPostgresVersion();
122         echo 'Postgres version found: '.$fPostgresVersion."\n";
123
124         if ($fPostgresVersion < 9.03) {
125             fail('Minimum supported version of Postgresql is 9.3.');
126         }
127
128         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
129         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
130
131         $fPostgisVersion = $this->oDB->getPostgisVersion();
132         echo 'Postgis version found: '.$fPostgisVersion."\n";
133
134         if ($fPostgisVersion < 2.2) {
135             echo "Minimum required Postgis version 2.2\n";
136             exit(1);
137         }
138
139         $i = $this->oDB->getOne("select count(*) from pg_user where usename = '".CONST_Database_Web_User."'");
140         if ($i == 0) {
141             echo "\nERROR: Web user '".CONST_Database_Web_User."' does not exist. Create it with:\n";
142             echo "\n          createuser ".CONST_Database_Web_User."\n\n";
143             exit(1);
144         }
145
146         // Try accessing the C module, so we know early if something is wrong
147         checkModulePresence(); // raises exception on failure
148
149         if (!file_exists(CONST_ExtraDataPath.'/country_osm_grid.sql.gz')) {
150             echo 'Error: you need to download the country_osm_grid first:';
151             echo "\n    wget -O ".CONST_ExtraDataPath."/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
152             exit(1);
153         }
154         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
155         $this->pgsqlRunScriptFile(CONST_ExtraDataPath.'/country_osm_grid.sql.gz');
156         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
157         $this->pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode_table.sql');
158
159         $sPostcodeFilename = CONST_BasePath.'/data/gb_postcode_data.sql.gz';
160         if (file_exists($sPostcodeFilename)) {
161             $this->pgsqlRunScriptFile($sPostcodeFilename);
162         } else {
163             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
164         }
165
166         $sPostcodeFilename = CONST_BasePath.'/data/us_postcode_data.sql.gz';
167         if (file_exists($sPostcodeFilename)) {
168             $this->pgsqlRunScriptFile($sPostcodeFilename);
169         } else {
170             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
171         }
172
173         if ($this->bNoPartitions) {
174             $this->pgsqlRunScript('update country_name set partition = 0');
175         }
176     }
177
178     public function importData($sOSMFile)
179     {
180         info('Import data');
181
182         if (!file_exists(CONST_Osm2pgsql_Binary)) {
183             echo "Check CONST_Osm2pgsql_Binary in your local settings file.\n";
184             echo "Normally you should not need to set this manually.\n";
185             fail("osm2pgsql not found in '".CONST_Osm2pgsql_Binary."'");
186         }
187
188         $oCmd = new \Nominatim\Shell(CONST_Osm2pgsql_Binary);
189         $oCmd->addParams('--style', CONST_Import_Style);
190
191         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
192             $oCmd->addParams('--flat-nodes', CONST_Osm2pgsql_Flatnode_File);
193         }
194         if (CONST_Tablespace_Osm2pgsql_Data) {
195             $oCmd->addParams('--tablespace-slim-data', CONST_Tablespace_Osm2pgsql_Data);
196         }
197         if (CONST_Tablespace_Osm2pgsql_Index) {
198             $oCmd->addParams('--tablespace-slim-index', CONST_Tablespace_Osm2pgsql_Index);
199         }
200         if (CONST_Tablespace_Place_Data) {
201             $oCmd->addParams('--tablespace-main-data', CONST_Tablespace_Place_Data);
202         }
203         if (CONST_Tablespace_Place_Index) {
204             $oCmd->addParams('--tablespace-main-index', CONST_Tablespace_Place_Index);
205         }
206         $oCmd->addParams('--latlong', '--slim', '--create');
207         $oCmd->addParams('--output', 'gazetteer');
208         $oCmd->addParams('--hstore');
209         $oCmd->addParams('--number-processes', 1);
210         $oCmd->addParams('--cache', $this->iCacheMemory);
211         $oCmd->addParams('--port', $this->aDSNInfo['port']);
212
213         if (isset($this->aDSNInfo['username'])) {
214             $oCmd->addParams('--username', $this->aDSNInfo['username']);
215         }
216         if (isset($this->aDSNInfo['password'])) {
217             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
218         }
219         if (isset($this->aDSNInfo['hostspec'])) {
220             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
221         }
222         $oCmd->addParams('--database', $this->aDSNInfo['database']);
223         $oCmd->addParams($sOSMFile);
224         $oCmd->run();
225
226         if (!$this->sIgnoreErrors && !$this->oDB->getRow('select * from place limit 1')) {
227             fail('No Data');
228         }
229
230         if ($this->bDrop) {
231             $this->dropTable('planet_osm_nodes');
232             $this->removeFlatnodeFile();
233         }
234     }
235
236     public function createFunctions()
237     {
238         info('Create Functions');
239
240         // Try accessing the C module, so we know early if something is wrong
241         checkModulePresence(); // raises exception on failure
242
243         $this->createSqlFunctions();
244     }
245
246     public function createTables($bReverseOnly = false)
247     {
248         info('Create Tables');
249
250         $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
251         $sTemplate = $this->replaceSqlPatterns($sTemplate);
252
253         $this->pgsqlRunScript($sTemplate, false);
254
255         if ($bReverseOnly) {
256             $this->dropTable('search_name');
257         }
258
259         $oAlParser = new AddressLevelParser(CONST_Address_Level_Config);
260         $oAlParser->createTable($this->oDB, 'address_levels');
261     }
262
263     public function createTableTriggers()
264     {
265         info('Create Tables');
266
267         $sTemplate = file_get_contents(CONST_BasePath.'/sql/table-triggers.sql');
268         $sTemplate = $this->replaceSqlPatterns($sTemplate);
269
270         $this->pgsqlRunScript($sTemplate, false);
271     }
272
273     public function createPartitionTables()
274     {
275         info('Create Partition Tables');
276
277         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
278         $sTemplate = $this->replaceSqlPatterns($sTemplate);
279
280         $this->pgsqlRunPartitionScript($sTemplate);
281     }
282
283     public function createPartitionFunctions()
284     {
285         info('Create Partition Functions');
286
287         $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
288         $this->pgsqlRunPartitionScript($sTemplate);
289     }
290
291     public function importWikipediaArticles()
292     {
293         $sWikiArticlesFile = CONST_Wikipedia_Data_Path.'/wikimedia-importance.sql.gz';
294         if (file_exists($sWikiArticlesFile)) {
295             info('Importing wikipedia articles and redirects');
296             $this->dropTable('wikipedia_article');
297             $this->dropTable('wikipedia_redirect');
298             $this->pgsqlRunScriptFile($sWikiArticlesFile);
299         } else {
300             warn('wikipedia importance dump file not found - places will have default importance');
301         }
302     }
303
304     public function loadData($bDisableTokenPrecalc)
305     {
306         info('Drop old Data');
307
308         $this->oDB->exec('TRUNCATE word');
309         echo '.';
310         $this->oDB->exec('TRUNCATE placex');
311         echo '.';
312         $this->oDB->exec('TRUNCATE location_property_osmline');
313         echo '.';
314         $this->oDB->exec('TRUNCATE place_addressline');
315         echo '.';
316         $this->oDB->exec('TRUNCATE location_area');
317         echo '.';
318         if (!$this->dbReverseOnly()) {
319             $this->oDB->exec('TRUNCATE search_name');
320             echo '.';
321         }
322         $this->oDB->exec('TRUNCATE search_name_blank');
323         echo '.';
324         $this->oDB->exec('DROP SEQUENCE seq_place');
325         echo '.';
326         $this->oDB->exec('CREATE SEQUENCE seq_place start 100000');
327         echo '.';
328
329         $sSQL = 'select distinct partition from country_name';
330         $aPartitions = $this->oDB->getCol($sSQL);
331
332         if (!$this->bNoPartitions) $aPartitions[] = 0;
333         foreach ($aPartitions as $sPartition) {
334             $this->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 '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
341         $this->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_BasePath.'/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 = CONST_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 = CONST_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($this->oDB);
419         $this->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             $this->oDB->exec($sSQL);
425             echo "Latest data imported from $sDatabaseDate.\n";
426         }
427     }
428
429     public function importTigerData()
430     {
431         info('Import Tiger data');
432
433         $aFilenames = glob(CONST_Tiger_Data_Path.'/*.sql');
434         info('Found '.count($aFilenames).' SQL files in path '.CONST_Tiger_Data_Path);
435         if (empty($aFilenames)) {
436             warn('Tiger data import selected but no files found in path '.CONST_Tiger_Data_Path);
437             return;
438         }
439         $sTemplate = file_get_contents(CONST_BasePath.'/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 = CONST_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_BasePath.'/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->oDB->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->oDB->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->oDB->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->oDB->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->oDB->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->oDB->exec($sSQL);
543     }
544
545     public function index($bIndexNoanalyse)
546     {
547         $oBaseCmd = (new \Nominatim\Shell(CONST_BasePath.'/nominatim/nominatim.py'))
548                     ->addParams('--database', $this->aDSNInfo['database'])
549                     ->addParams('--port', $this->aDSNInfo['port'])
550                     ->addParams('--threads', $this->iInstances);
551
552         if (!$this->bQuiet) {
553             $oBaseCmd->addParams('-v');
554         }
555         if ($this->bVerbose) {
556             $oBaseCmd->addParams('-v');
557         }
558         if (isset($this->aDSNInfo['hostspec'])) {
559             $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
560         }
561         if (isset($this->aDSNInfo['username'])) {
562             $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
563         }
564         if (isset($this->aDSNInfo['password'])) {
565             $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
566         }
567
568         info('Index ranks 0 - 4');
569         $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
570         echo $oCmd->escapedCmd();
571         
572         $iStatus = $oCmd->run();
573         if ($iStatus != 0) {
574             fail('error status ' . $iStatus . ' running nominatim!');
575         }
576         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
577
578         info('Index ranks 5 - 25');
579         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
580         $iStatus = $oCmd->run();
581         if ($iStatus != 0) {
582             fail('error status ' . $iStatus . ' running nominatim!');
583         }
584         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
585
586         info('Index ranks 26 - 30');
587         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
588         $iStatus = $oCmd->run();
589         if ($iStatus != 0) {
590             fail('error status ' . $iStatus . ' running nominatim!');
591         }
592
593         info('Index postcodes');
594         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
595         $this->oDB->exec($sSQL);
596     }
597
598     public function createSearchIndices()
599     {
600         info('Create Search indices');
601
602         $sSQL = 'SELECT relname FROM pg_class, pg_index ';
603         $sSQL .= 'WHERE pg_index.indisvalid = false AND pg_index.indexrelid = pg_class.oid';
604         $aInvalidIndices = $this->oDB->getCol($sSQL);
605
606         foreach ($aInvalidIndices as $sIndexName) {
607             info("Cleaning up invalid index $sIndexName");
608             $this->oDB->exec("DROP INDEX $sIndexName;");
609         }
610
611         $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
612         if (!$this->bDrop) {
613             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_updates.src.sql');
614         }
615         if (!$this->dbReverseOnly()) {
616             $sTemplate .= file_get_contents(CONST_BasePath.'/sql/indices_search.src.sql');
617         }
618         $sTemplate = $this->replaceSqlPatterns($sTemplate);
619
620         $this->pgsqlRunScript($sTemplate);
621     }
622
623     public function createCountryNames()
624     {
625         info('Create search index for default country names');
626
627         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('uk'), 'gb')");
628         $this->pgsqlRunScript("select getorcreate_country(make_standard_name('united states'), 'us')");
629         $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');
630         $this->pgsqlRunScript("select count(*) from (select getorcreate_country(make_standard_name(name->'name'), country_code) from country_name where name ? 'name') as x");
631         $sSQL = 'select count(*) from (select getorcreate_country(make_standard_name(v),'
632             .'country_code) from (select country_code, skeys(name) as k, svals(name) as v from country_name) x where k ';
633         if (CONST_Languages) {
634             $sSQL .= 'in ';
635             $sDelim = '(';
636             foreach (explode(',', CONST_Languages) as $sLang) {
637                 $sSQL .= $sDelim."'name:$sLang'";
638                 $sDelim = ',';
639             }
640             $sSQL .= ')';
641         } else {
642             // all include all simple name tags
643             $sSQL .= "like 'name:%'";
644         }
645         $sSQL .= ') v';
646         $this->pgsqlRunScript($sSQL);
647     }
648
649     public function drop()
650     {
651         info('Drop tables only required for updates');
652
653         // The implementation is potentially a bit dangerous because it uses
654         // a positive selection of tables to keep, and deletes everything else.
655         // Including any tables that the unsuspecting user might have manually
656         // created. USE AT YOUR OWN PERIL.
657         // tables we want to keep. everything else goes.
658         $aKeepTables = array(
659                         '*columns',
660                         'import_polygon_*',
661                         'import_status',
662                         'place_addressline',
663                         'location_postcode',
664                         'location_property*',
665                         'placex',
666                         'search_name',
667                         'seq_*',
668                         'word',
669                         'query_log',
670                         'new_query_log',
671                         'spatial_ref_sys',
672                         'country_name',
673                         'place_classtype_*',
674                         'country_osm_grid'
675                        );
676
677         $aDropTables = array();
678         $aHaveTables = $this->oDB->getListOfTables();
679
680         foreach ($aHaveTables as $sTable) {
681             $bFound = false;
682             foreach ($aKeepTables as $sKeep) {
683                 if (fnmatch($sKeep, $sTable)) {
684                     $bFound = true;
685                     break;
686                 }
687             }
688             if (!$bFound) array_push($aDropTables, $sTable);
689         }
690         foreach ($aDropTables as $sDrop) {
691             $this->dropTable($sDrop);
692         }
693
694         $this->removeFlatnodeFile();
695     }
696
697     /**
698      * Setup settings-frontend.php in the build/website directory
699      *
700      * @return null
701      */
702     public function setupWebsite()
703     {
704         $rOutputFile = fopen(CONST_InstallPath.'/website/settings-frontend.php', 'w');
705
706         fwrite($rOutputFile, "<?php
707 @define('CONST_BasePath', '".CONST_BasePath."');
708 if (file_exists(getenv('NOMINATIM_SETTINGS'))) require_once(getenv('NOMINATIM_SETTINGS'));
709
710 @define('CONST_Debug', ". (CONST_Debug? 'true' : 'false').");
711 @define('CONST_Database_DSN', '".CONST_Database_DSN."'); // or add ;host=...;port=...;user=...;password=...
712 @define('CONST_Default_Language', ".(CONST_Default_Language ? 'true' : 'false').");
713 @define('CONST_Default_Lat', ".CONST_Default_Lat.");
714 @define('CONST_Default_Lon', ".CONST_Default_Lon.");
715 @define('CONST_Default_Zoom', ".CONST_Default_Zoom.");
716 @define('CONST_Map_Tile_URL', '".CONST_Map_Tile_URL."');
717 @define('CONST_Map_Tile_Attribution', '".CONST_Map_Tile_Attribution."'); // Set if tile source isn't osm.org
718 @define('CONST_Log_DB', ".(CONST_Log_DB ? 'true' : 'false').");
719 @define('CONST_Log_File', ".(CONST_Log_File ? 'true' : 'false').");
720 @define('CONST_Max_Word_Frequency', '".CONST_Max_Word_Frequency."');
721 @define('CONST_NoAccessControl', ".CONST_NoAccessControl.");
722 @define('CONST_Places_Max_ID_count', ".CONST_Places_Max_ID_count.");
723 @define('CONST_PolygonOutput_MaximumTypes', ".CONST_PolygonOutput_MaximumTypes.");
724 @define('CONST_Search_AreaPolygons', ".CONST_Search_AreaPolygons.");
725 @define('CONST_Search_BatchMode', ".(CONST_Search_BatchMode ? 'true' : 'false').");
726 @define('CONST_Search_NameOnlySearchFrequencyThreshold', ".CONST_Search_NameOnlySearchFrequencyThreshold.");
727 @define('CONST_Search_ReversePlanForAll', ".CONST_Search_ReversePlanForAll.");
728 @define('CONST_Term_Normalization_Rules', \"".CONST_Term_Normalization_Rules."\");
729 @define('CONST_Use_Aux_Location_data', ".(CONST_Use_Aux_Location_data ? 'true' : 'false').");
730 @define('CONST_Use_US_Tiger_Data', ".(CONST_Use_US_Tiger_Data ? 'true' : 'false').");
731 @define('CONST_Website_BaseURL', '".CONST_Website_BaseURL."');
732 ");
733         info(CONST_InstallPath.'/website/settings-frontend.php has been set up successfully');
734     }
735
736     private function removeFlatnodeFile()
737     {
738         if (!is_null(CONST_Osm2pgsql_Flatnode_File) && CONST_Osm2pgsql_Flatnode_File) {
739             if (file_exists(CONST_Osm2pgsql_Flatnode_File)) {
740                 if ($this->bVerbose) echo 'Deleting '.CONST_Osm2pgsql_Flatnode_File."\n";
741                 unlink(CONST_Osm2pgsql_Flatnode_File);
742             }
743         }
744     }
745
746     private function pgsqlRunScript($sScript, $bfatal = true)
747     {
748         runSQLScript(
749             $sScript,
750             $bfatal,
751             $this->bVerbose,
752             $this->sIgnoreErrors
753         );
754     }
755
756     private function createSqlFunctions()
757     {
758         $sBasePath = CONST_BasePath.'/sql/functions/';
759         $sTemplate = file_get_contents($sBasePath.'utils.sql');
760         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
761         $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
762         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
763         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
764         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
765         if ($this->oDB->tableExists('place')) {
766             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
767         }
768         if ($this->oDB->tableExists('placex')) {
769             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
770         }
771         if ($this->oDB->tableExists('location_postcode')) {
772             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
773         }
774         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
775         if ($this->bEnableDiffUpdates) {
776             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
777         }
778         if ($this->bEnableDebugStatements) {
779             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
780         }
781         if (CONST_Limit_Reindexing) {
782             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
783         }
784         if (!CONST_Use_US_Tiger_Data) {
785             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
786         }
787         if (!CONST_Use_Aux_Location_data) {
788             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
789         }
790
791         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
792         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
793
794         $this->pgsqlRunScript($sTemplate);
795     }
796
797     private function pgsqlRunPartitionScript($sTemplate)
798     {
799         $sSQL = 'select distinct partition from country_name';
800         $aPartitions = $this->oDB->getCol($sSQL);
801         if (!$this->bNoPartitions) $aPartitions[] = 0;
802
803         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
804         foreach ($aMatches as $aMatch) {
805             $sResult = '';
806             foreach ($aPartitions as $sPartitionName) {
807                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
808             }
809             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
810         }
811
812         $this->pgsqlRunScript($sTemplate);
813     }
814
815     private function pgsqlRunScriptFile($sFilename)
816     {
817         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
818
819         $oCmd = (new \Nominatim\Shell('psql'))
820                 ->addParams('--port', $this->aDSNInfo['port'])
821                 ->addParams('--dbname', $this->aDSNInfo['database']);
822
823         if (!$this->bVerbose) {
824             $oCmd->addParams('--quiet');
825         }
826         if (isset($this->aDSNInfo['hostspec'])) {
827             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
828         }
829         if (isset($this->aDSNInfo['username'])) {
830             $oCmd->addParams('--username', $this->aDSNInfo['username']);
831         }
832         if (isset($this->aDSNInfo['password'])) {
833             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
834         }
835         $ahGzipPipes = null;
836         if (preg_match('/\\.gz$/', $sFilename)) {
837             $aDescriptors = array(
838                              0 => array('pipe', 'r'),
839                              1 => array('pipe', 'w'),
840                              2 => array('file', '/dev/null', 'a')
841                             );
842             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
843
844             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
845             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
846             $aReadPipe = $ahGzipPipes[1];
847             fclose($ahGzipPipes[0]);
848         } else {
849             $oCmd->addParams('--file', $sFilename);
850             $aReadPipe = array('pipe', 'r');
851         }
852         $aDescriptors = array(
853                          0 => $aReadPipe,
854                          1 => array('pipe', 'w'),
855                          2 => array('file', '/dev/null', 'a')
856                         );
857         $ahPipes = null;
858
859         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
860         if (!is_resource($hProcess)) fail('unable to start pgsql');
861         // TODO: error checking
862         while (!feof($ahPipes[1])) {
863             echo fread($ahPipes[1], 4096);
864         }
865         fclose($ahPipes[1]);
866         $iReturn = proc_close($hProcess);
867         if ($iReturn > 0) {
868             fail("pgsql returned with error code ($iReturn)");
869         }
870         if ($ahGzipPipes) {
871             fclose($ahGzipPipes[1]);
872             proc_close($hGzipProcess);
873         }
874     }
875
876     private function replaceSqlPatterns($sSql)
877     {
878         $sSql = str_replace('{www-user}', CONST_Database_Web_User, $sSql);
879
880         $aPatterns = array(
881                       '{ts:address-data}' => CONST_Tablespace_Address_Data,
882                       '{ts:address-index}' => CONST_Tablespace_Address_Index,
883                       '{ts:search-data}' => CONST_Tablespace_Search_Data,
884                       '{ts:search-index}' =>  CONST_Tablespace_Search_Index,
885                       '{ts:aux-data}' =>  CONST_Tablespace_Aux_Data,
886                       '{ts:aux-index}' =>  CONST_Tablespace_Aux_Index,
887         );
888
889         foreach ($aPatterns as $sPattern => $sTablespace) {
890             if ($sTablespace) {
891                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
892             } else {
893                 $sSql = str_replace($sPattern, '', $sSql);
894             }
895         }
896
897         return $sSql;
898     }
899
900     /**
901      * Drop table with the given name if it exists.
902      *
903      * @param string $sName Name of table to remove.
904      *
905      * @return null
906      *
907      * @pre connect() must have been called.
908      */
909     private function dropTable($sName)
910     {
911         if ($this->bVerbose) echo "Dropping table $sName\n";
912         $this->oDB->deleteTable($sName);
913     }
914
915     /**
916      * Check if the database is in reverse-only mode.
917      *
918      * @return True if there is no search_name table and infrastructure.
919      */
920     private function dbReverseOnly()
921     {
922         return !($this->oDB->tableExists('search_name'));
923     }
924 }