]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
remove the structuredAddressElement function from search that was moved to lib.php
[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-instances'])) $aResult['index-instances'] = 1;
50         if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
51 /*
52         // Lock to prevent multiple copies running
53         if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
54         {
55                 echo "Copy already running\n";
56                 exit;
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                 echo "Too many blocking processes for import\n";
63                 exit;
64         }
65 */
66
67         // Assume osm2pgsql is in the folder above
68         $sBasePath = dirname(dirname(__FILE__));
69
70         date_default_timezone_set('Etc/UTC');
71
72         $oDB =& getDB();
73
74         $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
75
76         $bFirst = true;
77         $bContinue = $aResult['import-all'];
78         while ($bContinue || $bFirst)
79         {
80                 $bFirst = false;
81
82                 if ($aResult['import-hourly'])
83                 {
84                         // Mirror the hourly diffs
85                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
86                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
87                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
88                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
89                 }
90
91                 if ($aResult['import-daily'])
92                 {
93                         // Mirror the daily diffs
94                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
95                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
96                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
97                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
98                 }
99                 
100                 if (isset($aResult['import-diff']))
101                 {
102                         // import diff directly (e.g. from osmosis --rri)
103                         $sNextFile = $aResult['import-diff'];
104                         if (!file_exists($sNextFile))
105                         {
106                                 echo "Cannot open $nextFile\n";
107                                 exit;
108                         }
109                         // Don't update the import status - we don't know what this file contains
110                         $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
111                 }
112
113                 // Missing file is not an error - it might not be created yet
114                 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
115                 {
116                         // Import the file
117                         $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sNextFile;
118                         if (!is_null(CONST_Osm2pgsql_Flatnode_File))
119                         {
120                                 $sCMD .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
121                         }
122                         echo $sCMD."\n";
123                         exec($sCMD, $sJunk, $iErrorLevel);
124
125                         if ($iErrorLevel)
126                         {
127                                 echo "Error from osm2pgsql, $iErrorLevel\n";
128                                 exit;
129                         }
130         
131                         // Move the date onwards
132                         $oDB->query($sUpdateSQL);
133                 }
134                 else
135                 {
136                         $bContinue = false;
137                 }
138         }
139
140         $bModifyXML = false;
141         $sModifyXMLstr = '';
142         $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
143         if (isset($aResult['import-file']) && $aResult['import-file'])
144         {
145                 $bModifyXML = true;
146         }
147         if (isset($aResult['import-node']) && $aResult['import-node'])
148         {
149                 $bModifyXML = true;
150                 if ($bUseOSMApi)
151                 {
152                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
153                 }
154                 else
155                 {
156                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;');
157                 }
158         }
159         if (isset($aResult['import-way']) && $aResult['import-way'])
160         {
161                 $bModifyXML = true;
162                 if ($bUseOSMApi)
163                 {
164                         $sCmd = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
165                 }
166                 else
167                 {
168                         $sCmd = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
169                 }
170                 $sModifyXMLstr = file_get_contents($sCmd);
171         }
172         if (isset($aResult['import-relation']) && $aResult['import-relation'])
173         {
174                 $bModifyXML = true;
175                 if ($bUseOSMApi)
176                 {
177                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
178                 }
179                 else
180                 {
181                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;');
182                 }
183         }
184         if ($bModifyXML)
185         {
186                 // derive change from normal osm file with osmosis
187                 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
188                 if (isset($aResult['import-file']) && $aResult['import-file'])
189                 {
190                         $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
191                         echo $sCMD."\n";
192                         exec($sCMD, $sJunk, $iErrorLevel);
193                         if ($iErrorLevel)
194                         {
195                                 echo "Error converting osm to osc, osmosis returned: $iErrorLevel\n";
196                                 exit;
197                         }
198                 }
199                 else
200                 {
201                         $aSpec = array(
202                                 0 => array("pipe", "r"),  // stdin
203                                 1 => array("pipe", "w"),  // stdout
204                                 2 => array("pipe", "w") // stderr
205                         );
206                         $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
207                         echo $sCMD."\n";
208                         $hProc = proc_open($sCMD, $aSpec, $aPipes);
209                         if (!is_resource($hProc))
210                         {
211                                 echo "Error converting osm to osc, osmosis failed\n";
212                                 exit;
213                         }
214                         fwrite($aPipes[0], $sModifyXMLstr);
215                         fclose($aPipes[0]);
216                         $sOut = stream_get_contents($aPipes[1]);
217                         if ($aResult['verbose']) echo $sOut;
218                         fclose($aPipes[1]);
219                         $sErrors = stream_get_contents($aPipes[2]);
220                         if ($aResult['verbose']) echo $sErrors;
221                         fclose($aPipes[2]);
222                         if ($iError = proc_close($hProc))
223                         {
224                                 echo "Error converting osm to osc, osmosis returned: $iError\n";
225                                 echo $sOut;
226                                 echo $sErrors;
227                                 exit;
228                         }
229                 }
230
231                 // import generated change file
232                 $sCMD = CONST_Osm2pgsql_Binary.' -klas -C 2000 -O gazetteer -d '.$aDSNInfo['database'].' '.$sTemporaryFile;
233                 if (!is_null(CONST_Osm2pgsql_Flatnode_File))
234                 {
235                         $sCMD .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
236                 }
237                 echo $sCMD."\n";
238                 exec($sCMD, $sJunk, $iErrorLevel);
239                 if ($iErrorLevel)
240                 {
241                         echo "osm2pgsql exited with error level $iErrorLevel\n";
242                         exit;
243                 }
244         }
245
246         if ($aResult['deduplicate'])
247         {
248                 $oDB =& getDB();
249                 $sSQL = 'select partition from country_name order by country_code';
250                 $aPartitions = $oDB->getCol($sSQL);
251                 if (PEAR::isError($aPartitions))
252                 {
253                         fail($aPartitions->getMessage());
254                 }
255                 $aPartitions[] = 0;
256
257                 $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";
258                 $aDuplicateTokens = $oDB->getAll($sSQL);
259                 foreach($aDuplicateTokens as $aToken)
260                 {
261                         if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
262                         echo "Deduping ".$aToken['word_token']."\n";
263                         $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";
264                         $aTokenSet = $oDB->getAll($sSQL);
265                         if (PEAR::isError($aTokenSet))
266                         {
267                                 var_dump($aTokenSet, $sSQL);
268                                 exit;
269                         }
270                         
271                         $aKeep = array_shift($aTokenSet);
272                         $iKeepID = $aKeep['word_id'];
273
274                         foreach($aTokenSet as $aRemove)
275                         {
276                                 $sSQL = "update search_name set";
277                                 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
278                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
279                                 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
280                                 $x = $oDB->query($sSQL);
281                                 if (PEAR::isError($x))
282                                 {
283                                         var_dump($x);
284                                         exit;
285                                 }
286
287                                 $sSQL = "update search_name set";
288                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
289                                 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
290                                 $x = $oDB->query($sSQL);
291                                 if (PEAR::isError($x))
292                                 {
293                                         var_dump($x);
294                                         exit;
295                                 }
296
297                                 $sSQL = "update location_area_country set";
298                                 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
299                                 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
300                                 $x = $oDB->query($sSQL);
301                                 if (PEAR::isError($x))
302                                 {
303                                         var_dump($x);
304                                         exit;
305                                 }
306
307                                 foreach ($aPartitions as $sPartition)
308                                 {
309                                         $sSQL = "update search_name_".$sPartition." set";
310                                         $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
311                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
312                                         $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
313                                         $x = $oDB->query($sSQL);
314                                         if (PEAR::isError($x))
315                                         {
316                                                 var_dump($x);
317                                                 exit;
318                                         }
319
320                                         $sSQL = "update search_name_".$sPartition." set";
321                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
322                                         $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
323                                         $x = $oDB->query($sSQL);
324                                         if (PEAR::isError($x))
325                                         {
326                                                 var_dump($x);
327                                                 exit;
328                                         }
329
330                                         $sSQL = "update location_area_country set";
331                                         $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
332                                         $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
333                                         $x = $oDB->query($sSQL);
334                                         if (PEAR::isError($x))
335                                         {
336                                                 var_dump($x);
337                                                 exit;
338                                         }
339                                 }
340
341                                 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
342                                 $x = $oDB->query($sSQL);
343                                 if (PEAR::isError($x))
344                                 {
345                                         var_dump($x);
346                                         exit;
347                                 }
348                         }
349
350                 }
351         }
352
353         if ($aResult['index'])
354         {
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'].' -t '.$aResult['index-instances'];
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 == 1 || $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 == 1)
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                         $sThisIndexCmd = $sCMDIndex;
454
455                         if (!$aResult['no-npi'])
456                         {
457                                 $fCMDStartTime = time();
458                                 $iFileID = $oDB->getOne('select nextval(\'file\')');
459                                 if (PEAR::isError($iFileID))
460                                 {
461                                         echo $iFileID->getMessage()."\n";
462                                         exit;
463                                 } 
464                                 $sFileDir = CONST_BasePath.'/export/diff/';
465                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
466                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
467
468                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
469                                 $sThisIndexCmd .= $sFileDir;
470                                 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
471                                 $sThisIndexCmd .= ".npi.out";
472
473                                 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
474                                 $sFileDir = CONST_BasePath.'/export/index/';
475                                 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
476
477                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
478                                 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
479                         }
480
481                         if (!$aResult['no-index'])
482                         {
483                                 echo "$sThisIndexCmd\n";
484                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
485                                 if ($iErrorLevel)
486                                 {
487                                         echo "Error: $iErrorLevel\n";
488                                         exit;
489                                 }
490
491                                 if (!$aResult['no-npi'])
492                                 {
493                                         $sFileDir = CONST_BasePath.'/export/diff/';
494                                         $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
495                                         $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
496
497                                         $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
498                                         echo "$sThisIndexCmd\n";
499                                         exec($sThisIndexCmd, $sJunk, $iErrorLevel);
500                                         if ($iErrorLevel)
501                                         {
502                                                 echo "Error: $iErrorLevel\n";
503                                                 exit;
504                                         }
505
506                                         rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
507                                                 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
508                                 }
509                         }
510
511                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
512                         $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')";
513                         $oDB->query($sSQL);
514
515                         $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
516                         $oDB->query($sSQL);
517
518                         $fDuration = time() - $fStartTime;
519                         echo "Completed for $sBatchEnd in ".round($fDuration/60,2)."\n";
520                         if (!$aResult['import-osmosis-all']) exit;
521
522                         if ( CONST_Replication_Update_Interval > 60 )
523                         {
524                                 $iSleep = round(CONST_Replication_Update_Interval*0.8);
525                         }
526                         else
527                         {
528                                 $iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
529                         }
530                         echo "Sleeping $iSleep seconds\n";
531                         sleep($iSleep);
532                 }
533
534         }
535
536         if ($aResult['import-npi-all'])
537         {
538                 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
539                 if (PEAR::isError($iNPIID))
540                 {
541                         var_dump($iNPIID);
542                         exit;
543                 }
544                 $sConfigDirectory = CONST_BasePath.'/settings';
545                 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
546                 while(true)
547                 {
548                         $fStartTime = time();
549
550                         $iNPIID++;
551
552                         $sImportFile = CONST_BasePath.'/export/diff/';
553                         $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
554                         $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
555                         $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
556                         $sImportFile .= ".npi";
557                         while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
558                         {
559                                 echo "sleep (waiting for $sImportFile)\n";
560                                 sleep(10);
561                         }
562                         if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
563
564                         $iFileSize = filesize($sImportFile);
565                 
566                         // Import the file
567                         $fCMDStartTime = time();
568                         $sCMDImport = $sCMDImportTemplate . $sImportFile;
569                         echo $sCMDImport."\n";
570                         exec($sCMDImport, $sJunk, $iErrorLevel);
571                         if ($iErrorLevel)
572                         {
573                                 echo "Error: $iErrorLevel\n";
574                                 exit;
575                         }
576                         $sBatchEnd = $iNPIID;
577                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
578                         $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')";
579                         var_Dump($sSQL);
580                         $oDB->query($sSQL);
581                 }
582                 
583         }
584
585         function getosmosistimestamp($sOsmosisConfigDirectory)
586         {
587                 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
588                 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
589                 return str_replace('\:',':',$aResult[1]);
590         }