]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
Updated FIPS map in utils/tigerAddressImport.py
[nominatim.git] / utils / update.php
1 #!/usr/bin/php -Cq
2 <?php
3
4         require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5         ini_set('memory_limit', '800M');
6
7         $aCMDOptions = array(
8                 "Import / update / index osm data",
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'),
12
13                 array('max-load', '', 0, 1, 1, 1, 'float', 'Maximum load average - indexing is paused if this is exceeded'),
14                 array('max-blocking', '', 0, 1, 1, 1, 'int', 'Maximum blocking processes - indexing is aborted / paused if this is exceeded'),
15
16                 array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'),
17                 array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'),
18                 array('no-npi', '', 0, 1, 0, 0, 'bool', 'Do not write npi index files'),
19                 array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'),
20
21                 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
22
23                 array('import-hourly', '', 0, 1, 0, 0, 'bool', 'Import hourly diffs'),
24                 array('import-daily', '', 0, 1, 0, 0, 'bool', 'Import daily diffs'),
25                 array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
26
27                 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
28                 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
29                 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
30
31                 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
32                 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
33                 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
34                 array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
35
36                 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
37                 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
38                 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
39                 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
40
41                 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
42         );
43         getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
44
45         if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
46         {
47                 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
48         }
49
50         if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
51         if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
52
53 /*
54         // Lock to prevent multiple copies running
55         if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
56         {
57                 fail("Copy already running\n");
58         }
59         if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
60         if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
61         if (getBlockingProcesses() > $aResult['max-blocking'])
62         {
63                 fail("Too many blocking processes for import\n");
64         }
65 */
66
67         // Assume osm2pgsql is in the folder above
68         $sBasePath = dirname(dirname(__FILE__));
69
70         date_default_timezone_set('Etc/UTC');
71
72         $oDB =& getDB();
73
74         $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
75         if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
76
77         // cache memory to be used by osm2pgsql, should not be more than the available memory
78         $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
79         if ($iCacheMemory + 500 > getTotalMemoryMB())
80         {
81                 $iCacheMemory = getCacheMemoryMB();
82                 echo "WARNING: resetting cache memory to $iCacheMemory\n";
83         }
84         $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas --number-processes 1 -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
85         if (!is_null(CONST_Osm2pgsql_Flatnode_File))
86         {
87                 $sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
88         }
89
90
91         $bFirst = true;
92         $bContinue = $aResult['import-all'];
93         while ($bContinue || $bFirst)
94         {
95                 $bFirst = false;
96
97                 if ($aResult['import-hourly'])
98                 {
99                         // Mirror the hourly diffs
100                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
101                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
102                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
103                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
104                 }
105
106                 if ($aResult['import-daily'])
107                 {
108                         // Mirror the daily diffs
109                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
110                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
111                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
112                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
113                 }
114                 
115                 if (isset($aResult['import-diff']))
116                 {
117                         // import diff directly (e.g. from osmosis --rri)
118                         $sNextFile = $aResult['import-diff'];
119                         if (!file_exists($sNextFile))
120                         {
121                                 fail("Cannot open $sNextFile\n");
122                         }
123                         // Don't update the import status - we don't know what this file contains
124                         $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
125                 }
126
127                 // Missing file is not an error - it might not be created yet
128                 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
129                 {
130                         // Import the file
131                         $sCMD = $sOsm2pgsqlCmd.' '.$sNextFile;
132                         echo $sCMD."\n";
133                         exec($sCMD, $sJunk, $iErrorLevel);
134
135                         if ($iErrorLevel)
136                         {
137                                 fail("Error from osm2pgsql, $iErrorLevel\n");
138                         }
139         
140                         // Move the date onwards
141                         $oDB->query($sUpdateSQL);
142                 }
143                 else
144                 {
145                         $bContinue = false;
146                 }
147         }
148
149         $bModifyXML = false;
150         $sModifyXMLstr = '';
151         $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
152         if (isset($aResult['import-file']) && $aResult['import-file'])
153         {
154                 $bModifyXML = true;
155         }
156         if (isset($aResult['import-node']) && $aResult['import-node'])
157         {
158                 $bModifyXML = true;
159                 if ($bUseOSMApi)
160                 {
161                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
162                 }
163                 else
164                 {
165                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;');
166                 }
167         }
168         if (isset($aResult['import-way']) && $aResult['import-way'])
169         {
170                 $bModifyXML = true;
171                 if ($bUseOSMApi)
172                 {
173                         $sCmd = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
174                 }
175                 else
176                 {
177                         $sCmd = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
178                 }
179                 $sModifyXMLstr = file_get_contents($sCmd);
180         }
181         if (isset($aResult['import-relation']) && $aResult['import-relation'])
182         {
183                 $bModifyXML = true;
184                 if ($bUseOSMApi)
185                 {
186                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
187                 }
188                 else
189                 {
190                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;');
191                 }
192         }
193         if ($bModifyXML)
194         {
195                 // derive change from normal osm file with osmosis
196                 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
197                 if (isset($aResult['import-file']) && $aResult['import-file'])
198                 {
199                         $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
200                         echo $sCMD."\n";
201                         exec($sCMD, $sJunk, $iErrorLevel);
202                         if ($iErrorLevel)
203                         {
204                                 fail("Error converting osm to osc, osmosis returned: $iErrorLevel\n");
205                         }
206                 }
207                 else
208                 {
209                         $aSpec = array(
210                                 0 => array("pipe", "r"),  // stdin
211                                 1 => array("pipe", "w"),  // stdout
212                                 2 => array("pipe", "w") // stderr
213                         );
214                         $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
215                         echo $sCMD."\n";
216                         $hProc = proc_open($sCMD, $aSpec, $aPipes);
217                         if (!is_resource($hProc))
218                         {
219                                 fail("Error converting osm to osc, osmosis failed\n");
220                         }
221                         fwrite($aPipes[0], $sModifyXMLstr);
222                         fclose($aPipes[0]);
223                         $sOut = stream_get_contents($aPipes[1]);
224                         if ($aResult['verbose']) echo $sOut;
225                         fclose($aPipes[1]);
226                         $sErrors = stream_get_contents($aPipes[2]);
227                         if ($aResult['verbose']) echo $sErrors;
228                         fclose($aPipes[2]);
229                         if ($iError = proc_close($hProc))
230                         {
231                                 echo "Error converting osm to osc, osmosis returned: $iError\n";
232                                 echo $sOut;
233                                 echo $sErrors;
234                                 exit(-1);
235                         }
236                 }
237
238                 // import generated change file
239                 $sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
240                 echo $sCMD."\n";
241                 exec($sCMD, $sJunk, $iErrorLevel);
242                 if ($iErrorLevel)
243                 {
244                         fail("osm2pgsql exited with error level $iErrorLevel\n");
245                 }
246         }
247
248         if ($aResult['deduplicate'])
249         {
250
251                 $pgver = (float) CONST_Postgresql_Version;
252                 if ($pgver < 9.3) {
253                         fail("ERROR: deduplicate is only currently supported in postgresql 9.3");
254                 }
255
256                 $oDB =& getDB();
257                 $sSQL = 'select partition from country_name order by country_code';
258                 $aPartitions = $oDB->getCol($sSQL);
259                 if (PEAR::isError($aPartitions))
260                 {
261                         fail($aPartitions->getMessage());
262                 }
263                 $aPartitions[] = 0;
264
265                 $sSQL = "select word_token,count(*) from word where substr(word_token, 1, 1) = ' ' and class is null and type is null and country_code is null group by word_token having count(*) > 1 order by word_token";
266                 $aDuplicateTokens = $oDB->getAll($sSQL);
267                 foreach($aDuplicateTokens as $aToken)
268                 {
269                         if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
270                         echo "Deduping ".$aToken['word_token']."\n";
271                         $sSQL = "select word_id,(select count(*) from search_name where nameaddress_vector @> ARRAY[word_id]) as num from word where word_token = '".$aToken['word_token']."' and class is null and type is null and country_code is null order by num desc";
272                         $aTokenSet = $oDB->getAll($sSQL);
273                         if (PEAR::isError($aTokenSet))
274                         {
275                                 var_dump($aTokenSet, $sSQL);
276                                 exit(1);
277                         }
278
279                         $aKeep = array_shift($aTokenSet);
280                         $iKeepID = $aKeep['word_id'];
281
282                         foreach($aTokenSet as $aRemove)
283                         {
284                                 $sSQL = "update search_name set";
285                                 $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID."),";
286                                 $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
287                                 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
288                                 $x = $oDB->query($sSQL);
289                                 if (PEAR::isError($x))
290                                 {
291                                         var_dump($x);
292                                         exit(1);
293                                 }
294
295                                 $sSQL = "update search_name set";
296                                 $sSQL .= " nameaddress_vector = array_replace(nameaddress_vector,".$aRemove['word_id'].",".$iKeepID.")";
297                                 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
298                                 $x = $oDB->query($sSQL);
299                                 if (PEAR::isError($x))
300                                 {
301                                         var_dump($x);
302                                         exit(1);
303                                 }
304
305                                 $sSQL = "update location_area_country set";
306                                 $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
307                                 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
308                                 $x = $oDB->query($sSQL);
309                                 if (PEAR::isError($x))
310                                 {
311                                         var_dump($x);
312                                         exit(1);
313                                 }
314
315                                 foreach ($aPartitions as $sPartition)
316                                 {
317                                         $sSQL = "update search_name_".$sPartition." set";
318                                         $sSQL .= " name_vector = array_replace(name_vector,".$aRemove['word_id'].",".$iKeepID.")";
319                                         $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
320                                         $x = $oDB->query($sSQL);
321                                         if (PEAR::isError($x))
322                                         {
323                                                 var_dump($x);
324                                                 exit(1);
325                                         }
326
327                                         $sSQL = "update location_area_country set";
328                                         $sSQL .= " keywords = array_replace(keywords,".$aRemove['word_id'].",".$iKeepID.")";
329                                         $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
330                                         $x = $oDB->query($sSQL);
331                                         if (PEAR::isError($x))
332                                         {
333                                                 var_dump($x);
334                                                 exit(1);
335                                         }
336                                 }
337
338                                 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
339                                 $x = $oDB->query($sSQL);
340                                 if (PEAR::isError($x))
341                                 {
342                                         var_dump($x);
343                                         exit(1);
344                                 }
345                         }
346
347                 }
348         }
349
350         if ($aResult['index'])
351         {
352                 passthru(CONST_BasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'].' -r '.$aResult['index-rank']);
353         }
354
355         if ($aResult['import-osmosis'] || $aResult['import-osmosis-all'])
356         {
357
358                 if (strpos(CONST_Replication_Url, 'download.geofabrik.de') !== false && CONST_Replication_Update_Interval < 86400) {
359                         fail("Error: Update interval too low for download.geofabrik.de.  Please check install documentation (http://wiki.openstreetmap.org/wiki/Nominatim/Installation#Updates)\n");
360                 }
361
362                 $sImportFile = CONST_BasePath.'/data/osmosischange.osc';
363                 $sOsmosisCMD = CONST_Osmosis_Binary;
364                 $sOsmosisConfigDirectory = CONST_BasePath.'/settings';
365                 $sCMDDownload = $sOsmosisCMD.' --read-replication-interval workingDirectory='.$sOsmosisConfigDirectory.' --simplify-change --write-xml-change '.$sImportFile;
366                 $sCMDCheckReplicationLag = $sOsmosisCMD.' -q --read-replication-lag workingDirectory='.$sOsmosisConfigDirectory;
367                 $sCMDImport = $sOsm2pgsqlCmd.' '.$sImportFile;
368                 $sCMDIndex = $sBasePath.'/nominatim/nominatim -i -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'].' -t '.$aResult['index-instances'];
369                 if (!$aResult['no-npi']) {
370                         $sCMDIndex .= '-F ';
371                 }
372                 while(true)
373                 {
374                         $fStartTime = time();
375                         $iFileSize = 1001;
376
377                         // Logic behind this is that osm2pgsql locks the database quite a bit
378                         // So it is better to import lots of small files
379                         // But indexing works most efficiently on large amounts of data
380                         // So do lots of small imports and a BIG index
381
382 //                      while($aResult['import-osmosis-all'] && $iFileSize > 1000)
383 //                      {
384                                 if (!file_exists($sImportFile))
385                                 {
386                                         // First check if there are new updates published (except for minutelies - there's always new diffs to process)
387                                         if ( CONST_Replication_Update_Interval > 60 )
388                                         {
389
390                                                 unset($aReplicationLag);
391                                                 exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel); 
392                                                 while ($iErrorLevel > 0 || $aReplicationLag[0] < 1)
393                                                 {
394                                                         if ($iErrorLevel)
395                                                         {
396                                                                 echo "Error: $iErrorLevel. ";
397                                                                 echo "Re-trying: ".$sCMDCheckReplicationLag." in ".CONST_Replication_Recheck_Interval." secs\n";
398                                                         }
399                                                         else
400                                                         {
401                                                                 echo ".";
402                                                         }
403                                                         sleep(CONST_Replication_Recheck_Interval);
404                                                         unset($aReplicationLag);
405                                                         exec($sCMDCheckReplicationLag, $aReplicationLag, $iErrorLevel); 
406                                                 }
407                                                 // There are new replication files - use osmosis to download the file
408                                                 echo "\n".date('Y-m-d H:i:s')." Replication Delay is ".$aReplicationLag[0]."\n";
409                                         }
410                                         $fStartTime = time();
411                                         $fCMDStartTime = time();
412                                         echo $sCMDDownload."\n";
413                                         exec($sCMDDownload, $sJunk, $iErrorLevel);
414                                         while ($iErrorLevel > 0)
415                                         {
416                                                 echo "Error: $iErrorLevel\n";
417                                                 sleep(60);
418                                                 echo 'Re-trying: '.$sCMDDownload."\n";
419                                                 exec($sCMDDownload, $sJunk, $iErrorLevel);
420                                         }
421                                         $iFileSize = filesize($sImportFile);
422                                         $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
423                                         $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osmosis')";
424                                         var_Dump($sSQL);
425                                         $oDB->query($sSQL);
426                                         echo date('Y-m-d H:i:s')." Completed osmosis step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
427                                 }
428
429                                 $iFileSize = filesize($sImportFile);
430                                 $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
431                 
432                                 // Import the file
433                                 $fCMDStartTime = time();
434                                 echo $sCMDImport."\n";
435                                 exec($sCMDImport, $sJunk, $iErrorLevel);
436                                 if ($iErrorLevel)
437                                 {
438                                         echo "Error: $iErrorLevel\n";
439                                         exit($iErrorLevel);
440                                 }
441                                 $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','osm2pgsql')";
442                                 var_Dump($sSQL);
443                                 $oDB->query($sSQL);
444                                 echo date('Y-m-d H:i:s')." Completed osm2pgsql step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
445
446                                 // Archive for debug?
447                                 unlink($sImportFile);
448 //                      }
449
450                         $sBatchEnd = getosmosistimestamp($sOsmosisConfigDirectory);
451
452                         // Index file
453                         $sThisIndexCmd = $sCMDIndex;
454                         $fCMDStartTime = time();
455
456                         if (!$aResult['no-npi'])
457                         {
458                                 $iFileID = $oDB->getOne('select nextval(\'file\')');
459                                 if (PEAR::isError($iFileID))
460                                 {
461                                         echo $iFileID->getMessage()."\n";
462                                         exit(-1);
463                                 } 
464                                 $sFileDir = CONST_BasePath.'/export/diff/';
465                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
466                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
467
468                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
469                                 $sThisIndexCmd .= $sFileDir;
470                                 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
471                                 $sThisIndexCmd .= ".npi.out";
472
473                                 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
474                                 $sFileDir = CONST_BasePath.'/export/index/';
475                                 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
476
477                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
478                                 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
479                         }
480
481                         if (!$aResult['no-index'])
482                         {
483                                 echo "$sThisIndexCmd\n";
484                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
485                                 if ($iErrorLevel)
486                                 {
487                                         echo "Error: $iErrorLevel\n";
488                                         exit($iErrorLevel);
489                                 }
490
491                                 if (!$aResult['no-npi'])
492                                 {
493                                         $sFileDir = CONST_BasePath.'/export/diff/';
494                                         $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
495                                         $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
496
497                                         $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
498                                         echo "$sThisIndexCmd\n";
499                                         exec($sThisIndexCmd, $sJunk, $iErrorLevel);
500                                         if ($iErrorLevel)
501                                         {
502                                                 echo "Error: $iErrorLevel\n";
503                                                 exit($iErrorLevel);
504                                         }
505
506                                         rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
507                                                 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
508                                 }
509                         }
510
511                         $sSQL = "INSERT INTO import_osmosis_log values ('$sBatchEnd',$iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','index')";
512                         var_Dump($sSQL);
513                         $oDB->query($sSQL);
514                         echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
515
516                         $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
517                         $oDB->query($sSQL);
518
519                         $fDuration = time() - $fStartTime;
520                         echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n";
521                         if (!$aResult['import-osmosis-all']) exit(0);
522
523                         if ( CONST_Replication_Update_Interval > 60 )
524                         {
525                                 $iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
526                         }
527                         else
528                         {
529                                 $iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
530                         }
531                         echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
532                         sleep($iSleep);
533                 }
534
535         }
536
537         if ($aResult['import-npi-all'])
538         {
539                 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
540                 if (PEAR::isError($iNPIID))
541                 {
542                         var_dump($iNPIID);
543                         exit(1);
544                 }
545                 $sConfigDirectory = CONST_BasePath.'/settings';
546                 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
547                 while(true)
548                 {
549                         $fStartTime = time();
550
551                         $iNPIID++;
552
553                         $sImportFile = CONST_BasePath.'/export/diff/';
554                         $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
555                         $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
556                         $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
557                         $sImportFile .= ".npi";
558                         while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
559                         {
560                                 echo "sleep (waiting for $sImportFile)\n";
561                                 sleep(10);
562                         }
563                         if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
564
565                         $iFileSize = filesize($sImportFile);
566                 
567                         // Import the file
568                         $fCMDStartTime = time();
569                         $sCMDImport = $sCMDImportTemplate . $sImportFile;
570                         echo $sCMDImport."\n";
571                         exec($sCMDImport, $sJunk, $iErrorLevel);
572                         if ($iErrorLevel)
573                         {
574                                 fail("Error: $iErrorLevel\n");
575                         }
576                         $sBatchEnd = $iNPIID;
577                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
578                         $sSQL = "INSERT INTO import_npi_log values ($iNPIID, null, $iFileSize,'".date('Y-m-d H:i:s',$fCMDStartTime)."','".date('Y-m-d H:i:s')."','import')";
579                         var_Dump($sSQL);
580                         $oDB->query($sSQL);
581                 }
582                 
583         }
584
585         function getosmosistimestamp($sOsmosisConfigDirectory)
586         {
587                 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
588                 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
589                 return str_replace('\:',':',$aResult[1]);
590         }