]> git.openstreetmap.org Git - nominatim.git/blob - utils/update.php
don't overreact when bulk pool is still empty
[nominatim.git] / utils / update.php
1 #!/usr/bin/php -Cq
2 <?php
3
4         require_once(dirname(dirname(__FILE__)).'/lib/init-cmd.php');
5         ini_set('memory_limit', '800M');
6
7         $aCMDOptions = array(
8                 "Import / update / index osm data",
9                 array('help', 'h', 0, 1, 0, 0, false, 'Show Help'),
10                 array('quiet', 'q', 0, 1, 0, 0, 'bool', 'Quiet output'),
11                 array('verbose', 'v', 0, 1, 0, 0, 'bool', 'Verbose output'),
12
13                 array('max-load', '', 0, 1, 1, 1, 'float', 'Maximum load average - indexing is paused if this is exceeded'),
14                 array('max-blocking', '', 0, 1, 1, 1, 'int', 'Maximum blocking processes - indexing is aborted / paused if this is exceeded'),
15
16                 array('import-osmosis', '', 0, 1, 0, 0, 'bool', 'Import using osmosis'),
17                 array('import-osmosis-all', '', 0, 1, 0, 0, 'bool', 'Import using osmosis forever'),
18                 array('no-npi', '', 0, 1, 0, 0, 'bool', 'Do not write npi index files'),
19                 array('no-index', '', 0, 1, 0, 0, 'bool', 'Do not index the new data'),
20
21                 array('import-npi-all', '', 0, 1, 0, 0, 'bool', 'Import npi pre-indexed files'),
22
23                 array('import-hourly', '', 0, 1, 0, 0, 'bool', 'Import hourly diffs'),
24                 array('import-daily', '', 0, 1, 0, 0, 'bool', 'Import daily diffs'),
25                 array('import-all', '', 0, 1, 0, 0, 'bool', 'Import all available files'),
26
27                 array('import-file', '', 0, 1, 1, 1, 'realpath', 'Re-import data from an OSM file'),
28                 array('import-diff', '', 0, 1, 1, 1, 'realpath', 'Import a diff (osc) file from local file system'),
29                 array('osm2pgsql-cache', '', 0, 1, 1, 1, 'int', 'Cache size used by osm2pgsql'),
30
31                 array('import-node', '', 0, 1, 1, 1, 'int', 'Re-import node'),
32                 array('import-way', '', 0, 1, 1, 1, 'int', 'Re-import way'),
33                 array('import-relation', '', 0, 1, 1, 1, 'int', 'Re-import relation'),
34                 array('import-from-main-api', '', 0, 1, 0, 0, 'bool', 'Use OSM API instead of Overpass to download objects'),
35
36                 array('index', '', 0, 1, 0, 0, 'bool', 'Index'),
37                 array('index-rank', '', 0, 1, 1, 1, 'int', 'Rank to start indexing from'),
38                 array('index-instances', '', 0, 1, 1, 1, 'int', 'Number of indexing instances (threads)'),
39                 array('index-estrate', '', 0, 1, 1, 1, 'int', 'Estimated indexed items per second (def:30)'),
40
41                 array('deduplicate', '', 0, 1, 0, 0, 'bool', 'Deduplicate tokens'),
42         );
43         getCmdOpt($_SERVER['argv'], $aCMDOptions, $aResult, true, true);
44
45         if ($aResult['import-hourly'] + $aResult['import-daily'] + isset($aResult['import-diff']) > 1)
46         {
47                 showUsage($aCMDOptions, true, 'Select either import of hourly or daily');
48         }
49
50         if (!isset($aResult['index-rank'])) $aResult['index-rank'] = 0;
51
52 /*
53         // Lock to prevent multiple copies running
54         if (exec('/bin/ps uww | grep '.basename(__FILE__).' | grep -v /dev/null | grep -v grep -c', $aOutput2, $iResult) > 1)
55         {
56                 echo "Copy already running\n";
57                 exit;
58         }
59         if (!isset($aResult['max-load'])) $aResult['max-load'] = 1.9;
60         if (!isset($aResult['max-blocking'])) $aResult['max-blocking'] = 3;
61         if (getBlockingProcesses() > $aResult['max-blocking'])
62         {
63                 echo "Too many blocking processes for import\n";
64                 exit;
65         }
66 */
67
68         // Assume osm2pgsql is in the folder above
69         $sBasePath = dirname(dirname(__FILE__));
70
71         date_default_timezone_set('Etc/UTC');
72
73         $oDB =& getDB();
74
75         $aDSNInfo = DB::parseDSN(CONST_Database_DSN);
76         if (!isset($aDSNInfo['port']) || !$aDSNInfo['port']) $aDSNInfo['port'] = 5432;
77
78         // cache memory to be used by osm2pgsql, should not be more than the available memory
79         $iCacheMemory = (isset($aResult['osm2pgsql-cache'])?$aResult['osm2pgsql-cache']:2000);
80         if ($iCacheMemory + 500 > getTotalMemoryMB())
81         {
82                 $iCacheMemory = getCacheMemoryMB();
83                 echo "WARNING: resetting cache memory to $iCacheMemory\n";
84         }
85         $sOsm2pgsqlCmd = CONST_Osm2pgsql_Binary.' -klas -C '.$iCacheMemory.' -O gazetteer -d '.$aDSNInfo['database'].' -P '.$aDSNInfo['port'];
86         if (!is_null(CONST_Osm2pgsql_Flatnode_File))
87         {
88                 $sOsm2pgsqlCmd .= ' --flat-nodes '.CONST_Osm2pgsql_Flatnode_File;
89         }
90
91
92         $bFirst = true;
93         $bContinue = $aResult['import-all'];
94         while ($bContinue || $bFirst)
95         {
96                 $bFirst = false;
97
98                 if ($aResult['import-hourly'])
99                 {
100                         // Mirror the hourly diffs
101                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/hourly');
102                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDDHH24\')||\'-\'||TO_CHAR(lastimportdate+\'1 hour\'::interval,\'YYYYMMDDHH24\')||\'.osc.gz\' from import_status');
103                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/hourly/'.$sNextFile;
104                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate+\'1 hour\'::interval';
105                 }
106
107                 if ($aResult['import-daily'])
108                 {
109                         // Mirror the daily diffs
110                         exec('wget --quiet --mirror -l 1 -P '.$sMirrorDir.' http://planet.openstreetmap.org/daily');
111                         $sNextFile = $oDB->getOne('select TO_CHAR(lastimportdate,\'YYYYMMDD\')||\'-\'||TO_CHAR(lastimportdate+\'1 day\'::interval,\'YYYYMMDD\')||\'.osc.gz\' from import_status');
112                         $sNextFile = $sMirrorDir.'planet.openstreetmap.org/daily/'.$sNextFile;
113                         $sUpdateSQL = 'update import_status set lastimportdate = lastimportdate::date + 1';
114                 }
115                 
116                 if (isset($aResult['import-diff']))
117                 {
118                         // import diff directly (e.g. from osmosis --rri)
119                         $sNextFile = $aResult['import-diff'];
120                         if (!file_exists($sNextFile))
121                         {
122                                 echo "Cannot open $sNextFile\n";
123                                 exit;
124                         }
125                         // Don't update the import status - we don't know what this file contains
126                         $sUpdateSQL = 'update import_status set lastimportdate = now() where false';
127                 }
128
129                 // Missing file is not an error - it might not be created yet
130                 if (($aResult['import-hourly'] || $aResult['import-daily'] || isset($aResult['import-diff'])) && file_exists($sNextFile))
131                 {
132                         // Import the file
133                         $sCMD = $sOsm2pgsqlCmd.' '.$sNextFile;
134                         echo $sCMD."\n";
135                         exec($sCMD, $sJunk, $iErrorLevel);
136
137                         if ($iErrorLevel)
138                         {
139                                 echo "Error from osm2pgsql, $iErrorLevel\n";
140                                 exit;
141                         }
142         
143                         // Move the date onwards
144                         $oDB->query($sUpdateSQL);
145                 }
146                 else
147                 {
148                         $bContinue = false;
149                 }
150         }
151
152         $bModifyXML = false;
153         $sModifyXMLstr = '';
154         $bUseOSMApi = isset($aResult['import-from-main-api']) && $aResult['import-from-main-api'];
155         if (isset($aResult['import-file']) && $aResult['import-file'])
156         {
157                 $bModifyXML = true;
158         }
159         if (isset($aResult['import-node']) && $aResult['import-node'])
160         {
161                 $bModifyXML = true;
162                 if ($bUseOSMApi)
163                 {
164                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/node/'.$aResult['import-node']);
165                 }
166                 else
167                 {
168                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=node('.$aResult['import-node'].');out%20meta;');
169                 }
170         }
171         if (isset($aResult['import-way']) && $aResult['import-way'])
172         {
173                 $bModifyXML = true;
174                 if ($bUseOSMApi)
175                 {
176                         $sCmd = 'http://www.openstreetmap.org/api/0.6/way/'.$aResult['import-way'].'/full';
177                 }
178                 else
179                 {
180                         $sCmd = 'http://overpass-api.de/api/interpreter?data=(way('.$aResult['import-way'].');node(w););out%20meta;';
181                 }
182                 $sModifyXMLstr = file_get_contents($sCmd);
183         }
184         if (isset($aResult['import-relation']) && $aResult['import-relation'])
185         {
186                 $bModifyXML = true;
187                 if ($bUseOSMApi)
188                 {
189                         $sModifyXMLstr = file_get_contents('http://www.openstreetmap.org/api/0.6/relation/'.$aResult['import-relation'].'/full');
190                 }
191                 else
192                 {
193                         $sModifyXMLstr = file_get_contents('http://overpass-api.de/api/interpreter?data=((rel('.$aResult['import-relation'].');way(r);node(w));node(r));out%20meta;');
194                 }
195         }
196         if ($bModifyXML)
197         {
198                 // derive change from normal osm file with osmosis
199                 $sTemporaryFile = CONST_BasePath.'/data/osmosischange.osc';
200                 if (isset($aResult['import-file']) && $aResult['import-file'])
201                 {
202                         $sCMD = CONST_Osmosis_Binary.' --read-xml \''.$aResult['import-file'].'\' --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
203                         echo $sCMD."\n";
204                         exec($sCMD, $sJunk, $iErrorLevel);
205                         if ($iErrorLevel)
206                         {
207                                 echo "Error converting osm to osc, osmosis returned: $iErrorLevel\n";
208                                 exit;
209                         }
210                 }
211                 else
212                 {
213                         $aSpec = array(
214                                 0 => array("pipe", "r"),  // stdin
215                                 1 => array("pipe", "w"),  // stdout
216                                 2 => array("pipe", "w") // stderr
217                         );
218                         $sCMD = CONST_Osmosis_Binary.' --read-xml - --read-empty --derive-change --write-xml-change '.$sTemporaryFile;
219                         echo $sCMD."\n";
220                         $hProc = proc_open($sCMD, $aSpec, $aPipes);
221                         if (!is_resource($hProc))
222                         {
223                                 echo "Error converting osm to osc, osmosis failed\n";
224                                 exit;
225                         }
226                         fwrite($aPipes[0], $sModifyXMLstr);
227                         fclose($aPipes[0]);
228                         $sOut = stream_get_contents($aPipes[1]);
229                         if ($aResult['verbose']) echo $sOut;
230                         fclose($aPipes[1]);
231                         $sErrors = stream_get_contents($aPipes[2]);
232                         if ($aResult['verbose']) echo $sErrors;
233                         fclose($aPipes[2]);
234                         if ($iError = proc_close($hProc))
235                         {
236                                 echo "Error converting osm to osc, osmosis returned: $iError\n";
237                                 echo $sOut;
238                                 echo $sErrors;
239                                 exit;
240                         }
241                 }
242
243                 // import generated change file
244                 $sCMD = $sOsm2pgsqlCmd.' '.$sTemporaryFile;
245                 echo $sCMD."\n";
246                 exec($sCMD, $sJunk, $iErrorLevel);
247                 if ($iErrorLevel)
248                 {
249                         echo "osm2pgsql exited with error level $iErrorLevel\n";
250                         exit;
251                 }
252         }
253
254         if ($aResult['deduplicate'])
255         {
256                 $oDB =& getDB();
257                 $sSQL = 'select partition from country_name order by country_code';
258                 $aPartitions = $oDB->getCol($sSQL);
259                 if (PEAR::isError($aPartitions))
260                 {
261                         fail($aPartitions->getMessage());
262                 }
263                 $aPartitions[] = 0;
264
265                 $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";
266                 $aDuplicateTokens = $oDB->getAll($sSQL);
267                 foreach($aDuplicateTokens as $aToken)
268                 {
269                         if (trim($aToken['word_token']) == '' || trim($aToken['word_token']) == '-') continue;
270                         echo "Deduping ".$aToken['word_token']."\n";
271                         $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";
272                         $aTokenSet = $oDB->getAll($sSQL);
273                         if (PEAR::isError($aTokenSet))
274                         {
275                                 var_dump($aTokenSet, $sSQL);
276                                 exit;
277                         }
278                         
279                         $aKeep = array_shift($aTokenSet);
280                         $iKeepID = $aKeep['word_id'];
281
282                         foreach($aTokenSet as $aRemove)
283                         {
284                                 $sSQL = "update search_name set";
285                                 $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
286                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
287                                 $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
288                                 $x = $oDB->query($sSQL);
289                                 if (PEAR::isError($x))
290                                 {
291                                         var_dump($x);
292                                         exit;
293                                 }
294
295                                 $sSQL = "update search_name set";
296                                 $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
297                                 $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
298                                 $x = $oDB->query($sSQL);
299                                 if (PEAR::isError($x))
300                                 {
301                                         var_dump($x);
302                                         exit;
303                                 }
304
305                                 $sSQL = "update location_area_country set";
306                                 $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
307                                 $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
308                                 $x = $oDB->query($sSQL);
309                                 if (PEAR::isError($x))
310                                 {
311                                         var_dump($x);
312                                         exit;
313                                 }
314
315                                 foreach ($aPartitions as $sPartition)
316                                 {
317                                         $sSQL = "update search_name_".$sPartition." set";
318                                         $sSQL .= " name_vector = (name_vector - ".$aRemove['word_id'].")+".$iKeepID.",";
319                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
320                                         $sSQL .= " where name_vector @> ARRAY[".$aRemove['word_id']."]";
321                                         $x = $oDB->query($sSQL);
322                                         if (PEAR::isError($x))
323                                         {
324                                                 var_dump($x);
325                                                 exit;
326                                         }
327
328                                         $sSQL = "update search_name_".$sPartition." set";
329                                         $sSQL .= " nameaddress_vector = (nameaddress_vector - ".$aRemove['word_id'].")+".$iKeepID;
330                                         $sSQL .= " where nameaddress_vector @> ARRAY[".$aRemove['word_id']."]";
331                                         $x = $oDB->query($sSQL);
332                                         if (PEAR::isError($x))
333                                         {
334                                                 var_dump($x);
335                                                 exit;
336                                         }
337
338                                         $sSQL = "update location_area_country set";
339                                         $sSQL .= " keywords = (keywords - ".$aRemove['word_id'].")+".$iKeepID;
340                                         $sSQL .= " where keywords @> ARRAY[".$aRemove['word_id']."]";
341                                         $x = $oDB->query($sSQL);
342                                         if (PEAR::isError($x))
343                                         {
344                                                 var_dump($x);
345                                                 exit;
346                                         }
347                                 }
348
349                                 $sSQL = "delete from word where word_id = ".$aRemove['word_id'];
350                                 $x = $oDB->query($sSQL);
351                                 if (PEAR::isError($x))
352                                 {
353                                         var_dump($x);
354                                         exit;
355                                 }
356                         }
357
358                 }
359         }
360
361         if ($aResult['index'])
362         {
363                 if (!isset($aResult['index-instances'])) $aResult['index-instances'] = 1;
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'];
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                         if (!isset($aResult['index-instances']))
467                         {
468                                 if (getLoadAverage() < 24)
469                                         $iIndexInstances = 2;
470                                 else
471                                         $iIndexInstances = 1;
472                         } else
473                                 $iIndexInstances = $aResult['index-instances'];
474
475                         $sThisIndexCmd = $sCMDIndex.' -t '.$iIndexInstances;
476                         $fCMDStartTime = time();
477
478                         if (!$aResult['no-npi'])
479                         {
480                                 $iFileID = $oDB->getOne('select nextval(\'file\')');
481                                 if (PEAR::isError($iFileID))
482                                 {
483                                         echo $iFileID->getMessage()."\n";
484                                         exit(-1);
485                                 } 
486                                 $sFileDir = CONST_BasePath.'/export/diff/';
487                                 $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
488                                 $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
489
490                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
491                                 $sThisIndexCmd .= $sFileDir;
492                                 $sThisIndexCmd .= '/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT);
493                                 $sThisIndexCmd .= ".npi.out";
494
495                                 preg_match('#^([0-9]{4})-([0-9]{2})-([0-9]{2})#', $sBatchEnd, $aBatchMatch);
496                                 $sFileDir = CONST_BasePath.'/export/index/';
497                                 $sFileDir .= $aBatchMatch[1].'/'.$aBatchMatch[2];
498
499                                 if (!is_dir($sFileDir)) mkdir($sFileDir, 0777, true);
500                                 file_put_contents($sFileDir.'/'.$aBatchMatch[3].'.idx', "$sBatchEnd\t$iFileID\n", FILE_APPEND);
501                         }
502
503                         if (!$aResult['no-index'])
504                         {
505                                 echo "$sThisIndexCmd\n";
506                                 exec($sThisIndexCmd, $sJunk, $iErrorLevel);
507                                 if ($iErrorLevel)
508                                 {
509                                         echo "Error: $iErrorLevel\n";
510                                         exit($iErrorLevel);
511                                 }
512
513                                 if (!$aResult['no-npi'])
514                                 {
515                                         $sFileDir = CONST_BasePath.'/export/diff/';
516                                         $sFileDir .= str_pad(floor($iFileID/1000000), 3, '0', STR_PAD_LEFT);
517                                         $sFileDir .= '/'.str_pad(floor($iFileID/1000) % 1000, 3, '0', STR_PAD_LEFT);
518
519                                         $sThisIndexCmd = 'bzip2 -z9 '.$sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out";
520                                         echo "$sThisIndexCmd\n";
521                                         exec($sThisIndexCmd, $sJunk, $iErrorLevel);
522                                         if ($iErrorLevel)
523                                         {
524                                                 echo "Error: $iErrorLevel\n";
525                                                 exit($iErrorLevel);
526                                         }
527
528                                         rename($sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.out.bz2",
529                                                 $sFileDir.'/'.str_pad($iFileID % 1000, 3, '0', STR_PAD_LEFT).".npi.bz2");
530                                 }
531                         }
532
533                         $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')";
534                         var_Dump($sSQL);
535                         $oDB->query($sSQL);
536                         echo date('Y-m-d H:i:s')." Completed index step for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
537
538                         $sSQL = "update import_status set lastimportdate = '$sBatchEnd'";
539                         $oDB->query($sSQL);
540
541                         $fDuration = time() - $fStartTime;
542                         echo date('Y-m-d H:i:s')." Completed all for $sBatchEnd in ".round($fDuration/60,2)." minutes\n";
543                         if (!$aResult['import-osmosis-all']) exit;
544
545                         if ( CONST_Replication_Update_Interval > 60 )
546                         {
547                                 $iSleep = max(0,(strtotime($sBatchEnd)+CONST_Replication_Update_Interval-time()));
548                         }
549                         else
550                         {
551                                 $iSleep = max(0,CONST_Replication_Update_Interval-$fDuration);
552                         }
553                         echo date('Y-m-d H:i:s')." Sleeping $iSleep seconds\n";
554                         sleep($iSleep);
555                 }
556
557         }
558
559         if ($aResult['import-npi-all'])
560         {
561                 $iNPIID = $oDB->getOne('select max(npiid) from import_npi_log');
562                 if (PEAR::isError($iNPIID))
563                 {
564                         var_dump($iNPIID);
565                         exit;
566                 }
567                 $sConfigDirectory = CONST_BasePath.'/settings';
568                 $sCMDImportTemplate = $sBasePath.'/nominatim/nominatim -d gazetteer -P 5433 -I -T '.$sBasePath.'/nominatim/partitionedtags.def -F ';
569                 while(true)
570                 {
571                         $fStartTime = time();
572
573                         $iNPIID++;
574
575                         $sImportFile = CONST_BasePath.'/export/diff/';
576                         $sImportFile .= str_pad(floor($iNPIID/1000000), 3, '0', STR_PAD_LEFT);
577                         $sImportFile .= '/'.str_pad(floor($iNPIID/1000) % 1000, 3, '0', STR_PAD_LEFT);
578                         $sImportFile .= '/'.str_pad($iNPIID % 1000, 3, '0', STR_PAD_LEFT);
579                         $sImportFile .= ".npi";
580                         while(!file_exists($sImportFile) && !file_exists($sImportFile.'.bz2'))
581                         {
582                                 echo "sleep (waiting for $sImportFile)\n";
583                                 sleep(10);
584                         }
585                         if (file_exists($sImportFile.'.bz2')) $sImportFile .= '.bz2';
586
587                         $iFileSize = filesize($sImportFile);
588                 
589                         // Import the file
590                         $fCMDStartTime = time();
591                         $sCMDImport = $sCMDImportTemplate . $sImportFile;
592                         echo $sCMDImport."\n";
593                         exec($sCMDImport, $sJunk, $iErrorLevel);
594                         if ($iErrorLevel)
595                         {
596                                 echo "Error: $iErrorLevel\n";
597                                 exit;
598                         }
599                         $sBatchEnd = $iNPIID;
600                         echo "Completed for $sBatchEnd in ".round((time()-$fCMDStartTime)/60,2)." minutes\n";
601                         $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')";
602                         var_Dump($sSQL);
603                         $oDB->query($sSQL);
604                 }
605                 
606         }
607
608         function getosmosistimestamp($sOsmosisConfigDirectory)
609         {
610                 $sStateFile = file_get_contents($sOsmosisConfigDirectory.'/state.txt');
611                 preg_match('#timestamp=(.+)#', $sStateFile, $aResult);
612                 return str_replace('\:',':',$aResult[1]);
613         }