<?
/**
 * VoiceOne Webservices Interface
 *
 * @package voiceone_webservices
 * @subpackage Network
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
/******************************   NETWORK  ************************************/
/**
* FUNCTION: getNetworkConf
* Get network configurations
* @param null
* @return:NetworkConf -> Structure contains network settings
*/
function getNetworkConf(){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=array();
  //extract network configuration
  $qry="SELECT `var_name`,`var_val` FROM `cw_sys_config` ";
  $qry.="WHERE `var_name` IN ('host','domain','address','broadcast','gateway','network','netmask','dns1','dns2',";
  $qry.="'dhcp_range_from','dhcp_range_to','vpn_range_from','vpn_range_to','ntp_host','ntp_zone','dhcp_status') ";
  $res=$db->Execute($qry);
  if($res!==false){
  	while($arr=$res->FetchRow()){
    	$ret[$arr["var_name"]]=$arr["var_val"];
    }
    //extract system time
    $ret["ntp_time"]=date("H:i:s [d-m-Y]");
  }
  //return
  return $ret;
}
/**
* FUNCTION: putNetworkConf
* Put and reload network configuration 
* @param networkConf:NetworkConf -> structure contains network settings
* @return:int -> If success method returns 1, else it returns zero
*/
function putNetworkConf($networkConf){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=0;
  //save configuration
  if(is_array($networkConf)){
    //save configuration in db
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["host"]))."', `commented`='0' WHERE `var_name`='host' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["domain"]))."', `commented`='0' WHERE `var_name`='domain' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["address"]))."', `commented`='0' WHERE `var_name`='address' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["broadcast"]))."', `commented`='0' WHERE `var_name`='broadcast' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["gateway"]))."', `commented`='0' WHERE `var_name`='gateway' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["network"]))."', `commented`='0' WHERE `var_name`='network' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["netmask"]))."', `commented`='0' WHERE `var_name`='netmask' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["dns1"]))."', `commented`='0' WHERE `var_name`='dns1' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["dns2"]))."', `commented`='0' WHERE `var_name`='dns2' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["dhcp_status"]))."', `commented`='0' WHERE `var_name`='dhcp_status' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["dhcp_range_from"]))."', `commented`='0' WHERE `var_name`='dhcp_range_from' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["dhcp_range_to"]))."', `commented`='0' WHERE `var_name`='dhcp_range_to' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["vpn_range_from"]))."', `commented`='0' WHERE `var_name`='vpn_range_from' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["vpn_range_to"]))."', `commented`='0' WHERE `var_name`='vpn_range_to' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["ntp_host"]))."', `commented`='0' WHERE `var_name`='ntp_host' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($networkConf["ntp_zone"]))."', `commented`='0' WHERE `var_name`='ntp_zone' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='http://".string2sql(trim($networkConf["address"]))."', `commented`='0' WHERE `var_name`='server-name' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    //write configuration to file
    $ret=writeNetConf(true);
    //return
    return $ret;
  }
  //return 
  return 0;
}
/*******************************   SMTP   *************************************/
/**
* FUNCTION: getSmtpConf
* Get smtp configurations
* @param null
* @return:NetworkConf -> Structure contains smtp settings
*/
function getSmtpConf(){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=array();
  //extract smtp configuration
  $qry="SELECT `var_name`,`var_val` FROM `cw_sys_config` ";
  $qry.="WHERE `var_name` IN ('smtp_host','smtp_protocol','smtp_port','smtp_from','smtp_auth','smtp_user','smtp_pass') ";
  $res=$db->Execute($qry);
  if($res!==false){
  	while($arr=$res->FetchRow()){
    	$ret[$arr["var_name"]]=$arr["var_val"];
    }
  }
  //return
  return $ret;
}
/**
* FUNCTION: putSmtpConf
* Put smtp configuration 
* @param smtpConf:SmtpConf -> structure contains smtp settings
* @return:int -> If success method returns 1, else it returns zero
*/
function putSmtpConf($smtpConf){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=0;
  //save configuration
  if(is_array($smtpConf)){
    //save configuration in db
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_host"]))."', `commented`='0' WHERE `var_name`='smtp_host' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_protocol"]))."', `commented`='0' WHERE `var_name`='smtp_protocol' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_port"]))."', `commented`='0' WHERE `var_name`='smtp_port' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_from"]))."', `commented`='0' WHERE `var_name`='smtp_from' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_auth"]))."', `commented`='0' WHERE `var_name`='smtp_auth' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_user"]))."', `commented`='0' WHERE `var_name`='smtp_user' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    $qry="UPDATE `cw_sys_config` SET `var_val`='".string2sql(trim($smtpConf["smtp_pass"]))."', `commented`='0' WHERE `var_name`='smtp_pass' ";
    $res=$db->Execute($qry); if($res===false) return 0;
    //write configuration to file
    $ret=writeSmtpConf(true);
    //return
    return $ret;
  }
  //return 
  return 0;
}     
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
/**
* FUNCTION: writeNetConf
* Write net conf on FS and reload network interfaces
* @param reload:boolean -> if true reload network interfaces
* @return:int -> If success method returns 1, else it returns zero
*/
function writeNetConf($reload=true){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=0;
  $now=date("H:i:s [d-m-Y]");
  //get network parameters
  $qry="SELECT * FROM `cw_sys_config`";
  $res=$db->Execute($qry);
  if($res!==false){
    $network=array();
  	while($arr=$res->FetchRow()){
    	$networkConf[$arr["var_name"]]=trim($arr["var_val"]);
    }
    if($networkConf["dhcp_status"]=="1") $vpn_comment="#"; else $vpn_comment="";
    if(trim($networkConf["dns2"])==""){
      $network_dns=$networkConf["dns1"];
      $dhcp_dns=$networkConf["dns1"];
    }else{
      $network_dns=$networkConf["dns1"]." ".$networkConf["dns2"];
      $dhcp_dns=$networkConf["dns1"].", ".$networkConf["dns2"];
    } 
  }
  //edit file contents
  if(is_array($network)){
    $time=time();
    $fileArray=array(
      array( // network conf file
        "path" => $voiceoneWSDocumentRoot."/sandbox/interfaces.".$time,
        "comment_char" => "#",
        "contents" => "# The loopback network interface\n". 
                      "auto lo\n".
                      "iface lo inet loopback\n".
                      "\n". 
                      "# The primary network interface\n". 
                      "auto eth0\n".
                      "iface eth0 inet manual\n". 
                      "        up ifconfig \$IFACE 0.0.0.0 up\n". 
                      "        up ip link set \$IFACE promisc on\n".
                      "        down ip link set \$IFACE promisc off\n".
                      "        down ifconfig \$IFACE down\n".
                      "\n".
                      "# The bridge interface\n". 
                      "auto br0\n".
                      "iface br0 inet static\n".
                      "        address ".$networkConf["address"]."\n". 
                      "        netmask ".$networkConf["netmask"]."\n".
                      "        network ".$networkConf["network"]."\n".
                      "        broadcast ".$networkConf["broadcast"]."\n". 
                      "        gateway ".$networkConf["gateway"]."\n".
                      "        # dns-* options are implemented by the resolvconf package, if installed\n".
                      "        dns-nameservers ".$network_dns."\n".
                      "        # Build bridge\n".
                      "        bridge_ports eth0 tap0\n".
                      "        # Bridge options\n".
                      "        bridge_fd 0                     # Forward delay in seconds\n".
                      "        bridge_stp off\n".
                      "        bridge_maxwait 5\n".
                      "        # Set IF_OPENVPN variable for the openvpn scripts in if-up.d and if-down.d\n".
                      "        openvpn server\n".
                      "        # Interface pre-up and post-down scripts\n".
                      "        pre-up /usr/sbin/openvpn --mktun --dev tap0\n".
                      "        pre-up ifconfig tap0 0.0.0.0 promisc\n".
                      "        post-down /usr/sbin/openvpn --rmtun --dev tap0\n"
        ),
      array( //dhcp conf file
        "path" => $voiceoneWSDocumentRoot."/sandbox/dhcpd.".$time,
        "comment_char" => "#",
        "contents" => "ddns-update-style none;\n".
                      "log-facility local7;\n". 
                      "\n".
                      "option tftp-server-name \"".$networkConf["server-name"]."\";\n".
                      "option bootfile-name \"".$networkConf["filename"]."\";\n".
                      "\n".
                      "subnet ".$networkConf["network"]." netmask ".$networkConf["netmask"]." {\n".
                      "  range ".$networkConf["dhcp_range_from"]." ".$networkConf["dhcp_range_to"].";\n".
                      "  option domain-name \"".$networkConf["domain"]."\";\n".
                      "  option domain-name-servers ".$dhcp_dns.";\n".
                      "  option broadcast-address ".$networkConf["broadcast"].";\n".
                      "  option routers ".$networkConf["gateway"].";\n".
                      "  default-lease-time 600;\n".
                      "  max-lease-time 7200;\n".
                      "}\n"
        ), 
      array( //vpn conf file
        "path" => $voiceoneWSDocumentRoot."/sandbox/vpn.".$time,
        "comment_char" => ";",
        "contents" => "; daemon configuration\n".
                      "mode server\n".
                      "tls-server\n".
                      "proto udp\n".
                      "port 1194\n".
                      "user nobody\n".
                      "group nogroup\n".
                      "\n".
                      "; tunnel configuration\n".
                      "dev tap0\n".
                      "\n".
                      $vpn_comment."server-bridge ".$networkConf["address"]." ".$networkConf["netmask"]." ".$networkConf["vpn_range_from"]." ".$networkConf["vpn_range_to"]."\n".
                      $vpn_comment."push \"route-gateway ".$networkConf["gateway"]."\"\n".
                      $vpn_comment."ifconfig-pool-persist /var/openvpn/openvpn.leases\n".
                      "\n".
                      "client-to-client\n".
                      "\n".
                      "passtos\n".
                      "comp-lzo\n".
                      "management 127.0.0.1 5555\n".
                      "keepalive 10 120\n".
                      "\n".
                      "tun-mtu 1500\n".
                      "tun-mtu-extra 32\n".
                      "mssfix 1450\n".
                      "\n".
                      "persist-key\n".
                      "persist-tun\n".
                      "persist-local-ip\n".
                      "persist-remote-ip\n".
                      "\n".
                      "; logging and status\n".
                      "#writepid /var/run/openvpn.pid\n".
                      "#status /var/log/openvpn/openvpn-status.log\n".
                      "verb 1\n".
                      "\n".
                      "; certificates and authentication\n".
                      "dh /etc/openvpn/keys/dh1024.pem\n".
                      "ca /etc/openvpn/keys/ca.crt\n".
                      "cert /etc/openvpn/keys/server.crt\n".
                      "key /etc/openvpn/keys/server.key\n".
                      "\n".
                      "plugin /usr/lib/openvpn/openvpn-auth-pam.so login\n".
                      "#username-as-common-name\n".
                      "client-cert-not-required\n"
        ),
      array( //hosts conf file
        "path" => $voiceoneWSDocumentRoot."/sandbox/hosts.".$time,
        "comment_char" => "#",
        "contents" => "127.0.0.1\tlocalhost\n".        
                      "127.0.1.1\t".$networkConf["host"].".".$networkConf["domain"]."\t".$networkConf["host"]."\n".
                      $networkConf["address"]."\t".$networkConf["host"].".".$networkConf["domain"]."\t".$networkConf["host"]."\n".
                      "\n".
                      "# The following lines are desirable for IPv6 capable hosts\n".
                      "::1 ip6-localhost ip6-loopback\n".
                      "fe00::0 ip6-localnet\n".
                      "ff00::0 ip6-mcastprefix\n".
                      "ff02::1 ip6-allnodes\n".
                      "ff02::2 ip6-allrouters\n".
                      "ff02::3 ip6-allhosts\n"
        ),
      array( //ntp conf file
        "path" => $voiceoneWSDocumentRoot."/sandbox/ntp.".$time,
        "comment_char" => "#",
        "contents" => "driftfile /var/lib/ntp/ntp.drift\n".
                      "\n".
                      "# Enable this if you want statistics to be logged.\n".
                      "#statsdir /var/log/ntpstats/\n".
                      "\n".
                      "statistics loopstats peerstats clockstats\n".
                      "filegen loopstats file loopstats type day enable\n".
                      "filegen peerstats file peerstats type day enable\n".
                      "filegen clockstats file clockstats type day enable\n".
                      "\n". 
                      "server ".$networkConf["ntp_host"]."\n".
                      "\n".
                      "# By default, exchange time with everybody, but don't allow configuration.\n".
                      "restrict -4 default kod notrap nomodify nopeer noquery\n".
                      "restrict -6 default kod notrap nomodify nopeer noquery\n".
                      "\n".
                      "# Local users may interrogate the ntp server more closely.\n".
                      "restrict 127.0.0.1\n".
                      "restrict ::1\n"
        )
      );
  }
  //write config file
  if(!is_array($fileArray)) return 0;
  else{ 
    //move network config file to sandbox
    $fileList="";
    foreach($fileArray as $file) $fileList.=$file["path"]." ";
    exec("sudo $voTools copyNetConfToSandbox $fileList",$output,$retScript);
    //edit config file in sandbox
    foreach($fileArray as $file){
      $star_modify=false;
      $modified=false;
      $newcontents="";
      //add comment to file contents
      $file["contents"]=$file["comment_char"]."#################################################################\n".
                        $file["comment_char"]."### AUTOMATICALLY GENERATED by VOICEONE ".$now."####\n".
                        $file["comment_char"]."#################################################################\n".
                        $file["contents"]; 
      //read file and prepare new one
      if(@is_file($file["path"])){
        //parse file lines and replace voiceone part
    	  $lineArr=@file($file["path"]);
        if(is_array($lineArr)){
        	$star_modify=false;
        	foreach($lineArr as $k=>$line){
            if(strstr($line,"VOICEONE_START")!==false){
              $star_modify=true;
              $newcontents.=$file["comment_char"]."[VOICEONE_START]\n";
              continue;
            }
            if(($star_modify===true)&&(strstr($line,"VOICEONE_END")!==false)){
              $star_modify=false;
              $newcontents.=$file["contents"];
              $newcontents.=$file["comment_char"]."[VOICEONE_END]\n";
              $modified=true;
              continue;
            }
            if($star_modify!==true){
              $newcontents.=$line;
              continue;
            }
          }
        }
      }
      if($modified!==true){
        $newcontents=$file["comment_char"]."[VOICEONE_START]\n".$file["contents"].$file["comment_char"]."[VOICEONE_END]\n";
      }
      //write changed file to sandbox
      if(file_put_contents($file["path"],$newcontents)===false) return 0;
    }
    //copy sandbox file to configuration file
    exec("sudo $voTools copyNetConfFromSandbox $fileList ".$networkConf["ntp_zone"]." ".$networkConf["host"],$output,$retScript);
    //verify if config files in sandbox has been deleted
    foreach($fileArray as $file){
      if(file_exists($file["path"])) return 0;
    }
    //reload network configurations
    if($reload==true){
      if($networkConf["dhcp_status"]=="1"){
      	exec("sudo $voTools reloadNetConf 1",$output,$retScript);
      }else{
      	exec("sudo $voTools reloadNetConf 0",$output,$retScript);
      }
    }
    //return success
    return 1;
  }
}
/**
* FUNCTION: writeSmtpConf
* Write smtp conf on FS and reload smtp
* @param reload:boolean -> if true reload smtp
* @return:int -> If success method returns 1, else it returns zero
*/
function writeSmtpConf($reload=true){
	global $db,$voTools,$voiceoneWSDocumentRoot;
  $ret=0;
  $now=date("H:i:s [d-m-Y]");
  //get network parameters
  $qry="SELECT `var_name`,`var_val` FROM `cw_sys_config` ";
  $qry.="WHERE `var_name` IN ('smtp_host','smtp_protocol','smtp_port','smtp_from','smtp_auth','smtp_user','smtp_pass') ";
  $res=$db->Execute($qry);
  if($res!==false){
    $network=array();
  	while($arr=$res->FetchRow()){
    	$smtpConf[$arr["var_name"]]=trim($arr["var_val"]);
    }
    if(trim($smtpConf["smtp_user"])!="") $username=$smtpConf["smtp_user"]; else $username="";
    if(trim($smtpConf["smtp_auth"])!="") $password=$smtpConf["smtp_pass"]; else $password="";
  }
  //edit file contents
  if(!is_array($smtpConf)) return 0;
  else{
    $time=time();
    $file=$voiceoneWSDocumentRoot."/sandbox/smtp.".$time;    
    $contents="##################################################################\n".
              "#### AUTOMATICALLY GENERATED by VOICEONE ".$now."####\n".
              "##################################################################\n".
              "# Set default values for all following accounts.\n".
              "defaults\n".
              "logfile /var/log/maillog\n".
              "syslog LOG_MAIL\n".
              "\n".
              "# The SMTP server of the provider.\n".
              "account voiceone\n".
              "auto_from off\n".
              "from ".$smtpConf["smtp_from"]."\n".
              "tls off\n".
              "host ".$smtpConf["smtp_host"]."\n".
              "protocol ".$smtpConf["smtp_protocol"]."\n".
              "port ".$smtpConf["smtp_port"]."\n".
              "auth ".$smtpConf["smtp_auth"]."\n".
              "user ".$username."\n".
              "password ".$password."\n".
              "\n".
              "# Set a default account\n".
              "account default : voiceone\n";
    //move network config file to sandbox
    exec("sudo $voTools copySmtpConfToSandbox $file",$output,$retScript);
    //edit file
    $star_modify=false;
    $modified=false;
    $newcontents="";
    if(@is_file($file)){
      //parse file lines and replace voiceone part
  	  $lineArr=@file($file);
      if(is_array($lineArr)){
      	$star_modify=false;
      	foreach($lineArr as $k=>$line){
          if(strstr($line,"VOICEONE_START")!==false){
            $star_modify=true;
            $newcontents.="#[VOICEONE_START]\n";
            continue;
          }
          if(($star_modify===true)&&(strstr($line,"VOICEONE_END")!==false)){
            $star_modify=false;
            $newcontents.=$contents;
            $newcontents.="#[VOICEONE_END]\n";
            $modified=true;
            continue;
          }
          if($star_modify!==true){
            $newcontents.=$line;
            continue;
          }
        }
      }
    }
    if($modified!==true){
      $newcontents="#[VOICEONE_START]\n".$contents."#[VOICEONE_END]\n";
    }
    //write changed file to sandbox
    if(file_put_contents($file,$newcontents)===false) return 0;
    //copy sandbox file to configuration file
    exec("sudo $voTools copySmtpConfFromSandbox $file",$output,$retScript);
    //verify if config files in sandbox has been deleted
    if(file_exists($file)) return 0;
    //return success
    return 1;
  }  
}
/**
* FUNCTION: readNetworkConf
* Copy network config files to sandbox and read the network configuration running on the system
* @param null
* @return:NetworkConf -> Structure contains network settings
*/
function readNetworkConf(){
	global $voTools,$voiceoneWSDocumentRoot;
  $ret=array();
	//move network config file to sandbox
  $time=time();
  $sandboxNetworkFilePath = $voiceoneWSDocumentRoot."/sandbox/interfaces.".$time;
  $sandboxDHCPFilePath = $voiceoneWSDocumentRoot."/sandbox/dhcpd.".$time;
  $sandboxVPNFilePath = $voiceoneWSDocumentRoot."/sandbox/vpn.".$time;
  $sandboxHOSTSFilePath = $voiceoneWSDocumentRoot."/sandbox/hosts.".$time;
  $sandboxNTPFilePath = $voiceoneWSDocumentRoot."/sandbox/ntp.".$time;
  $sandboxDHCPPidPath = $voiceoneWSDocumentRoot."/sandbox/dhcpd.pid.".$time;
  $sandboxTimeZonePath = $voiceoneWSDocumentRoot."/sandbox/timezone.".$time;
  exec("sudo $voTools copyNetConfToSandbox $sandboxNetworkFilePath $sandboxDHCPFilePath $sandboxVPNFilePath $sandboxHOSTSFilePath $sandboxNTPFilePath $sandboxDHCPPidPath $sandboxTimeZonePath",$output,$retScript);
  //read network config file from sandbox
  if(@is_file($sandboxNetworkFilePath)){
  	$lineArr=@file($sandboxNetworkFilePath);
    if(is_array($lineArr)){
    	$not_parsered="";
    	$read=false; 
    	foreach($lineArr as $line){
      	$line=str_replace(array("\n","\r"),"",trim($line));
        if(($line=="")||(substr($line,0,4)=="auto")) continue;
        else if((substr($line,0,5)=="iface")&&(substr(substr($line,6),0,strpos(substr($line,6)," "))=="br0")){
        	$read=true;
        }else if($read===true){
        	if(substr($line,0,5)=="iface"){
          	$read=false;
            break;
        	}else{
          	//extract address
          	if(strpos($line,"address")!==false){
            	$address=trim(substr($line,(strpos($line,"address")+strlen("address"))));
            	if(strpos($address," ")!==false) $address=substr($address,0,strpos($address," "));
            } 
            //extract netmask
          	else if(strpos($line,"netmask")!==false){
            	$netmask=trim(substr($line,(strpos($line,"netmask")+strlen("netmask"))));
            	if(strpos($netmask," ")!==false) $netmask=substr($netmask,0,strpos($netmask," "));
            }
            //extract network
          	else if(strpos($line,"network")!==false){
            	$network=trim(substr($line,(strpos($line,"network")+strlen("network"))));
            	if(strpos($network," ")!==false) $network=substr($network,0,strpos($network," "));
            }
            //extract broadcast
          	else if(strpos($line,"broadcast")!==false){
            	$broadcast=trim(substr($line,(strpos($line,"broadcast")+strlen("broadcast"))));
            	if(strpos($broadcast," ")!==false) $broadcast=substr($broadcast,0,strpos($broadcast," "));
            }
            //extract gateway
          	else if(strpos($line,"gateway")!==false){
            	$gateway=trim(substr($line,(strpos($line,"gateway")+strlen("gateway"))));
            	if(strpos($gateway," ")!==false) $gateway=substr($gateway,0,strpos($gateway," "));
            }
            //extract dns1 and dns2
          	else if(strpos($line,"dns-nameservers")!==false){
            	$dnsnameservers=trim(substr($line,(strpos($line,"dns-nameservers")+strlen("dns-nameservers"))));
            	if(strpos($dnsnameservers," ")!==false){
              	$dnsnameserversArr=explode(" ",$dnsnameservers);
                if(is_array($dnsnameserversArr)){
                	if(isset($dnsnameserversArr[0])) $dns1=$dnsnameserversArr[0];
                  if(isset($dnsnameserversArr[1])) $dns2=$dnsnameserversArr[1];
                }
              }else{ 
              	$dns1=$dnsnameservers;
                $dns2="";
              }
            }
            //others
            else if(substr($line,0,1)!="#"){
            	$not_parsered.=$line."\n";
            }
          }
        }
      }
      //fill data in response structure
      $ret=array(
      		"address" => $address,
      		"netmask" => $netmask,
          "network" => $network,
          "broadcast" => $broadcast,
          "gateway" => $gateway,
          "dns1" => $dns1,
          "dns2" => $dns2
          //"advanced" => substr($not_parsered,0,-1)
      	);
      //read DHCP pid file from sandbox
      $dhcp_status=0;
      if(@is_file($sandboxDHCPPidPath)){
      	$lineArr=@file($sandboxDHCPPidPath);
        if(is_array($lineArr)){
      		foreach($lineArr as $line){
       			$line=str_replace(array("\n","\r"),"",trim($line));
            if($line!=""){
            	$dhcp_status=1;
            	break;
            }
          }
        }
      }
      $ret["dhcp_status"]=$dhcp_status;
      //read DHCP config file from sandbox
      $dhcp_range_from="";
      $dhcp_range_to="";
      $star_reading=false;
      if(@is_file($sandboxDHCPFilePath)){
      	$lineArr=@file($sandboxDHCPFilePath);
        if(is_array($lineArr)){
        	$not_parsered="";
        	$read=false;
        	foreach($lineArr as $line){
          	$line=str_replace(array("\n","\r",";"),"",trim($line));
            if(strstr($line,"VOICEONE_START")!==false) $star_reading=true;
            else if(strstr($line,"VOICEONE_END")!==false) break;
            else if($star_reading===true){
              if(substr($line,0,5)=="range"){
              	$range=trim(substr($line,(strpos($line,"range")+strlen("range"))));
              	if(strpos($range," ")!==false){
                	$rangeArr=explode(" ",$range);
                  if(is_array($rangeArr)){
                  	if(isset($rangeArr[0])) $dhcp_range_from=trim($rangeArr[0]);
                    if(isset($rangeArr[1])) $dhcp_range_to=trim($rangeArr[1]);
                  }
                }
              }
            }
          }
        }
      }
      //fill data in response structure
      $ret["dhcp_range_from"]=$dhcp_range_from;
      $ret["dhcp_range_to"]=$dhcp_range_to;
      //read VPN config file from sandbox
      $vpn_range_from="";
      $vpn_range_to="";
      $star_reading=false;
      if(@is_file($sandboxVPNFilePath)){
      	$lineArr=@file($sandboxVPNFilePath);
        if(is_array($lineArr)){
        	foreach($lineArr as $line){
          	$line=str_replace(array("\n","\r",";"),"",trim($line));
            if(strstr($line,"VOICEONE_START")!==false) $star_reading=true;
            else if(strstr($line,"VOICEONE_END")!==false) break;
            else if($star_reading===true){
              if((substr($line,0,13)=="server-bridge")||(substr($line,0,14)=="#server-bridge")){
              	if(strpos($line," ")!==false){
                	$rangeArr=explode(" ",$line);
                  if(is_array($rangeArr)){
                  	if(isset($rangeArr[3])) $vpn_range_from=trim($rangeArr[3]);
                    if(isset($rangeArr[4])) $vpn_range_to=trim($rangeArr[4]);
                  }
                }
              }
            }
          }
        }
      }
      //fill data in response structure
      $ret["vpn_range_from"]=$vpn_range_from;
      $ret["vpn_range_to"]=$vpn_range_to;
      //read HOSTS config file from sandbox
      $host="";
      $domain="";
      $star_reading=false;
      if(@is_file($sandboxHOSTSFilePath)){
      	$lineArr=@file($sandboxHOSTSFilePath);
        if(is_array($lineArr)){
        	foreach($lineArr as $line){
          	$line=str_replace(array("\n",";"),"",trim($line));
            if(strstr($line,"VOICEONE_START")!==false) $star_reading=true;
            else if(strstr($line,"VOICEONE_END")!==false) break;
            else if($star_reading===true){
              $lineArr=explode("\t",$line);
              if((is_array($lineArr))&&(count($lineArr)>2)){
                $host=$lineArr[2];
                $domain=substr($lineArr[1],strlen($host."."));
                if((trim($host)!="")&&(trim($domain)!="")) break;
              }
            }
          }
        }
      }
      //fill data in response structure
      $ret["host"]=$host;
      $ret["domain"]=$domain;
      //read NTP config file from sandbox
      $ntp_host="";
      $star_reading=false;
      if(@is_file($sandboxNTPFilePath)){
      	$lineArr=@file($sandboxNTPFilePath);
        if(is_array($lineArr)){
        	foreach($lineArr as $line){
          	$line=str_replace(array("\n","\t",";"),"",trim($line));
            if(strstr($line,"VOICEONE_START")!==false) $star_reading=true;
            else if(strstr($line,"VOICEONE_END")!==false) $star_reading=false;
            else if($star_reading===true){
              if(substr($line,0,6)=="server"){
                $ntp_host=trim(substr($line,(strpos($line,"server")+strlen("server"))));
              }
            }
          }
        }
      }
      //fill data in response structure
      $ret["ntp_host"]=$ntp_host;
      //read timezone file from sandbox
      $ntp_zone="";
      $star_reading=false;
      if(@is_file($sandboxTimeZonePath)){
      	$lineArr=@file($sandboxTimeZonePath);
        if(is_array($lineArr)){
        	foreach($lineArr as $line){
          	$line=str_replace(array("\n","\t",";"),"",trim($line)); 
            if(substr($line,0,9)=="zoneinfo="){
              $zoneinfo=trim(substr($line,strlen("zoneinfo=")));
            }else if(substr($line,0,10)=="localtime="){
              $localtime=trim(substr(strstr($line," -> "),strlen(" -> ")));
            }
          }
        }
      }
      if(strlen($localtime)>strlen($zoneinfo)){
        $ntp_zone=substr($localtime,strlen($zoneinfo));
        if(substr($ntp_zone,0,1)=="/"){
          $ntp_zone=substr($ntp_zone,1);
        }
      }
      //fill data in response structure
      $ret["ntp_zone"]=$ntp_zone;
      $ret["ntp_time"]=date("H:i:s [d-m-Y]");
    }
  }
  //delete network config file from sandbox
  @unlink($sandboxNetworkFilePath);
  @unlink($sandboxDHCPFilePath);
  @unlink($sandboxVPNFilePath);
  @unlink($sandboxHOSTSFilePath);
  @unlink($sandboxNTPFilePath);
  @unlink($sandboxDHCPPidPath);
  @unlink($sandboxTimeZonePath);
  //return
  return $ret;
}


