change_ntp.php 1.68 KB
<?php
 $open_ntp = '/etc/ntp.conf';
 $ntp_title = array('# pool: <http://www.pool.ntp.org/join.html>','#end');
 shell_exec("sudo chmod 777 ".$open_ntp);
 $nn = 0;
 $i = 0; 
 $handle = @fopen($open_ntp,"r");
 //讀檔案
 while(($data = fgetcsv($handle,1000,"\n")) != false){
  foreach($data as $key => $value){
   $aa[$i] = $value;
   $i++;
  }
  
 }
 //計算出server之前和之後的key抓出來
 foreach($aa as $num => $num_value){
  if(in_array($num_value,'#end')){
   $have_end[] = $num;
  }
  
  //判斷Ip內是否有結尾
  $end = ($num_value != '#end') ? '0':'1';
  //判斷Ip內是否有fudge
  if(false !== ($rst =strpos($num_value,'fudge'))){
   $end_num = $num;
  }
  
  if(substr($num_value,0,6) == 'server'){
   $max_min[] = $num;
  }
 }
 
 if($end_num == ""){
  $total = count($max_min);
  $key = $total-1;
  $end_num = $max_min[$key];
 }
  
 $j=0;
 for($j=0;$j<=$max_min['0']-1;$j++){
  $update[$j][] = $aa[$j]."\n";
 }
 
 foreach($_POST['server'] as $key => $value){
  if($value != ""){
   $update[$j][] = "server ".$value." minpoll 3 maxpoll 6 iburst prefer\n";
   //$update[$j+1][] = "fudge ".$value." refid GPS stratum 1\n";
   $j=$j+2;
  }
 }
 if($end == 0){
  $update[$j][] = "#end\n";
  $j++;
  for($m=$end_num+2;$m<=count($aa);$m++){
   $update[$j][] = $aa[$m]."\n";;
   $j++;
  }
 }else{
  for($m=$have_end[0]+1;$m<=count($aa);$m++){
   $update[$j][] = $aa[$m]."\n";
   $j++;
  }
  
 }
 
 
 $fp = fopen($open_ntp,'w')  or die("Unable to open file!");
 foreach($update as $key => $value){
  foreach($value as $k => $v){
   fwrite($fp, $v);
  }
 }
 fclose($fp);
 
 shell_exec("sudo service ntp restart");
 echo "1";
?>