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