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