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