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