4 require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5 ini_set('memory_limit', '800M');
8 "Create and setup nominatim search system",
9 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
10 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
11 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
13 array('osm-file', '', 0, 1, 1, 1, 'realpath', 'File to import'),
14 array('threads', '', 0, 1, 1, 1, 'int', 'Number of threads (where possible)'),
16 array('all', '', 0, 1, 0, 0, 'bool', 'Do the complete process'),
18 array('create-db', '', 0, 1, 0, 0, 'bool', 'Create nominatim db'),
19 array('setup-db', '', 0, 1, 0, 0, 'bool', 'Build a blank nominatim db'),
20 array('import-data', '', 0, 1, 0, 0, 'bool', 'Import a osm file'),
21 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
22 array('create-functions', '', 0, 1, 0, 0, 'bool', 'Create functions'),
23 array('enable-diff-updates', '', 0, 1, 0, 0, 'bool', 'Turn on the code required to make diff updates work'),
24 array('enable-debug-statements', '', 0, 1, 0, 0, 'bool', 'Include debug warning statements in pgsql commands'),
25 array('ignore-errors', '', 0, 1, 0, 0, 'bool', 'Continue import even when errors in SQL are present (EXPERT)'),
26 array('create-minimal-tables', '', 0, 1, 0, 0, 'bool', 'Create minimal main tables'),
27 array('create-tables', '', 0, 1, 0, 0, 'bool', 'Create main tables'),
28 array('create-partition-tables', '', 0, 1, 0, 0, 'bool', 'Create required partition tables'),
29 array('create-partition-functions', '', 0, 1, 0, 0, 'bool', 'Create required partition triggers'),
30 array('no-partitions', '', 0, 1, 0, 0, 'bool', "Do not partition search indices (speeds up import of single country extracts)"),
31 array('import-wikipedia-articles', '', 0, 1, 0, 0, 'bool', 'Import wikipedia article dump'),
32 array('load-data', '', 0, 1, 0, 0, 'bool', 'Copy data to live tables from import table'),
33 array('disable-token-precalc', '', 0, 1, 0, 0, 'bool', 'Disable name precalculation (EXPERT)'),
34 array('import-tiger-data', '', 0, 1, 0, 0, 'bool', 'Import tiger data (not included in \'all\')'),
35 array('calculate-postcodes', '', 0, 1, 0, 0, 'bool', 'Calculate postcode centroids'),
36 array('osmosis-init', '', 0, 1, 0, 0, 'bool', 'Generate default osmosis configuration'),
37 array('index', '', 0, 1, 0, 0, 'bool', 'Index the data'),
38 array('index-noanalyse', '', 0, 1, 0, 0, 'bool', 'Do not perform analyse operations during index (EXPERT)'),
39 array('index-output', '', 0, 1, 1, 1, 'string', 'File to dump index information to'),
40 array('create-search-indices', '', 0, 1, 0, 0, 'bool', 'Create additional indices required for search and update'),
41 array('create-website', '', 0, 1, 1, 1, 'realpath', 'Create symlinks to setup web directory'),
42 array('drop', '', 0, 1, 0, 0, 'bool', 'Drop tables needed for updates, making the database readonly (EXPERIMENTAL)'),
44 getCmdOpt($_SERVER['argv'], $aCMDOptions, $aCMDResult, true, true);
46 $bDidSomething = false;
48 // Check if osm-file is set and points to a valid file if --all or --import-data is given
49 if ($aCMDResult['import-data'] || $aCMDResult['all'])
51 if (!isset($aCMDResult['osm-file']))
53 fail('missing --osm-file for data import');
56 if (!file_exists($aCMDResult['osm-file']))
58 fail('the path supplied to --osm-file does not exist');
61 if (!is_readable($aCMDResult['osm-file']))
63 fail('osm-file "'.$aCMDResult['osm-file'].'" not readable');
68 // This is a pretty hard core default - the number of processors in the box - 1
69 $iInstances = isset($aCMDResult['threads'])?$aCMDResult['threads']:(getProcessorCount()-1);
73 echo "WARNING: resetting threads to $iInstances\n";
75 if ($iInstances > getProcessorCount())
77 $iInstances = getProcessorCount();
78 echo "WARNING: resetting threads to $iInstances\n";
81 // Assume we can steal all the cache memory in the box (unless told otherwise)
82 if (isset($aCMDResult['osm2pgsql-cache']))
84 $iCacheMemory = $aCMDResult['osm2pgsql-cache'];
88 $iCacheMemory = getCacheMemoryMB();
91 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
92 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
94 $fPostgisVersion = (float) CONST_Postgis_Version;
96 if ($aCMDResult['create-db'] || $aCMDResult['all'])
99 $bDidSomething = true;
100 $oDB =& DB::connect(CONST_Database_DSN, false);
101 if (!PEAR::isError($oDB))
103 fail('database already exists ('.CONST_Database_DSN.')');
105 passthruCheckReturn('createdb -E UTF-8 -p '.$aDSNInfo['port'].' '.$aDSNInfo['database']);
108 if ($aCMDResult['setup-db'] || $aCMDResult['all'])
111 $bDidSomething = true;
112 // TODO: path detection, detection memory, etc.
116 $sVersionString = $oDB->getOne('select version()');
117 preg_match('#PostgreSQL ([0-9]+)[.]([0-9]+)[^0-9]#', $sVersionString, $aMatches);
118 if (CONST_Postgresql_Version != $aMatches[1].'.'.$aMatches[2])
120 echo "ERROR: PostgreSQL version is not correct. Expected ".CONST_Postgresql_Version." found ".$aMatches[1].'.'.$aMatches[2]."\n";
124 passthru('createlang plpgsql -p '.$aDSNInfo['port'].' '.$aDSNInfo['database']);
125 $pgver = (float) CONST_Postgresql_Version;
127 pgsqlRunScriptFile(CONST_Path_Postgresql_Contrib.'/hstore.sql');
128 pgsqlRunScriptFile(CONST_BasePath.'/sql/hstore_compatability_9_0.sql');
130 pgsqlRunScript('CREATE EXTENSION hstore');
133 if ($fPostgisVersion < 2.0) {
134 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/postgis.sql');
135 pgsqlRunScriptFile(CONST_Path_Postgresql_Postgis.'/spatial_ref_sys.sql');
137 pgsqlRunScript('CREATE EXTENSION IF NOT EXISTS postgis');
139 if ($fPostgisVersion < 2.1) {
140 // Function was renamed in 2.1 and throws an annoying deprecation warning
141 pgsqlRunScript('ALTER FUNCTION st_line_interpolate_point(geometry, double precision) RENAME TO ST_LineInterpolatePoint');
143 $sVersionString = $oDB->getOne('select postgis_full_version()');
144 preg_match('#POSTGIS="([0-9]+)[.]([0-9]+)[.]([0-9]+)( r([0-9]+))?"#', $sVersionString, $aMatches);
145 if (CONST_Postgis_Version != $aMatches[1].'.'.$aMatches[2])
147 echo "ERROR: PostGIS version is not correct. Expected ".CONST_Postgis_Version." found ".$aMatches[1].'.'.$aMatches[2]."\n";
151 pgsqlRunScriptFile(CONST_BasePath.'/data/country_name.sql');
152 pgsqlRunScriptFile(CONST_BasePath.'/data/country_naturalearthdata.sql');
153 pgsqlRunScriptFile(CONST_BasePath.'/data/country_osm_grid.sql');
154 pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_table.sql');
155 if (file_exists(CONST_BasePath.'/data/gb_postcode_data.sql.gz'))
157 pgsqlRunScriptFile(CONST_BasePath.'/data/gb_postcode_data.sql.gz');
161 echo "WARNING: external UK postcode table not found.\n";
163 pgsqlRunScriptFile(CONST_BasePath.'/data/us_statecounty.sql');
164 pgsqlRunScriptFile(CONST_BasePath.'/data/us_state.sql');
165 pgsqlRunScriptFile(CONST_BasePath.'/data/us_postcode.sql');
167 if ($aCMDResult['no-partitions'])
169 pgsqlRunScript('update country_name set partition = 0');
172 // the following will be needed by create_functions later but
173 // is only defined in the subsequently called create_tables.
174 // Create dummies here that will be overwritten by the proper
175 // versions in create-tables.
176 pgsqlRunScript('CREATE TABLE place_boundingbox ()');
177 pgsqlRunScript('create type wikipedia_article_match as ()');
180 if ($aCMDResult['import-data'] || $aCMDResult['all'])
183 $bDidSomething = true;
185 $osm2pgsql = CONST_Osm2pgsql_Binary;
186 if (!file_exists($osm2pgsql))
188 echo "Please download and build osm2pgsql.\nIf it is already installed, check the path in your local settings (settings/local.php) file.\n";
189 fail("osm2pgsql not found in '$osm2pgsql'");
192 if (!is_null(CONST_Osm2pgsql_Flatnode_File))
194 $osm2pgsql .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
196 if (CONST_Tablespace_Osm2pgsql_Data)
197 $osm2pgsql .= ' --tablespace-slim-data '.CONST_Tablespace_Osm2pgsql_Data;
198 if (CONST_Tablespace_Osm2pgsql_Index)
199 $osm2pgsql .= ' --tablespace-slim-index '.CONST_Tablespace_Osm2pgsql_Index;
200 if (CONST_Tablespace_Place_Data)
201 $osm2pgsql .= ' --tablespace-main-data '.CONST_Tablespace_Place_Data;
202 if (CONST_Tablespace_Place_Index)
203 $osm2pgsql .= ' --tablespace-main-index '.CONST_Tablespace_Place_Index;
204 $osm2pgsql .= ' -lsc -O gazetteer --hstore --number-processes 1';
205 $osm2pgsql .= ' -C 25000';
206 $osm2pgsql .= ' -P '.$aDSNInfo['port'];
207 $osm2pgsql .= ' -d '.$aDSNInfo['database'].' '.$aCMDResult['osm-file'];
208 passthruCheckReturn($osm2pgsql);
211 $x = $oDB->getRow('select * from place limit 1');
212 if (PEAR::isError($x)) {
213 fail($x->getMessage());
215 if (!$x) fail('No Data');
218 if ($aCMDResult['create-functions'] || $aCMDResult['all'])
221 $bDidSomething = true;
222 if (!file_exists(CONST_BasePath.'/module/nominatim.so')) fail("nominatim module not built");
223 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
224 $sTemplate = str_replace('{modulepath}', CONST_BasePath.'/module', $sTemplate);
225 if ($aCMDResult['enable-diff-updates']) $sTemplate = str_replace('RETURN NEW; -- @DIFFUPDATES@', '--', $sTemplate);
226 if ($aCMDResult['enable-debug-statements']) $sTemplate = str_replace('--DEBUG:', '', $sTemplate);
227 if (CONST_Limit_Reindexing) $sTemplate = str_replace('--LIMIT INDEXING:', '', $sTemplate);
228 pgsqlRunScript($sTemplate);
230 if ($fPostgisVersion < 2.0) {
231 echo "Helper functions for postgis < 2.0\n";
232 $sTemplate = file_get_contents(CONST_BasePath.'/sql/postgis_15_aux.sql');
234 echo "Helper functions for postgis >= 2.0\n";
235 $sTemplate = file_get_contents(CONST_BasePath.'/sql/postgis_20_aux.sql');
237 pgsqlRunScript($sTemplate);
240 if ($aCMDResult['create-minimal-tables'])
242 echo "Minimal Tables\n";
243 $bDidSomething = true;
244 pgsqlRunScriptFile(CONST_BasePath.'/sql/tables-minimal.sql');
248 // Backstop the import process - easliest possible import id
249 $sScript .= "insert into import_npi_log values (18022);\n";
251 $hFile = @fopen(CONST_BasePath.'/settings/partitionedtags.def', "r");
252 if (!$hFile) fail('unable to open list of partitions: '.CONST_BasePath.'/settings/partitionedtags.def');
254 while (($sLine = fgets($hFile, 4096)) !== false && $sLine && substr($sLine,0,1) !='#')
256 list($sClass, $sType) = explode(' ', trim($sLine));
257 $sScript .= "create table place_classtype_".$sClass."_".$sType." as ";
258 $sScript .= "select place_id as place_id,geometry as centroid from placex limit 0;\n";
260 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_centroid ";
261 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING GIST (centroid);\n";
263 $sScript .= "CREATE INDEX idx_place_classtype_".$sClass."_".$sType."_place_id ";
264 $sScript .= "ON place_classtype_".$sClass."_".$sType." USING btree(place_id);\n";
267 pgsqlRunScript($sScript);
270 if ($aCMDResult['create-tables'] || $aCMDResult['all'])
272 $bDidSomething = true;
275 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tables.sql');
276 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
277 $sTemplate = replace_tablespace('{ts:address-data}',
278 CONST_Tablespace_Address_Data, $sTemplate);
279 $sTemplate = replace_tablespace('{ts:address-index}',
280 CONST_Tablespace_Address_Index, $sTemplate);
281 $sTemplate = replace_tablespace('{ts:search-data}',
282 CONST_Tablespace_Search_Data, $sTemplate);
283 $sTemplate = replace_tablespace('{ts:search-index}',
284 CONST_Tablespace_Search_Index, $sTemplate);
285 $sTemplate = replace_tablespace('{ts:aux-data}',
286 CONST_Tablespace_Aux_Data, $sTemplate);
287 $sTemplate = replace_tablespace('{ts:aux-index}',
288 CONST_Tablespace_Aux_Index, $sTemplate);
289 pgsqlRunScript($sTemplate, false);
291 // re-run the functions
293 $sTemplate = file_get_contents(CONST_BasePath.'/sql/functions.sql');
294 $sTemplate = str_replace('{modulepath}',
295 CONST_BasePath.'/module', $sTemplate);
296 pgsqlRunScript($sTemplate);
299 if ($aCMDResult['create-partition-tables'] || $aCMDResult['all'])
301 echo "Partition Tables\n";
302 $bDidSomething = true;
304 $sSQL = 'select distinct partition from country_name';
305 $aPartitions = $oDB->getCol($sSQL);
306 if (PEAR::isError($aPartitions))
308 fail($aPartitions->getMessage());
310 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
312 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-tables.src.sql');
313 $sTemplate = replace_tablespace('{ts:address-data}',
314 CONST_Tablespace_Address_Data, $sTemplate);
315 $sTemplate = replace_tablespace('{ts:address-index}',
316 CONST_Tablespace_Address_Index, $sTemplate);
317 $sTemplate = replace_tablespace('{ts:search-data}',
318 CONST_Tablespace_Search_Data, $sTemplate);
319 $sTemplate = replace_tablespace('{ts:search-index}',
320 CONST_Tablespace_Search_Index, $sTemplate);
321 $sTemplate = replace_tablespace('{ts:aux-data}',
322 CONST_Tablespace_Aux_Data, $sTemplate);
323 $sTemplate = replace_tablespace('{ts:aux-index}',
324 CONST_Tablespace_Aux_Index, $sTemplate);
325 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
326 foreach($aMatches as $aMatch)
329 foreach($aPartitions as $sPartitionName)
331 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
333 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
336 pgsqlRunScript($sTemplate);
340 if ($aCMDResult['create-partition-functions'] || $aCMDResult['all'])
342 echo "Partition Functions\n";
343 $bDidSomething = true;
345 $sSQL = 'select distinct partition from country_name';
346 $aPartitions = $oDB->getCol($sSQL);
347 if (PEAR::isError($aPartitions))
349 fail($aPartitions->getMessage());
351 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
353 $sTemplate = file_get_contents(CONST_BasePath.'/sql/partition-functions.src.sql');
354 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
355 foreach($aMatches as $aMatch)
358 foreach($aPartitions as $sPartitionName)
360 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
362 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
365 pgsqlRunScript($sTemplate);
368 if ($aCMDResult['import-wikipedia-articles'] || $aCMDResult['all'])
370 $bDidSomething = true;
371 $sWikiArticlesFile = CONST_BasePath.'/data/wikipedia_article.sql.bin';
372 $sWikiRedirectsFile = CONST_BasePath.'/data/wikipedia_redirect.sql.bin';
373 if (file_exists($sWikiArticlesFile))
375 echo "Importing wikipedia articles...";
376 pgsqlRunDropAndRestore($sWikiArticlesFile);
381 echo "WARNING: wikipedia article dump file not found - places will have default importance\n";
383 if (file_exists($sWikiRedirectsFile))
385 echo "Importing wikipedia redirects...";
386 pgsqlRunDropAndRestore($sWikiRedirectsFile);
391 echo "WARNING: wikipedia redirect dump file not found - some place importance values may be missing\n";
396 if ($aCMDResult['load-data'] || $aCMDResult['all'])
398 echo "Drop old Data\n";
399 $bDidSomething = true;
402 if (!pg_query($oDB->connection, 'TRUNCATE word')) fail(pg_last_error($oDB->connection));
404 if (!pg_query($oDB->connection, 'TRUNCATE placex')) fail(pg_last_error($oDB->connection));
406 if (!pg_query($oDB->connection, 'TRUNCATE place_addressline')) fail(pg_last_error($oDB->connection));
408 if (!pg_query($oDB->connection, 'TRUNCATE place_boundingbox')) fail(pg_last_error($oDB->connection));
410 if (!pg_query($oDB->connection, 'TRUNCATE location_area')) fail(pg_last_error($oDB->connection));
412 if (!pg_query($oDB->connection, 'TRUNCATE search_name')) fail(pg_last_error($oDB->connection));
414 if (!pg_query($oDB->connection, 'TRUNCATE search_name_blank')) fail(pg_last_error($oDB->connection));
416 if (!pg_query($oDB->connection, 'DROP SEQUENCE seq_place')) fail(pg_last_error($oDB->connection));
418 if (!pg_query($oDB->connection, 'CREATE SEQUENCE seq_place start 100000')) fail(pg_last_error($oDB->connection));
421 $sSQL = 'select distinct partition from country_name';
422 $aPartitions = $oDB->getCol($sSQL);
423 if (PEAR::isError($aPartitions))
425 fail($aPartitions->getMessage());
427 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
428 foreach($aPartitions as $sPartition)
430 if (!pg_query($oDB->connection, 'TRUNCATE location_road_'.$sPartition)) fail(pg_last_error($oDB->connection));
434 // used by getorcreate_word_id to ignore frequent partial words
435 if (!pg_query($oDB->connection, 'CREATE OR REPLACE FUNCTION get_maxwordfreq() RETURNS integer AS $$ SELECT '.CONST_Max_Word_Frequency.' as maxwordfreq; $$ LANGUAGE SQL IMMUTABLE')) fail(pg_last_error($oDB->connection));
438 // pre-create the word list
439 if (!$aCMDResult['disable-token-precalc'])
441 echo "Loading word list\n";
442 pgsqlRunScriptFile(CONST_BasePath.'/data/words.sql');
446 $aDBInstances = array();
447 for($i = 0; $i < $iInstances; $i++)
449 $aDBInstances[$i] =& getDB(true);
450 $sSQL = 'insert into placex (osm_type, osm_id, class, type, name, admin_level, ';
451 $sSQL .= 'housenumber, street, addr_place, isin, postcode, country_code, extratags, ';
452 $sSQL .= 'geometry) select * from place where osm_id % '.$iInstances.' = '.$i;
453 if ($aCMDResult['verbose']) echo "$sSQL\n";
454 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
460 for($i = 0; $i < $iInstances; $i++)
462 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
468 echo "Reanalysing database...\n";
469 pgsqlRunScript('ANALYSE');
472 if ($aCMDResult['import-tiger-data'])
474 $bDidSomething = true;
476 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_start.sql');
477 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
478 $sTemplate = replace_tablespace('{ts:aux-data}',
479 CONST_Tablespace_Aux_Data, $sTemplate);
480 $sTemplate = replace_tablespace('{ts:aux-index}',
481 CONST_Tablespace_Aux_Index, $sTemplate);
482 pgsqlRunScript($sTemplate, false);
484 $aDBInstances = array();
485 for($i = 0; $i < $iInstances; $i++)
487 $aDBInstances[$i] =& getDB(true);
490 foreach(glob(CONST_Tiger_Data_Path.'/*.sql') as $sFile)
493 $hFile = fopen($sFile, "r");
494 $sSQL = fgets($hFile, 100000);
499 for($i = 0; $i < $iInstances; $i++)
501 if (!pg_connection_busy($aDBInstances[$i]->connection))
503 while(pg_get_result($aDBInstances[$i]->connection));
504 $sSQL = fgets($hFile, 100000);
506 if (!pg_send_query($aDBInstances[$i]->connection, $sSQL)) fail(pg_last_error($oDB->connection));
524 for($i = 0; $i < $iInstances; $i++)
526 if (pg_connection_busy($aDBInstances[$i]->connection)) $bAnyBusy = true;
533 echo "Creating indexes\n";
534 $sTemplate = file_get_contents(CONST_BasePath.'/sql/tiger_import_finish.sql');
535 $sTemplate = str_replace('{www-user}', CONST_Database_Web_User, $sTemplate);
536 $sTemplate = replace_tablespace('{ts:aux-data}',
537 CONST_Tablespace_Aux_Data, $sTemplate);
538 $sTemplate = replace_tablespace('{ts:aux-index}',
539 CONST_Tablespace_Aux_Index, $sTemplate);
540 pgsqlRunScript($sTemplate, false);
543 if ($aCMDResult['calculate-postcodes'] || $aCMDResult['all'])
545 $bDidSomething = true;
547 if (!pg_query($oDB->connection, 'DELETE from placex where osm_type=\'P\'')) fail(pg_last_error($oDB->connection));
548 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,calculated_country_code,geometry) ";
549 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,calculated_country_code,";
550 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from (select calculated_country_code,postcode,";
551 $sSQL .= "avg(st_x(st_centroid(geometry))) as x,avg(st_y(st_centroid(geometry))) as y ";
552 $sSQL .= "from placex where postcode is not null and calculated_country_code not in ('ie') group by calculated_country_code,postcode) as x";
553 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
555 $sSQL = "insert into placex (osm_type,osm_id,class,type,postcode,calculated_country_code,geometry) ";
556 $sSQL .= "select 'P',nextval('seq_postcodes'),'place','postcode',postcode,'us',";
557 $sSQL .= "ST_SetSRID(ST_Point(x,y),4326) as geometry from us_postcode";
558 if (!pg_query($oDB->connection, $sSQL)) fail(pg_last_error($oDB->connection));
561 if ($aCMDResult['osmosis-init'] || ($aCMDResult['all'] && !$aCMDResult['drop'])) // no use doing osmosis-init when dropping update tables
563 $bDidSomething = true;
566 if (!file_exists(CONST_Osmosis_Binary))
568 echo "Please download osmosis.\nIf it is already installed, check the path in your local settings (settings/local.php) file.\n";
569 if (!$aCMDResult['all'])
571 fail("osmosis not found in '".CONST_Osmosis_Binary."'");
576 if (file_exists(CONST_BasePath.'/settings/configuration.txt'))
578 echo "settings/configuration.txt already exists\n";
582 passthru(CONST_Osmosis_Binary.' --read-replication-interval-init '.CONST_BasePath.'/settings');
583 // update osmosis configuration.txt with our settings
584 passthru("sed -i 's!baseUrl=.*!baseUrl=".CONST_Replication_Url."!' ".CONST_BasePath.'/settings/configuration.txt');
585 passthru("sed -i 's:maxInterval = .*:maxInterval = ".CONST_Replication_MaxInterval.":' ".CONST_BasePath.'/settings/configuration.txt');
588 // Find the last node in the DB
589 $iLastOSMID = $oDB->getOne("select max(osm_id) from place where osm_type = 'N'");
591 // Lookup the timestamp that node was created (less 3 hours for margin for changsets to be closed)
592 $sLastNodeURL = 'http://www.openstreetmap.org/api/0.6/node/'.$iLastOSMID."/1";
593 $sLastNodeXML = file_get_contents($sLastNodeURL);
594 preg_match('#timestamp="(([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z)"#', $sLastNodeXML, $aLastNodeDate);
595 $iLastNodeTimestamp = strtotime($aLastNodeDate[1]) - (3*60*60);
597 // Search for the correct state file - uses file timestamps so need to sort by date descending
598 $sRepURL = CONST_Replication_Url."/";
599 $sRep = file_get_contents($sRepURL."?C=M;O=D;F=1");
600 // download.geofabrik.de: <a href="000/">000/</a></td><td align="right">26-Feb-2013 11:53 </td>
601 // planet.openstreetmap.org: <a href="273/">273/</a> 2013-03-11 07:41 -
602 preg_match_all('#<a href="[0-9]{3}/">([0-9]{3}/)</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
605 $aPrevRepMatch = false;
606 foreach($aRepMatches as $aRepMatch)
608 if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
609 $aPrevRepMatch = $aRepMatch;
611 if ($aPrevRepMatch) $aRepMatch = $aPrevRepMatch;
613 $sRepURL .= $aRepMatch[1];
614 $sRep = file_get_contents($sRepURL."?C=M;O=D;F=1");
615 preg_match_all('#<a href="[0-9]{3}/">([0-9]{3}/)</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
616 $aPrevRepMatch = false;
617 foreach($aRepMatches as $aRepMatch)
619 if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
620 $aPrevRepMatch = $aRepMatch;
622 if ($aPrevRepMatch) $aRepMatch = $aPrevRepMatch;
624 $sRepURL .= $aRepMatch[1];
625 $sRep = file_get_contents($sRepURL."?C=M;O=D;F=1");
626 preg_match_all('#<a href="[0-9]{3}.state.txt">([0-9]{3}).state.txt</a>\s*([-0-9a-zA-Z]+ [0-9]{2}:[0-9]{2})#', $sRep, $aRepMatches, PREG_SET_ORDER);
627 $aPrevRepMatch = false;
628 foreach($aRepMatches as $aRepMatch)
630 if (strtotime($aRepMatch[2]) < $iLastNodeTimestamp) break;
631 $aPrevRepMatch = $aRepMatch;
633 if ($aPrevRepMatch) $aRepMatch = $aPrevRepMatch;
635 $sRepURL .= $aRepMatch[1].'.state.txt';
636 echo "Getting state file: $sRepURL\n";
637 $sStateFile = file_get_contents($sRepURL);
638 if (!$sStateFile || strlen($sStateFile) > 1000) fail("unable to obtain state file");
639 file_put_contents(CONST_BasePath.'/settings/state.txt', $sStateFile);
640 echo "Updating DB status\n";
641 pg_query($oDB->connection, 'TRUNCATE import_status');
642 $sSQL = "INSERT INTO import_status VALUES('".$aRepMatch[2]."')";
643 pg_query($oDB->connection, $sSQL);
647 if (!$aCMDResult['all'])
649 fail("Cannot read state file directory.");
655 if ($aCMDResult['index'] || $aCMDResult['all'])
657 $bDidSomething = true;
659 if (isset($aCMDResult['index-output'])) $sOutputFile = ' -F '.$aCMDResult['index-output'];
660 $sBaseCmd = CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$iInstances.$sOutputFile;
661 passthruCheckReturn($sBaseCmd.' -R 4');
662 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
663 passthruCheckReturn($sBaseCmd.' -r 5 -R 25');
664 if (!$aCMDResult['index-noanalyse']) pgsqlRunScript('ANALYSE');
665 passthruCheckReturn($sBaseCmd.' -r 26');
668 if ($aCMDResult['create-search-indices'] || $aCMDResult['all'])
670 echo "Search indices\n";
671 $bDidSomething = true;
673 $sSQL = 'select distinct partition from country_name';
674 $aPartitions = $oDB->getCol($sSQL);
675 if (PEAR::isError($aPartitions))
677 fail($aPartitions->getMessage());
679 if (!$aCMDResult['no-partitions']) $aPartitions[] = 0;
681 $sTemplate = file_get_contents(CONST_BasePath.'/sql/indices.src.sql');
682 $sTemplate = replace_tablespace('{ts:address-index}',
683 CONST_Tablespace_Address_Index, $sTemplate);
684 $sTemplate = replace_tablespace('{ts:search-index}',
685 CONST_Tablespace_Search_Index, $sTemplate);
686 $sTemplate = replace_tablespace('{ts:aux-index}',
687 CONST_Tablespace_Aux_Index, $sTemplate);
688 preg_match_all('#^-- start(.*?)^-- end#ms', $sTemplate, $aMatches, PREG_SET_ORDER);
689 foreach($aMatches as $aMatch)
692 foreach($aPartitions as $sPartitionName)
694 $sResult .= str_replace('-partition-', $sPartitionName, $aMatch[1]);
696 $sTemplate = str_replace($aMatch[0], $sResult, $sTemplate);
699 pgsqlRunScript($sTemplate);
702 if (isset($aCMDResult['create-website']))
704 $bDidSomething = true;
705 $sTargetDir = $aCMDResult['create-website'];
706 if (!is_dir($sTargetDir))
708 echo "You must create the website directory before calling this function.\n";
709 fail("Target directory does not exist.");
712 @symlink(CONST_BasePath.'/website/details.php', $sTargetDir.'/details.php');
713 @symlink(CONST_BasePath.'/website/reverse.php', $sTargetDir.'/reverse.php');
714 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/search.php');
715 @symlink(CONST_BasePath.'/website/search.php', $sTargetDir.'/index.php');
716 @symlink(CONST_BasePath.'/website/lookup.php', $sTargetDir.'/lookup.php');
717 @symlink(CONST_BasePath.'/website/deletable.php', $sTargetDir.'/deletable.php');
718 @symlink(CONST_BasePath.'/website/polygons.php', $sTargetDir.'/polygons.php');
719 @symlink(CONST_BasePath.'/website/status.php', $sTargetDir.'/status.php');
720 @symlink(CONST_BasePath.'/website/images', $sTargetDir.'/images');
721 @symlink(CONST_BasePath.'/website/js', $sTargetDir.'/js');
722 @symlink(CONST_BasePath.'/website/css', $sTargetDir.'/css');
723 echo "Symlinks created\n";
725 $sTestFile = @file_get_contents(CONST_Website_BaseURL.'js/tiles.js');
728 echo "\nWARNING: Unable to access the website at ".CONST_Website_BaseURL."\n";
729 echo "You may want to update settings/local.php with @define('CONST_Website_BaseURL', 'http://[HOST]/[PATH]/');\n";
733 if ($aCMDResult['drop'])
735 // The implementation is potentially a bit dangerous because it uses
736 // a positive selection of tables to keep, and deletes everything else.
737 // Including any tables that the unsuspecting user might have manually
738 // created. USE AT YOUR OWN PERIL.
739 $bDidSomething = true;
741 // tables we want to keep. everything else goes.
742 $aKeepTables = array(
747 "location_property*",
761 $aDropTables = array();
762 $aHaveTables = $oDB->getCol("SELECT tablename FROM pg_tables WHERE schemaname='public'");
763 if (PEAR::isError($aHaveTables))
765 fail($aPartitions->getMessage());
767 foreach($aHaveTables as $sTable)
770 foreach ($aKeepTables as $sKeep)
772 if (fnmatch($sKeep, $sTable))
778 if (!$bFound) array_push($aDropTables, $sTable);
781 foreach ($aDropTables as $sDrop)
783 if ($aCMDResult['verbose']) echo "dropping table $sDrop\n";
784 @pg_query($oDB->connection, "DROP TABLE $sDrop CASCADE");
785 // ignore warnings/errors as they might be caused by a table having
786 // been deleted already by CASCADE
789 if (!is_null(CONST_Osm2pgsql_Flatnode_File))
791 if ($aCMDResult['verbose']) echo "deleting ".CONST_Osm2pgsql_Flatnode_File."\n";
792 unlink(CONST_Osm2pgsql_Flatnode_File);
798 showUsage($aCMDOptions, true);
802 echo "Setup finished.\n";
805 function pgsqlRunScriptFile($sFilename)
807 if (!file_exists($sFilename)) fail('unable to find '.$sFilename);
809 // Convert database DSN to psql parameters
810 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
811 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
812 $sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'];
815 if (preg_match('/\\.gz$/', $sFilename))
817 $aDescriptors = array(
818 0 => array('pipe', 'r'),
819 1 => array('pipe', 'w'),
820 2 => array('file', '/dev/null', 'a')
822 $hGzipProcess = proc_open('zcat '.$sFilename, $aDescriptors, $ahGzipPipes);
823 if (!is_resource($hGzipProcess)) fail('unable to start zcat');
824 $aReadPipe = $ahGzipPipes[1];
825 fclose($ahGzipPipes[0]);
829 $sCMD .= ' -f '.$sFilename;
830 $aReadPipe = array('pipe', 'r');
833 $aDescriptors = array(
835 1 => array('pipe', 'w'),
836 2 => array('file', '/dev/null', 'a')
839 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
840 if (!is_resource($hProcess)) fail('unable to start pgsql');
843 // TODO: error checking
844 while(!feof($ahPipes[1]))
846 echo fread($ahPipes[1], 4096);
850 $iReturn = proc_close($hProcess);
853 fail("pgsql returned with error code ($iReturn)");
857 fclose($ahGzipPipes[1]);
858 proc_close($hGzipProcess);
863 function pgsqlRunScript($sScript, $bfatal = true)
866 // Convert database DSN to psql parameters
867 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
868 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
869 $sCMD = 'psql -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'];
870 if ($bfatal && !$aCMDResult['ignore-errors'])
871 $sCMD .= ' -v ON_ERROR_STOP=1';
872 $aDescriptors = array(
873 0 => array('pipe', 'r'),
878 $hProcess = @proc_open($sCMD, $aDescriptors, $ahPipes);
879 if (!is_resource($hProcess)) fail('unable to start pgsql');
881 while(strlen($sScript))
883 $written = fwrite($ahPipes[0], $sScript);
884 if ($written <= 0) break;
885 $sScript = substr($sScript, $written);
888 $iReturn = proc_close($hProcess);
889 if ($bfatal && $iReturn > 0)
891 fail("pgsql returned with error code ($iReturn)");
895 function pgsqlRunRestoreData($sDumpFile)
897 // Convert database DSN to psql parameters
898 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
899 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
900 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc -a '.$sDumpFile;
902 $aDescriptors = array(
903 0 => array('pipe', 'r'),
904 1 => array('pipe', 'w'),
905 2 => array('file', '/dev/null', 'a')
908 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
909 if (!is_resource($hProcess)) fail('unable to start pg_restore');
913 // TODO: error checking
914 while(!feof($ahPipes[1]))
916 echo fread($ahPipes[1], 4096);
920 $iReturn = proc_close($hProcess);
923 function pgsqlRunDropAndRestore($sDumpFile)
925 // Convert database DSN to psql parameters
926 $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
927 if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
928 $sCMD = 'pg_restore -p '.$aDSNInfo['port'].' -d '.$aDSNInfo['database'].' -Fc --clean '.$sDumpFile;
930 $aDescriptors = array(
931 0 => array('pipe', 'r'),
932 1 => array('pipe', 'w'),
933 2 => array('file', '/dev/null', 'a')
936 $hProcess = proc_open($sCMD, $aDescriptors, $ahPipes);
937 if (!is_resource($hProcess)) fail('unable to start pg_restore');
941 // TODO: error checking
942 while(!feof($ahPipes[1]))
944 echo fread($ahPipes[1], 4096);
948 $iReturn = proc_close($hProcess);
951 function passthruCheckReturn($cmd)
954 passthru($cmd, $result);
955 if ($result != 0) fail('Error executing external command: '.$cmd);
958 function replace_tablespace($sTemplate, $sTablespace, $sSql)
961 $sSql = str_replace($sTemplate, 'TABLESPACE "'.$sTablespace.'"',
964 $sSql = str_replace($sTemplate, '', $sSql);