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