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