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