3 namespace Nominatim\Setup;
 
   5 require_once(CONST_LibDir.'/setup/AddressLevelParser.php');
 
   6 require_once(CONST_LibDir.'/Shell.php');
 
  10     protected $iCacheMemory;
 
  11     protected $iInstances;
 
  12     protected $sModulePath;
 
  16     protected $sIgnoreErrors;
 
  17     protected $bEnableDiffUpdates;
 
  18     protected $bEnableDebugStatements;
 
  19     protected $bNoPartitions;
 
  21     protected $oDB = null;
 
  23     public function __construct(array $aCMDResult)
 
  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);
 
  30         if ($this->iInstances < 1) {
 
  31             $this->iInstances = 1;
 
  32             warn('resetting threads to '.$this->iInstances);
 
  35         if (isset($aCMDResult['osm2pgsql-cache'])) {
 
  36             $this->iCacheMemory = $aCMDResult['osm2pgsql-cache'];
 
  37         } elseif (getSetting('FLATNODE_FILE')) {
 
  38             // When flatnode files are enabled then disable cache per default.
 
  39             $this->iCacheMemory = 0;
 
  41             // Otherwise: Assume we can steal all the cache memory in the box.
 
  42             $this->iCacheMemory = getCacheMemoryMB();
 
  45         $this->sModulePath = getSetting('DATABASE_MODULE_PATH');
 
  46         if (!$this->sModulePath) {
 
  47             $this->sModulePath = CONST_Default_ModulePath;
 
  49         info('module path: ' . $this->sModulePath);
 
  51         // parse database string
 
  52         $this->aDSNInfo = \Nominatim\DB::parseDSN(getSetting('DATABASE_DSN'));
 
  53         if (!isset($this->aDSNInfo['port'])) {
 
  54             $this->aDSNInfo['port'] = 5432;
 
  57         // setting member variables based on command line options stored in $aCMDResult
 
  58         $this->bQuiet = isset($aCMDResult['quiet']) && $aCMDResult['quiet'];
 
  59         $this->bVerbose = $aCMDResult['verbose'];
 
  61         //setting default values which are not set by the update.php array
 
  62         if (isset($aCMDResult['ignore-errors'])) {
 
  63             $this->sIgnoreErrors = $aCMDResult['ignore-errors'];
 
  65             $this->sIgnoreErrors = false;
 
  67         if (isset($aCMDResult['enable-debug-statements'])) {
 
  68             $this->bEnableDebugStatements = $aCMDResult['enable-debug-statements'];
 
  70             $this->bEnableDebugStatements = false;
 
  72         if (isset($aCMDResult['no-partitions'])) {
 
  73             $this->bNoPartitions = $aCMDResult['no-partitions'];
 
  75             $this->bNoPartitions = false;
 
  77         if (isset($aCMDResult['enable-diff-updates'])) {
 
  78             $this->bEnableDiffUpdates = $aCMDResult['enable-diff-updates'];
 
  80             $this->bEnableDiffUpdates = false;
 
  83         $this->bDrop = isset($aCMDResult['drop']) && $aCMDResult['drop'];
 
  86     public function createDB()
 
  89         $oDB = new \Nominatim\DB;
 
  91         if ($oDB->checkConnection()) {
 
  92             fail('database already exists ('.getSetting('DATABASE_DSN').')');
 
  95         $oCmd = (new \Nominatim\Shell('createdb'))
 
  96                 ->addParams('-E', 'UTF-8')
 
  97                 ->addParams('-p', $this->aDSNInfo['port']);
 
  99         if (isset($this->aDSNInfo['username'])) {
 
 100             $oCmd->addParams('-U', $this->aDSNInfo['username']);
 
 102         if (isset($this->aDSNInfo['password'])) {
 
 103             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
 
 105         if (isset($this->aDSNInfo['hostspec'])) {
 
 106             $oCmd->addParams('-h', $this->aDSNInfo['hostspec']);
 
 108         $oCmd->addParams($this->aDSNInfo['database']);
 
 110         $result = $oCmd->run();
 
 111         if ($result != 0) fail('Error executing external command: '.$oCmd->escapedCmd());
 
 114     public function setupDB()
 
 118         $fPostgresVersion = $this->db()->getPostgresVersion();
 
 119         echo 'Postgres version found: '.$fPostgresVersion."\n";
 
 121         if ($fPostgresVersion < 9.03) {
 
 122             fail('Minimum supported version of Postgresql is 9.3.');
 
 125         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS hstore');
 
 126         $this->pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
 
 128         $fPostgisVersion = $this->db()->getPostgisVersion();
 
 129         echo 'Postgis version found: '.$fPostgisVersion."\n";
 
 131         if ($fPostgisVersion < 2.2) {
 
 132             echo "Minimum required Postgis version 2.2\n";
 
 136         $sPgUser = getSetting('DATABASE_WEBUSER');
 
 137         $i = $this->db()->getOne("select count(*) from pg_user where usename = '$sPgUser'");
 
 139             echo "\nERROR: Web user '".$sPgUser."' does not exist. Create it with:\n";
 
 140             echo "\n          createuser ".$sPgUser."\n\n";
 
 144         // Try accessing the C module, so we know early if something is wrong
 
 145         $this->checkModulePresence(); // raises exception on failure
 
 147         if (!file_exists(CONST_DataDir.'/data/country_osm_grid.sql.gz')) {
 
 148             echo 'Error: you need to download the country_osm_grid first:';
 
 149             echo "\n    wget -O ".CONST_DataDir."/data/country_osm_grid.sql.gz https://www.nominatim.org/data/country_grid.sql.gz\n";
 
 152         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_name.sql');
 
 153         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/country_osm_grid.sql.gz');
 
 154         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/gb_postcode_table.sql');
 
 155         $this->pgsqlRunScriptFile(CONST_DataDir.'/data/us_postcode_table.sql');
 
 157         $sPostcodeFilename = CONST_DataDir.'/data/gb_postcode_data.sql.gz';
 
 158         if (file_exists($sPostcodeFilename)) {
 
 159             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 161             warn('optional external GB postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 164         $sPostcodeFilename = CONST_DataDir.'/data/us_postcode_data.sql.gz';
 
 165         if (file_exists($sPostcodeFilename)) {
 
 166             $this->pgsqlRunScriptFile($sPostcodeFilename);
 
 168             warn('optional external US postcode table file ('.$sPostcodeFilename.') not found. Skipping.');
 
 171         if ($this->bNoPartitions) {
 
 172             $this->pgsqlRunScript('update country_name set partition = 0');
 
 176     public function importData($sOSMFile)
 
 180         if (!file_exists(getOsm2pgsqlBinary())) {
 
 181             echo "Check NOMINATIM_OSM2PGSQL_BINARY in your local .env file.\n";
 
 182             echo "Normally you should not need to set this manually.\n";
 
 183             fail("osm2pgsql not found in '".getOsm2pgsqlBinary()."'");
 
 186         $oCmd = new \Nominatim\Shell(getOsm2pgsqlBinary());
 
 187         $oCmd->addParams('--style', getImportStyle());
 
 189         if (getSetting('FLATNODE_FILE')) {
 
 190             $oCmd->addParams('--flat-nodes', getSetting('FLATNODE_FILE'));
 
 192         if (getSetting('TABLESPACE_OSM_DATA')) {
 
 193             $oCmd->addParams('--tablespace-slim-data', getSetting('TABLESPACE_OSM_DATA'));
 
 195         if (getSetting('TABLESPACE_OSM_INDEX')) {
 
 196             $oCmd->addParams('--tablespace-slim-index', getSetting('TABLESPACE_OSM_INDEX'));
 
 198         if (getSetting('TABLESPACE_PLACE_DATA')) {
 
 199             $oCmd->addParams('--tablespace-main-data', getSetting('TABLESPACE_PLACE_DATA'));
 
 201         if (getSetting('TABLESPACE_PLACE_INDEX')) {
 
 202             $oCmd->addParams('--tablespace-main-index', getSetting('TABLESPACE_PLACE_INDEX'));
 
 204         $oCmd->addParams('--latlong', '--slim', '--create');
 
 205         $oCmd->addParams('--output', 'gazetteer');
 
 206         $oCmd->addParams('--hstore');
 
 207         $oCmd->addParams('--number-processes', 1);
 
 208         $oCmd->addParams('--with-forward-dependencies', 'false');
 
 209         $oCmd->addParams('--log-progress', 'true');
 
 210         $oCmd->addParams('--cache', $this->iCacheMemory);
 
 211         $oCmd->addParams('--port', $this->aDSNInfo['port']);
 
 213         if (isset($this->aDSNInfo['username'])) {
 
 214             $oCmd->addParams('--username', $this->aDSNInfo['username']);
 
 216         if (isset($this->aDSNInfo['password'])) {
 
 217             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
 
 219         if (isset($this->aDSNInfo['hostspec'])) {
 
 220             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
 
 222         $oCmd->addParams('--database', $this->aDSNInfo['database']);
 
 223         $oCmd->addParams($sOSMFile);
 
 226         if (!$this->sIgnoreErrors && !$this->db()->getRow('select * from place limit 1')) {
 
 231             $this->dropTable('planet_osm_nodes');
 
 232             $this->removeFlatnodeFile();
 
 236     public function createFunctions()
 
 238         info('Create Functions');
 
 240         // Try accessing the C module, so we know early if something is wrong
 
 241         $this->checkModulePresence(); // raises exception on failure
 
 243         $this->createSqlFunctions();
 
 246     public function createTables($bReverseOnly = false)
 
 248         info('Create Tables');
 
 250         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tables.sql');
 
 251         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 253         $this->pgsqlRunScript($sTemplate, false);
 
 256             $this->dropTable('search_name');
 
 259         $oAlParser = new AddressLevelParser(getSettingConfig('ADDRESS_LEVEL_CONFIG', 'address-levels.json'));
 
 260         $oAlParser->createTable($this->db(), 'address_levels');
 
 263     public function createTableTriggers()
 
 265         info('Create Tables');
 
 267         $sTemplate = file_get_contents(CONST_DataDir.'/sql/table-triggers.sql');
 
 268         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 270         $this->pgsqlRunScript($sTemplate, false);
 
 273     public function createPartitionTables()
 
 275         info('Create Partition Tables');
 
 277         $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-tables.src.sql');
 
 278         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 280         $this->pgsqlRunPartitionScript($sTemplate);
 
 283     public function createPartitionFunctions()
 
 285         info('Create Partition Functions');
 
 287         $sTemplate = file_get_contents(CONST_DataDir.'/sql/partition-functions.src.sql');
 
 288         $this->pgsqlRunPartitionScript($sTemplate);
 
 291     public function importWikipediaArticles()
 
 293         $sWikiArticlePath = getSetting('WIKIPEDIA_DATA_PATH', CONST_DataDir.'/data');
 
 294         $sWikiArticlesFile = $sWikiArticlePath.'/wikimedia-importance.sql.gz';
 
 295         if (file_exists($sWikiArticlesFile)) {
 
 296             info('Importing wikipedia articles and redirects');
 
 297             $this->dropTable('wikipedia_article');
 
 298             $this->dropTable('wikipedia_redirect');
 
 299             $this->pgsqlRunScriptFile($sWikiArticlesFile);
 
 301             warn('wikipedia importance dump file not found - places will have default importance');
 
 305     public function loadData($bDisableTokenPrecalc)
 
 307         info('Drop old Data');
 
 311         $oDB->exec('TRUNCATE word');
 
 313         $oDB->exec('TRUNCATE placex');
 
 315         $oDB->exec('TRUNCATE location_property_osmline');
 
 317         $oDB->exec('TRUNCATE place_addressline');
 
 319         $oDB->exec('TRUNCATE location_area');
 
 321         if (!$this->dbReverseOnly()) {
 
 322             $oDB->exec('TRUNCATE search_name');
 
 325         $oDB->exec('TRUNCATE search_name_blank');
 
 327         $oDB->exec('DROP SEQUENCE seq_place');
 
 329         $oDB->exec('CREATE SEQUENCE seq_place start 100000');
 
 332         $sSQL = 'select distinct partition from country_name';
 
 333         $aPartitions = $oDB->getCol($sSQL);
 
 335         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 336         foreach ($aPartitions as $sPartition) {
 
 337             $oDB->exec('TRUNCATE location_road_'.$sPartition);
 
 341         // used by getorcreate_word_id to ignore frequent partial words
 
 342         $sSQL = 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS ';
 
 343         $sSQL .= '$$ SELECT '.getSetting('MAX_WORD_FREQUENCY').' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE';
 
 347         // pre-create the word list
 
 348         if (!$bDisableTokenPrecalc) {
 
 349             info('Loading word list');
 
 350             $this->pgsqlRunScriptFile(CONST_DataDir.'/data/words.sql');
 
 354         $sColumns = 'osm_type, osm_id, class, type, name, admin_level, address, extratags, geometry';
 
 356         $aDBInstances = array();
 
 357         $iLoadThreads = max(1, $this->iInstances - 1);
 
 358         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 359             // https://secure.php.net/manual/en/function.pg-connect.php
 
 360             $DSN = getSetting('DATABASE_DSN');
 
 361             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 362             $DSN = preg_replace('/;/', ' ', $DSN);
 
 363             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 364             pg_ping($aDBInstances[$i]);
 
 367         for ($i = 0; $i < $iLoadThreads; $i++) {
 
 368             $sSQL = "INSERT INTO placex ($sColumns) SELECT $sColumns FROM place WHERE osm_id % $iLoadThreads = $i";
 
 369             $sSQL .= " and not (class='place' and type='houses' and osm_type='W'";
 
 370             $sSQL .= "          and ST_GeometryType(geometry) = 'ST_LineString')";
 
 371             $sSQL .= ' and ST_IsValid(geometry)';
 
 372             if ($this->bVerbose) echo "$sSQL\n";
 
 373             if (!pg_send_query($aDBInstances[$i], $sSQL)) {
 
 374                 fail(pg_last_error($aDBInstances[$i]));
 
 378         // last thread for interpolation lines
 
 379         // https://secure.php.net/manual/en/function.pg-connect.php
 
 380         $DSN = getSetting('DATABASE_DSN');
 
 381         $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 382         $DSN = preg_replace('/;/', ' ', $DSN);
 
 383         $aDBInstances[$iLoadThreads] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW);
 
 384         pg_ping($aDBInstances[$iLoadThreads]);
 
 385         $sSQL = 'insert into location_property_osmline';
 
 386         $sSQL .= ' (osm_id, address, linegeo)';
 
 387         $sSQL .= ' SELECT osm_id, address, geometry from place where ';
 
 388         $sSQL .= "class='place' and type='houses' and osm_type='W' and ST_GeometryType(geometry) = 'ST_LineString'";
 
 389         if ($this->bVerbose) echo "$sSQL\n";
 
 390         if (!pg_send_query($aDBInstances[$iLoadThreads], $sSQL)) {
 
 391             fail(pg_last_error($aDBInstances[$iLoadThreads]));
 
 395         for ($i = 0; $i <= $iLoadThreads; $i++) {
 
 396             while (($hPGresult = pg_get_result($aDBInstances[$i])) !== false) {
 
 397                 $resultStatus = pg_result_status($hPGresult);
 
 398                 // PGSQL_EMPTY_QUERY, PGSQL_COMMAND_OK, PGSQL_TUPLES_OK,
 
 399                 // PGSQL_COPY_OUT, PGSQL_COPY_IN, PGSQL_BAD_RESPONSE,
 
 400                 // PGSQL_NONFATAL_ERROR and PGSQL_FATAL_ERROR
 
 401                 // echo 'Query result ' . $i . ' is: ' . $resultStatus . "\n";
 
 402                 if ($resultStatus != PGSQL_COMMAND_OK && $resultStatus != PGSQL_TUPLES_OK) {
 
 403                     $resultError = pg_result_error($hPGresult);
 
 404                     echo '-- error text ' . $i . ': ' . $resultError . "\n";
 
 410             fail('SQL errors loading placex and/or location_property_osmline tables');
 
 413         for ($i = 0; $i < $this->iInstances; $i++) {
 
 414             pg_close($aDBInstances[$i]);
 
 418         info('Reanalysing database');
 
 419         $this->pgsqlRunScript('ANALYSE');
 
 421         $sDatabaseDate = getDatabaseDate($oDB);
 
 422         $oDB->exec('TRUNCATE import_status');
 
 423         if (!$sDatabaseDate) {
 
 424             warn('could not determine database date.');
 
 426             $sSQL = "INSERT INTO import_status (lastimportdate) VALUES('".$sDatabaseDate."')";
 
 428             echo "Latest data imported from $sDatabaseDate.\n";
 
 432     public function importTigerData($sTigerPath)
 
 434         info('Import Tiger data');
 
 436         $aFilenames = glob($sTigerPath.'/*.sql');
 
 437         info('Found '.count($aFilenames).' SQL files in path '.$sTigerPath);
 
 438         if (empty($aFilenames)) {
 
 439             warn('Tiger data import selected but no files found in path '.$sTigerPath);
 
 442         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_start.sql');
 
 443         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 445         $this->pgsqlRunScript($sTemplate, false);
 
 447         $aDBInstances = array();
 
 448         for ($i = 0; $i < $this->iInstances; $i++) {
 
 449             // https://secure.php.net/manual/en/function.pg-connect.php
 
 450             $DSN = getSetting('DATABASE_DSN');
 
 451             $DSN = preg_replace('/^pgsql:/', '', $DSN);
 
 452             $DSN = preg_replace('/;/', ' ', $DSN);
 
 453             $aDBInstances[$i] = pg_connect($DSN, PGSQL_CONNECT_FORCE_NEW | PGSQL_CONNECT_ASYNC);
 
 454             pg_ping($aDBInstances[$i]);
 
 457         foreach ($aFilenames as $sFile) {
 
 459             $hFile = fopen($sFile, 'r');
 
 460             $sSQL = fgets($hFile, 100000);
 
 463                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 464                     if (!pg_connection_busy($aDBInstances[$i])) {
 
 465                         while (pg_get_result($aDBInstances[$i]));
 
 466                         $sSQL = fgets($hFile, 100000);
 
 468                         if (!pg_send_query($aDBInstances[$i], $sSQL)) fail(pg_last_error($aDBInstances[$i]));
 
 470                         if ($iLines == 1000) {
 
 483                 for ($i = 0; $i < $this->iInstances; $i++) {
 
 484                     if (pg_connection_busy($aDBInstances[$i])) $bAnyBusy = true;
 
 491         for ($i = 0; $i < $this->iInstances; $i++) {
 
 492             pg_close($aDBInstances[$i]);
 
 495         info('Creating indexes on Tiger data');
 
 496         $sTemplate = file_get_contents(CONST_DataDir.'/sql/tiger_import_finish.sql');
 
 497         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 499         $this->pgsqlRunScript($sTemplate, false);
 
 502     public function calculatePostcodes($bCMDResultAll)
 
 504         info('Calculate Postcodes');
 
 505         $this->db()->exec('TRUNCATE location_postcode');
 
 507         $sSQL  = 'INSERT INTO location_postcode';
 
 508         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 509         $sSQL .= "SELECT nextval('seq_place'), 1, country_code,";
 
 510         $sSQL .= "       upper(trim (both ' ' from address->'postcode')) as pc,";
 
 511         $sSQL .= '       ST_Centroid(ST_Collect(ST_Centroid(geometry)))';
 
 512         $sSQL .= '  FROM placex';
 
 513         $sSQL .= " WHERE address ? 'postcode' AND address->'postcode' NOT SIMILAR TO '%(,|;)%'";
 
 514         $sSQL .= '       AND geometry IS NOT null';
 
 515         $sSQL .= ' GROUP BY country_code, pc';
 
 516         $this->db()->exec($sSQL);
 
 518         // only add postcodes that are not yet available in OSM
 
 519         $sSQL  = 'INSERT INTO location_postcode';
 
 520         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 521         $sSQL .= "SELECT nextval('seq_place'), 1, 'us', postcode,";
 
 522         $sSQL .= '       ST_SetSRID(ST_Point(x,y),4326)';
 
 523         $sSQL .= '  FROM us_postcode WHERE postcode NOT IN';
 
 524         $sSQL .= '        (SELECT postcode FROM location_postcode';
 
 525         $sSQL .= "          WHERE country_code = 'us')";
 
 526         $this->db()->exec($sSQL);
 
 528         // add missing postcodes for GB (if available)
 
 529         $sSQL  = 'INSERT INTO location_postcode';
 
 530         $sSQL .= ' (place_id, indexed_status, country_code, postcode, geometry) ';
 
 531         $sSQL .= "SELECT nextval('seq_place'), 1, 'gb', postcode, geometry";
 
 532         $sSQL .= '  FROM gb_postcode WHERE postcode NOT IN';
 
 533         $sSQL .= '           (SELECT postcode FROM location_postcode';
 
 534         $sSQL .= "             WHERE country_code = 'gb')";
 
 535         $this->db()->exec($sSQL);
 
 537         if (!$bCMDResultAll) {
 
 538             $sSQL = "DELETE FROM word WHERE class='place' and type='postcode'";
 
 539             $sSQL .= 'and word NOT IN (SELECT postcode FROM location_postcode)';
 
 540             $this->db()->exec($sSQL);
 
 543         $sSQL = 'SELECT count(getorcreate_postcode_id(v)) FROM ';
 
 544         $sSQL .= '(SELECT distinct(postcode) as v FROM location_postcode) p';
 
 545         $this->db()->exec($sSQL);
 
 548     public function index($bIndexNoanalyse)
 
 550         $this->checkModulePresence(); // raises exception on failure
 
 552         $oBaseCmd = (new \Nominatim\Shell(CONST_DataDir.'/nominatim/nominatim.py'))
 
 553                     ->addParams('--database', $this->aDSNInfo['database'])
 
 554                     ->addParams('--port', $this->aDSNInfo['port'])
 
 555                     ->addParams('--threads', $this->iInstances);
 
 557         if (!$this->bQuiet) {
 
 558             $oBaseCmd->addParams('-v');
 
 560         if ($this->bVerbose) {
 
 561             $oBaseCmd->addParams('-v');
 
 563         if (isset($this->aDSNInfo['hostspec'])) {
 
 564             $oBaseCmd->addParams('--host', $this->aDSNInfo['hostspec']);
 
 566         if (isset($this->aDSNInfo['username'])) {
 
 567             $oBaseCmd->addParams('--user', $this->aDSNInfo['username']);
 
 569         if (isset($this->aDSNInfo['password'])) {
 
 570             $oBaseCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
 
 573         info('Index ranks 0 - 4');
 
 574         $oCmd = (clone $oBaseCmd)->addParams('--maxrank', 4);
 
 575         echo $oCmd->escapedCmd();
 
 577         $iStatus = $oCmd->run();
 
 579             fail('error status ' . $iStatus . ' running nominatim!');
 
 581         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 583         info('Index administrative boundaries');
 
 584         $oCmd = (clone $oBaseCmd)->addParams('-b');
 
 585         $iStatus = $oCmd->run();
 
 587             fail('error status ' . $iStatus . ' running nominatim!');
 
 590         info('Index ranks 5 - 25');
 
 591         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 5, '--maxrank', 25);
 
 592         $iStatus = $oCmd->run();
 
 594             fail('error status ' . $iStatus . ' running nominatim!');
 
 597         if (!$bIndexNoanalyse) $this->pgsqlRunScript('ANALYSE');
 
 599         info('Index ranks 26 - 30');
 
 600         $oCmd = (clone $oBaseCmd)->addParams('--minrank', 26);
 
 601         $iStatus = $oCmd->run();
 
 603             fail('error status ' . $iStatus . ' running nominatim!');
 
 606         info('Index postcodes');
 
 607         $sSQL = 'UPDATE location_postcode SET indexed_status = 0';
 
 608         $this->db()->exec($sSQL);
 
 611     public function createSearchIndices()
 
 613         info('Create Search indices');
 
 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);
 
 619         foreach ($aInvalidIndices as $sIndexName) {
 
 620             info("Cleaning up invalid index $sIndexName");
 
 621             $this->db()->exec("DROP INDEX $sIndexName;");
 
 624         $sTemplate = file_get_contents(CONST_DataDir.'/sql/indices.src.sql');
 
 626             $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_updates.src.sql');
 
 628         if (!$this->dbReverseOnly()) {
 
 629             $sTemplate .= file_get_contents(CONST_DataDir.'/sql/indices_search.src.sql');
 
 631         $sTemplate = $this->replaceSqlPatterns($sTemplate);
 
 633         $this->pgsqlRunScript($sTemplate);
 
 636     public function createCountryNames()
 
 638         info('Create search index for default country names');
 
 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');
 
 650             foreach (explode(',', $sLanguages) as $sLang) {
 
 651                 $sSQL .= $sDelim."'name:$sLang'";
 
 656             // all include all simple name tags
 
 657             $sSQL .= "like 'name:%'";
 
 660         $this->pgsqlRunScript($sSQL);
 
 663     public function drop()
 
 665         info('Drop tables only required for updates');
 
 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(
 
 678                         'location_property*',
 
 691         $aDropTables = array();
 
 692         $aHaveTables = $this->db()->getListOfTables();
 
 694         foreach ($aHaveTables as $sTable) {
 
 696             foreach ($aKeepTables as $sKeep) {
 
 697                 if (fnmatch($sKeep, $sTable)) {
 
 702             if (!$bFound) array_push($aDropTables, $sTable);
 
 704         foreach ($aDropTables as $sDrop) {
 
 705             $this->dropTable($sDrop);
 
 708         $this->removeFlatnodeFile();
 
 712      * Setup the directory for the API scripts.
 
 716     public function setupWebsite()
 
 718         if (!is_dir(CONST_InstallDir.'/website')) {
 
 719             info('Creating directory for website scripts at: '.CONST_InstallDir.'/website');
 
 720             mkdir(CONST_InstallDir.'/website');
 
 733         foreach ($aScripts as $sScript) {
 
 734             $rFile = fopen(CONST_InstallDir.'/website/'.$sScript, 'w');
 
 736             fwrite($rFile, "<?php\n\n");
 
 737             fwrite($rFile, '@define(\'CONST_Debug\', $_GET[\'debug\'] ?? false);'."\n\n");
 
 739             fwriteConstDef($rFile, 'LibDir', CONST_LibDir);
 
 740             fwriteConstDef($rFile, 'DataDir', CONST_DataDir);
 
 741             fwriteConstDef($rFile, 'InstallDir', CONST_InstallDir);
 
 742             fwriteConstDef($rFile, 'Database_DSN', getSetting('DATABASE_DSN'));
 
 743             fwriteConstDef($rFile, 'Default_Language', getSetting('DEFAULT_LANGUAGE'));
 
 744             fwriteConstDef($rFile, 'Log_DB', getSettingBool('LOG_DB'));
 
 745             fwriteConstDef($rFile, 'Log_File', getSetting('LOG_FILE'));
 
 746             fwriteConstDef($rFile, 'Max_Word_Frequency', (int)getSetting('MAX_WORD_FREQUENCY'));
 
 747             fwriteConstDef($rFile, 'NoAccessControl', getSettingBool('CORS_NOACCESSCONTROL'));
 
 748             fwriteConstDef($rFile, 'Places_Max_ID_count', (int)getSetting('LOOKUP_MAX_COUNT'));
 
 749             fwriteConstDef($rFile, 'PolygonOutput_MaximumTypes', getSetting('POLYGON_OUTPUT_MAX_TYPES'));
 
 750             fwriteConstDef($rFile, 'Search_BatchMode', getSettingBool('SEARCH_BATCH_MODE'));
 
 751             fwriteConstDef($rFile, 'Search_NameOnlySearchFrequencyThreshold', getSetting('SEARCH_NAME_ONLY_THRESHOLD'));
 
 752             fwriteConstDef($rFile, 'Term_Normalization_Rules', getSetting('TERM_NORMALIZATION'));
 
 753             fwriteConstDef($rFile, 'Use_Aux_Location_data', getSettingBool('USE_AUX_LOCATION_DATA'));
 
 754             fwriteConstDef($rFile, 'Use_US_Tiger_Data', getSettingBool('USE_US_TIGER_DATA'));
 
 755             fwriteConstDef($rFile, 'MapIcon_URL', getSetting('MAPICON_URL'));
 
 757             // XXX scripts should go into the library.
 
 758             fwrite($rFile, 'require_once(\''.CONST_DataDir.'/website/'.$sScript."');\n");
 
 761             chmod(CONST_InstallDir.'/website/'.$sScript, 0755);
 
 766      * Return the connection to the database.
 
 768      * @return Database object.
 
 770      * Creates a new connection if none exists yet. Otherwise reuses the
 
 771      * already established connection.
 
 773     private function db()
 
 775         if (is_null($this->oDB)) {
 
 776             $this->oDB = new \Nominatim\DB();
 
 777             $this->oDB->connect();
 
 783     private function removeFlatnodeFile()
 
 785         $sFName = getSetting('FLATNODE_FILE');
 
 786         if ($sFName && file_exists($sFName)) {
 
 787             if ($this->bVerbose) echo 'Deleting '.$sFName."\n";
 
 792     private function pgsqlRunScript($sScript, $bfatal = true)
 
 802     private function createSqlFunctions()
 
 804         $sBasePath = CONST_DataDir.'/sql/functions/';
 
 805         $sTemplate = file_get_contents($sBasePath.'utils.sql');
 
 806         $sTemplate .= file_get_contents($sBasePath.'normalization.sql');
 
 807         $sTemplate .= file_get_contents($sBasePath.'ranking.sql');
 
 808         $sTemplate .= file_get_contents($sBasePath.'importance.sql');
 
 809         $sTemplate .= file_get_contents($sBasePath.'address_lookup.sql');
 
 810         $sTemplate .= file_get_contents($sBasePath.'interpolation.sql');
 
 811         if ($this->db()->tableExists('place')) {
 
 812             $sTemplate .= file_get_contents($sBasePath.'place_triggers.sql');
 
 814         if ($this->db()->tableExists('placex')) {
 
 815             $sTemplate .= file_get_contents($sBasePath.'placex_triggers.sql');
 
 817         if ($this->db()->tableExists('location_postcode')) {
 
 818             $sTemplate .= file_get_contents($sBasePath.'postcode_triggers.sql');
 
 820         $sTemplate = str_replace('{modulepath}', $this->sModulePath, $sTemplate);
 
 821         if ($this->bEnableDiffUpdates) {
 
 822             $sTemplate = str_replace('RETURN NEW; -- %DIFFUPDATES%', '--', $sTemplate);
 
 824         if ($this->bEnableDebugStatements) {
 
 825             $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
 
 827         if (getSettingBool('LIMIT_REINDEXING')) {
 
 828             $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
 
 830         if (!getSettingBool('USE_US_TIGER_DATA')) {
 
 831             $sTemplate = str_replace('-- %NOTIGERDATA% ', '', $sTemplate);
 
 833         if (!getSettingBool('USE_AUX_LOCATION_DATA')) {
 
 834             $sTemplate = str_replace('-- %NOAUXDATA% ', '', $sTemplate);
 
 837         $sReverseOnly = $this->dbReverseOnly() ? 'true' : 'false';
 
 838         $sTemplate = str_replace('%REVERSE-ONLY%', $sReverseOnly, $sTemplate);
 
 840         $this->pgsqlRunScript($sTemplate);
 
 843     private function pgsqlRunPartitionScript($sTemplate)
 
 845         $sSQL = 'select distinct partition from country_name';
 
 846         $aPartitions = $this->db()->getCol($sSQL);
 
 847         if (!$this->bNoPartitions) $aPartitions[] = 0;
 
 849         preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
 
 850         foreach ($aMatches as $aMatch) {
 
 852             foreach ($aPartitions as $sPartitionName) {
 
 853                 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
 
 855             $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
 
 858         $this->pgsqlRunScript($sTemplate);
 
 861     private function pgsqlRunScriptFile($sFilename)
 
 863         if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
 
 865         $oCmd = (new \Nominatim\Shell('psql'))
 
 866                 ->addParams('--port', $this->aDSNInfo['port'])
 
 867                 ->addParams('--dbname', $this->aDSNInfo['database']);
 
 869         if (!$this->bVerbose) {
 
 870             $oCmd->addParams('--quiet');
 
 872         if (isset($this->aDSNInfo['hostspec'])) {
 
 873             $oCmd->addParams('--host', $this->aDSNInfo['hostspec']);
 
 875         if (isset($this->aDSNInfo['username'])) {
 
 876             $oCmd->addParams('--username', $this->aDSNInfo['username']);
 
 878         if (isset($this->aDSNInfo['password'])) {
 
 879             $oCmd->addEnvPair('PGPASSWORD', $this->aDSNInfo['password']);
 
 882         if (preg_match('/\\.gz$/', $sFilename)) {
 
 883             $aDescriptors = array(
 
 884                              0 => array('pipe', 'r'),
 
 885                              1 => array('pipe', 'w'),
 
 886                              2 => array('file', '/dev/null', 'a')
 
 888             $oZcatCmd = new \Nominatim\Shell('zcat', $sFilename);
 
 890             $hGzipProcess = proc_open($oZcatCmd->escapedCmd(), $aDescriptors, $ahGzipPipes);
 
 891             if (!is_resource($hGzipProcess)) fail('unable to start zcat');
 
 892             $aReadPipe = $ahGzipPipes[1];
 
 893             fclose($ahGzipPipes[0]);
 
 895             $oCmd->addParams('--file', $sFilename);
 
 896             $aReadPipe = array('pipe', 'r');
 
 898         $aDescriptors = array(
 
 900                          1 => array('pipe', 'w'),
 
 901                          2 => array('file', '/dev/null', 'a')
 
 905         $hProcess = proc_open($oCmd->escapedCmd(), $aDescriptors, $ahPipes, null, $oCmd->aEnv);
 
 906         if (!is_resource($hProcess)) fail('unable to start pgsql');
 
 907         // TODO: error checking
 
 908         while (!feof($ahPipes[1])) {
 
 909             echo fread($ahPipes[1], 4096);
 
 912         $iReturn = proc_close($hProcess);
 
 914             fail("pgsql returned with error code ($iReturn)");
 
 917             fclose($ahGzipPipes[1]);
 
 918             proc_close($hGzipProcess);
 
 922     private function replaceSqlPatterns($sSql)
 
 924         $sSql = str_replace('{www-user}', getSetting('DATABASE_WEBUSER'), $sSql);
 
 927                       '{ts:address-data}' => getSetting('TABLESPACE_ADDRESS_DATA'),
 
 928                       '{ts:address-index}' => getSetting('TABLESPACE_ADDRESS_INDEX'),
 
 929                       '{ts:search-data}' => getSetting('TABLESPACE_SEARCH_DATA'),
 
 930                       '{ts:search-index}' =>  getSetting('TABLESPACE_SEARCH_INDEX'),
 
 931                       '{ts:aux-data}' =>  getSetting('TABLESPACE_AUX_DATA'),
 
 932                       '{ts:aux-index}' =>  getSetting('TABLESPACE_AUX_INDEX')
 
 935         foreach ($aPatterns as $sPattern => $sTablespace) {
 
 937                 $sSql = str_replace($sPattern, 'TABLESPACE "'.$sTablespace.'"', $sSql);
 
 939                 $sSql = str_replace($sPattern, '', $sSql);
 
 947      * Drop table with the given name if it exists.
 
 949      * @param string $sName Name of table to remove.
 
 953     private function dropTable($sName)
 
 955         if ($this->bVerbose) echo "Dropping table $sName\n";
 
 956         $this->db()->deleteTable($sName);
 
 960      * Check if the database is in reverse-only mode.
 
 962      * @return True if there is no search_name table and infrastructure.
 
 964     private function dbReverseOnly()
 
 966         return !($this->db()->tableExists('search_name'));
 
 970      * Try accessing the C module, so we know early if something is wrong.
 
 972      * Raises Nominatim\DatabaseError on failure
 
 974     private function checkModulePresence()
 
 976         $sSQL = "CREATE FUNCTION nominatim_test_import_func(text) RETURNS text AS '";
 
 977         $sSQL .= $this->sModulePath . "/nominatim.so', 'transliteration' LANGUAGE c IMMUTABLE STRICT";
 
 978         $sSQL .= ';DROP FUNCTION nominatim_test_import_func(text);';
 
 980         $oDB = new \Nominatim\DB();
 
 982         $oDB->exec($sSQL, null, 'Database server failed to load '.$this->sModulePath.'/nominatim.so module');