/**
* FUNCTION: readSmtpConf
* Copy smtp config files to sandbox and read the smtp configuration running on the system
* @param null
* @return:SmtpConf -> Structure contains smtp settings
*/
function readSmtpConf(){
global $voTools,$voiceoneWSDocumentRoot;
  $ret=array();
	//move network config file to sandbox
  $time=time();
  $sandboxSmtpFilePath=$voiceoneWSDocumentRoot."/sandbox/smtp.".$time;
  exec("sudo $voTools copySmtpConfToSandbox $sandboxSmtpFilePath",$output,$retScript);
  //read SMTP config file from sandbox
  $ret=array(
      "smtp_host" => "",
      "smtp_protocol" => "",
      "smtp_port" => "",
      "smtp_from" => "",
      "smtp_auth" => "",
      "smtp_user" => "",
      "smtp_password" => ""
    );
  $star_reading=false;
  if(@is_file($sandboxSmtpFilePath)){
  	$lineArr=@file($sandboxSmtpFilePath);
    if(is_array($lineArr)){
    	$read=false;
    	foreach($lineArr as $line){
      	$line=str_replace(array("\n","\r",";"),"",trim($line));
        if(strstr($line,"VOICEONE_START")!==false) $star_reading=true;
        else if(strstr($line,"VOICEONE_END")!==false) break;
        else if($star_reading===true){
          if(substr($line,0,strlen("host"))=="host"){
            $ret["smtp_host"]=trim(substr($line,(strpos($line,"host")+strlen("host"))));
          }else if(substr($line,0,strlen("protocol"))=="protocol"){
            $ret["smtp_protocol"]=trim(substr($line,(strpos($line,"protocol")+strlen("protocol"))));
          }else if(substr($line,0,strlen("port"))=="port"){
            $ret["smtp_port"]=trim(substr($line,(strpos($line,"port")+strlen("port"))));
          }else if(substr($line,0,strlen("from"))=="from"){
            $ret["smtp_from"]=trim(substr($line,(strpos($line,"from")+strlen("from"))));
          }else if(substr($line,0,strlen("auth"))=="auth"){
            $ret["smtp_auth"]=trim(substr($line,(strpos($line,"auth")+strlen("auth"))));
          }else if(substr($line,0,strlen("user"))=="user"){
            $ret["smtp_user"]=trim(substr($line,(strpos($line,"user")+strlen("user"))));
          }else if(substr($line,0,strlen("password"))=="password"){
            $ret["smtp_password"]=trim(substr($line,(strpos($line,"password")+strlen("password"))));
          }
        }
      }
    }
  } 
  //delete smtp config file from sandbox
  @unlink($sandboxSmtpFilePath);
  //return
  return $ret;
}
?>