<?
/**
 * VoiceOne Webservices Interface
 *
 * @package voiceone_webservices
 * @subpackage Network
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
/**
* FUNCTION: isVotoolsExecutable
* Verify if vo-tools is executable
* @param null
* @return:String -> If executable method returns 1, else it returns vo-tools's path
*/
function isVotoolsExecutable(){
	global $voTools;
  if(!((@fileperms($voTools) & 0x0001))){
  	return $voTools;
  } 
  return "1";
}
/**
* FUNCTION: checkDatabaseAccess
* Verify database access
* @param null
* @return:int -> If accessible method returns 1, else it returns zero
*/
function checkDatabaseAccess(){
	global $db;
  if($db===false) return 0; 
  return 1;
}
// ---- setSystemName($name:string): int
/**
* FUNCTION: setSystemName
* Put system name in voiceone database
* @param name:String -> System name
* @return:int -> If success method returns 1, else it returns zero
*/
function setSystemName($system_name){
  global $db;
  //check input parameters
  if(trim($system_name)=="") return 0;
  //get system name option
  $systemOptionArr=getOptionByName("hostname","SYSTEM");
  if((!is_array($systemOptionArr))||(!is_array($systemOptionArr[0]))){
    return 0;
  }
  $option_id=$systemOptionArr[0]["id"];
  //remove from ast_config table
  $qry="UPDATE cw_option set value='".string2sql($system_name)."' WHERE id=".$option_id."";
  $res=$db->Execute($qry);
  if($res===false) return 0;
  //return
  return 1;
}
/**
* FUNCTION: setSystemPasswords
* Put system passwords in filesystem files
* @param passwords:SystemPasswords
* @return:int -> If success method returns 1, else it returns zero
*/
function setSystemPasswords($passwords){
  global $voTools,$voiceoneWSDocumentRoot,$synDbUser,$synDbPassword,$synDbName;
  //set config filepath
  $ws_config=$voiceoneWSDocumentRoot."/config/config.inc.php";
  //set asterisk api password
  if((isset($passwords["asterisk_api"]))&&(trim($passwords["asterisk_api"])!='')){
    exec("sudo $voTools setVoiceonePassword $ws_config \\\$API_pass ".$passwords["asterisk_api"],$output,$retScript);
    exec("sudo $voTools setAsteriskManagerPassword ".$passwords["asterisk_api"],$output,$retScript);
    exec("sudo $voTools setAstmanproxyPassword ".$passwords["asterisk_api"],$output,$retScript);
  }
  //set voiceone db password
  if((isset($passwords["voiceone_db"]))&&(trim($passwords["voiceone_db"])!='')){
    exec("sudo $voTools setMysqlPassword $synDbUser $synDbPassword $synDbName ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setVoiceonePassword $ws_config \\\$synDbPassword ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setAsteriskDbPassword ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setAsteriskCdrPassword ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setAutomysqlbackupPassword ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setAsteriskStatPassword ".$passwords["voiceone_db"],$output,$retScript);
    exec("sudo $voTools setVoiceoneUpdatePassword ".$passwords["voiceone_db"],$output,$retScript);
    if(function_exists("initFaxService")){
      exec("sudo $voTools setFaxDbPassword ".$passwords["voiceone_db"],$output,$retScript);
    }
  }
  //set voiceone ws password
  if((isset($passwords["voiceone_ws"]))&&(trim($passwords["voiceone_ws"])!='')){
    exec("sudo $voTools setVoiceonePassword $ws_config \\\$htaccessPassword ".$passwords["voiceone_ws"],$output,$retScript);
  }
  //set system password for shell user "voiceone"
  if((isset($passwords["ssh_access"]))&&(trim($passwords["ssh_access"])!='')){
    exec("sudo $voTools setSystemPassword ".$passwords["ssh_access"],$output,$retScript);
  }
  //return
  return 1;
}
/**
* FUNCTION: getSystemConfig
* Read from filesystem some configuration parameters like network and smtp configuration
* @param null
* @return:AssociativeArray -> ifNetwork module are installed it returns the network 
*     and smtp configuration, else it returns an empty array
*/
function getSystemConfig(){
  $ret=array();
  if((function_exists("readNetworkConf"))&&
     (function_exists("readSmtpConf"))){
    //read configurations
    $networkConf=readNetworkConf();
    $smtpConf=readSmtpConf();
    //write an associative array for response
    if((is_array($networkConf))&&(count($networkConf)>0)&&
       (is_array($smtpConf))&&(count($smtpConf)>0)){
      $ret[]=array("key"=>"network_success","value"=>"1");
      foreach($networkConf as $k=>$v){
        $ret[]=array("key"=>$k,"value"=>$v);
      }
      foreach($smtpConf as $k=>$v){
        $ret[]=array("key"=>$k,"value"=>$v);
      }
      //return "success"
      return $ret;
    }
  }
  $ret[]=array("key"=>"network_success","value"=>"0");
  //return "failed"
  return $ret;
}
/**
* FUNCTION: putSystemConfig
* Rwrite system configuration
* @param confAss:AssociativeArray -> Array of system parameter
* @return:int -> If success method returns 1, else it returns zero
*/
function putSystemConfig($confAss){
  //process associative array
  if(is_array($confAss)){
    foreach($confAss as $p){
      $confArr[$p["key"]]=$p["value"];
    }
  }
  //build network configuration array
  $netConfArr=array(
      'host'  	    => $confArr["host"],
      'domain'  	  => $confArr["domain"],
      'address'  	  => $confArr["address"],
      'netmask'  	  => $confArr["netmask"],
      'network'  	  => $confArr["network"],
      'broadcast'   => $confArr["broadcast"],
      'gateway'  	  => $confArr["gateway"],
      'dns1'  		  => $confArr["dns1"],
      'dns2'  		  => $confArr["dns2"],
      'dhcp_status' => $confArr["dhcp_status"],
      'dhcp_range_from'	=> $confArr["dhcp_range_from"],
      'dhcp_range_to'		=> $confArr["dhcp_range_to"],
      'vpn_range_from'	=> $confArr["vpn_range_from"],
      'vpn_range_to'		=> $confArr["vpn_range_to"],
      'ntp_host'		=> $confArr["ntp_host"],
      'ntp_zone'    => $confArr["ntp_zone"],
      'ntp_time'    => $confArr["ntp_time"]
    );
  $ret1=putNetworkConf($netConfArr);
  //build smtp configuration array
  $smtpConfArr=array(
      'smtp_host'  	  => $confArr["smtp_host"],
      'smtp_protocol' => $confArr["smtp_protocol"],
      'smtp_port'     => $confArr["smtp_port"],
      'smtp_from'  	  => $confArr["smtp_from"],
      'smtp_auth'  	  => $confArr["smtp_auth"],
      'smtp_user'     => $confArr["smtp_user"],
      'smtp_pass'     => $confArr["smtp_pass"]
    );
  $ret2=putSmtpConf($smtpConfArr);
  if(($ret1==0)||($ret2==0)) return 0;
  //return
  return 1;
}
/**
* FUNCTION: initialize
* Inizialize voiceone system
* @param genKeys:int -> If 1 generete system RSA key, else don't generate it
* @return:int -> it returns always 1
*/
function initialize($genKeys) {
  global $db,$synDbUser,$synDbPassword,$voiceoneWSDocumentRoot,$voiceoneWSDirName;
  global $keyName,$sandboxServer,$voTools,$synDbName,$synDbHost;
  error_log("[VOICEONE SETUP PROCEDURE]");
  //stop Asterisk
  error_log("Stop asterisk...");
  exec("sudo $voTools asterisk_stop",$out);
  //remove all the tables
  error_log("Delete database tables...");
  $tables=$db->MetaTables('TABLES');
  if(is_array($tables)){
    foreach($tables as $t){ 
      $db->Execute("DROP TABLE `$t`");
    }
  }
  //write the right file permission
  error_log("Install agi and set files permissions...");
  $doc_root=substr($voiceoneWSDocumentRoot,0,-strlen($voiceoneWSDirName)-1);
  exec("sudo $voTools install ".$doc_root,$out);
  //import database dump
  error_log("Import database dump...");
  //insert database core structures
  $imported=false;
  $db_core=$voiceoneWSDocumentRoot."/modules/core/db";
  if($handle=@opendir($db_core)){
    while(false!==($file=@readdir($handle))){
      if(($file!=".")&&($file!="..")&&($file=="dump.sql")){
        $filePath=$db_core."/".$file;
        exec("cat $filePath | mysql --user=$synDbUser --password=$synDbPassword --host=$synDbHost $synDbName",$out);
        $imported=true;
      }
    }
    closedir($handle);
  }
  if($imported===true){
  	error_log("  -> core:".str_repeat(" ",30-strlen("core"))."   IMPORTED  ");
  }else{
  	error_log("  -> core:".str_repeat(" ",30-strlen("core"))." NOT IMPORTED");
  }
  //insert database module structure (all about the core)
  $modules_dir=$voiceoneWSDocumentRoot."/modules";
  if($handle=@opendir($modules_dir)) {
    while(false!==($module=@readdir($handle))){
      if(($module!=".")&&($module!="..")&&(substr($module,0,1)!=".")&&(strtolower(trim($module))!="core")&&(@is_dir($modules_dir."/".$module))){
      	$imported=false;
        $db_module=$modules_dir."/".$module."/db";
        if($mod_handle=@opendir($db_module)){
          while(false!==($file=@readdir($mod_handle))){
            if(($file!=".")&&($file!="..")&&($file=="dump.sql")){
              $filePath=$db_module."/".$file;
              exec("cat $filePath | mysql --user=$synDbUser --password=$synDbPassword --host=$synDbHost $synDbName",$out);
              $imported=true;
            }
          }
          closedir($mod_handle);
        }
        if($imported===true){
        	error_log("  -> ".$module.":".str_repeat(" ",30-strlen($module))."   IMPORTED  ");
        }else{
        	error_log("  -> ".$module.":".str_repeat(" ",30-strlen($module))." NOT IMPORTED");
        }
      }
    }
    closedir($handle);
  }
  //write extensions config file
  error_log("Write extensions config files in astconfig...");
  writeExtensionsConf();
  //write .conf files
  error_log("Write asterisk config files in astconfig...");
  writeConf();
  //initialize cw_sounds_file
  error_log("Grub asterisk sounds from filesystem...");
  soundsInit();
  //create the metagroups
  error_log("Create the metagroups...");
  putGroup(Array("id"=>GROUP_OF_ALL,          "name"=>"_all_",              "type"=>GROUP_OF_ALL,         "metagroup"=>1));
  putGroup(Array("id"=>GROUP_OF_EXTENSION,    "name"=>"_all-extensions_",   "type"=>GROUP_OF_EXTENSION,   "metagroup"=>1));
  putGroup(Array("id"=>GROUP_OF_RESOURCE,     "name"=>"_all-resources_",    "type"=>GROUP_OF_RESOURCE,    "metagroup"=>1));
  putGroup(Array("id"=>GROUP_OF_OFFICE,       "name"=>"_all-offices_",      "type"=>GROUP_OF_OFFICE,      "metagroup"=>1));
  putGroup(Array("id"=>GROUP_OF_APPLICATION,  "name"=>"_all-applications_", "type"=>GROUP_OF_APPLICATION, "metagroup"=>1));
  putGroup(Array("id"=>GROUP_OF_PHONENUMBER,  "name"=>"_all-phonenumbers_", "type"=>GROUP_OF_PHONENUMBER, "metagroup"=>1));
  //create the MetaGroup inclusions
  $res=putAstConfig("extensions.conf","_all_","include","_all-extensions_");
  $res=putAstConfig("extensions.conf","_all-extensions_","","","All Extensions",1);
  //$res=putAstConfig("extensions.conf","_all_","include","_all-offices_");
  $res=putAstConfig("extensions.conf","_all_","include","_all-resources_");
  $res=putAstConfig("extensions.conf","_all-resources_","","","All Resources",1);
  $res=putAstConfig("extensions.conf","_all_","include","_all-applications_");
  $res=putAstConfig("extensions.conf","_all-applications_","","","All Applications",1);
  //$res=putAstConfig("extensions.conf","_all_","include","_all-phonenumbers_");
  $res=putAstConfig("extensions.conf","_all_","include","_catch-all_");
  $res=putAstConfig("extensions.conf","_catch-all_","","","Catch All",1);
  $res=putAstConfig("extensions.conf","_catch-all_","exten","_X.,1,AGI(dial.php,entity=&group=".GROUP_OF_PHONENUMBER."&extension=\${EXTEN})");
  $res=putAstConfig("extensions.conf","_catch-all_","exten","_+.,1,AGI(dial.php,entity=&group=".GROUP_OF_PHONENUMBER."&extension=\${EXTEN})");
  $res=putAstConfig("extensions.conf","_catch-all_","exten","_X,1,AGI(dial.php,entity=&group=".GROUP_OF_PHONENUMBER."&extension=\${EXTEN})");  
  // Load System Plugin
  error_log("Load plugin system...");
  $pli=file_get_contents($voiceoneWSDocumentRoot."/config/backup/plugininfo.xml");
  $pld=file_get_contents($voiceoneWSDocumentRoot."/config/backup/plugindata.xml");
  $ret=putPlugin($pli, $pld);
  //create defualt context (for incoming call sended by not registered clients)
  error_log("Create defaul context in dialplan...");
  $res=putAstConfig("extensions.conf","default","exten","_[a-zA-Z0-9].,1,Hangup");
  $res=putAstConfig("extensions.conf","default","exten","_[a-gj-ru-zA-Z0-9],1,Hangup");
  $res=putAstConfig("extensions.conf","default","exten","s,1,Hangup");
  $res=putAstConfig("extensions.conf","default","exten","t,1,Hangup");
  $res=putAstConfig("extensions.conf","default","exten","i,1,Hangup");
  //Create the first Outgoing Rule
  error_log("Create defaul outgoing ruleset...");
  $arr=Array("name"=>"DefaultOutgoingRule","type"=>RULE_OUTGOING);
  $rule=putRule($arr);
  $arr=Array ("rule"=>$rule,"timesegment"=>0,"action"=>1,"resource"=>0,"group"=>GROUP_OF_ALL);
  $ret=putOutgoingRule($arr);
  //Create the first Incoming Rule
  error_log("Create defaul incoming ruleset...");
  $arr=Array("name"=>"DefaultIncomingRule","type"=>RULE_INCOMING);
  $rule=putRule($arr);
  $inc_macro=getMacroByName("incoming-call-to-group");
  $arr=Array ("rule"=>$rule,"timesegment"=>0,"callertype"=>CALLER_ALL,"macro"=>$inc_macro[0]['id'],"parameter"=>"dest=".GROUP_OF_EXTENSION);
  $ret=putIncomingRule($arr);
  //write conf settings
  error_log("Put technology options in astconfig...");
  $techArr=getTechnology(null);
  foreach($techArr as $t) {
    $ret=putOptionInAstConfig($t["id"],null,false);
  }
  //generate the global variable
  error_log("Generate global variables...");
  generateGlobalVar();
  //Generate the private and public key and move it in the right position
  if($genKeys==1){
    error_log("Generate RSA key...");
    exec("sudo $voTools generatePbxKey $voiceoneWSDocumentRoot/sandbox/ $keyName",$output,$retScript);
    exec("sudo $voTools inkey \"$voiceoneWSDocumentRoot/sandbox/$keyName\"",$output,$retScript);
  }else{
    error_log("Generate RSA key [disabled by setup option]...");
  }
  //reset the fax service deleting all related config files
  if(function_exists("initFaxService")){
    error_log("Init Fax Service...");
    initFaxService();
  }else{
    error_log("Init Fax Service [module not found]...");
  }
  //reset the ldap data deleting all but the structure
  if(function_exists("initLdapService")){
    error_log("Init Ldap Service...");
    initLdapService();
  }else{
    error_log("Init Ldap Service [module not found]...");
  }
  error_log("[VOICEONE SETUP COMPLEATED]");
  //return
  return 1;
}
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
/**
* FUNCTION: writeExtensionsConf
* Write extension conf file in astconfig
* @param null
* @return:int -> it returns always 1
*/
function writeExtensionsConf() {
  global $db;
  //remove all rows of sip.conf. It will be regenerated
  $res=delAstConfig("extensions.conf","%");
  //insert the GENERAL OPTION
  $arr=getConfOption("",OPTION_EXTENSION_GENERAL,0);
  if (is_array($arr))
  foreach ($arr as $v) {
    if ($v["value"]=="") $value=$v["default"]; else $value=$v["value"];
    if ($v["commented"]!="1") $res=putAstConfig("extensions.conf", "general", $v["name"], $value);
  }
  //insert the GLOBALS OPTION
  $arr=getConfOption("",OPTION_EXTENSION_GLOBALS,0);
  if (is_array($arr))
  foreach ($arr as $v) {
    if ($v["value"]=="") $value=$v["default"]; else $value=$v["value"];
    if ($v["commented"]!="1") $res=putAstConfig("extensions.conf", "globals", $v["name"], $value);
  }
  //return
  return 1;
}
/**
* FUNCTION: writeConf
* Write conf file in astconfig
* @param null
* @return:int -> it returns always 1
*/
function writeConf() {
  global $db,$voTools;
  // retrieve .conf file names
  $qry="SELECT DISTINCT `file` FROM `cw_config_file`";
  $res=$db->Execute($qry);
  while($arr=$res->FetchRow()) $filenames[]=$arr["file"];
  // load .conf files
  foreach($filenames as $filename){
    //remove all rows of filename. It will be regenerated
    $res=delAstConfig($filename,"%");
    //specific actions to do before load .conf files
    switch ($filename) {
      case "musiconhold.conf":
        //update cw_option
        exec("sudo $voTools getMohDir",$output,$retScript);
        $dir=$output[0]."/voiceone/default";
        $qry="UPDATE `cw_option` SET `default` = '".string2sql($dir)."' WHERE `category`='MOH_CLASS' AND `name`='directory' LIMIT 1;";
        $res=$db->Execute($qry);
        //section to write
        $section=1;
      break;
      case "features.conf":
      case "queues.conf":
      case "agents.conf":
      case "voicemail.conf":
        //section to write
        $section=1;
      break;
    }
    //retrieve categories
    $qry="SELECT `tag` , `category` FROM `cw_config_file` WHERE `file`='".string2sql($filename)."'";
    $res=$db->Execute($qry);
    $i=0;
    $ret=array();
    while ($arr=$res->FetchRow()) {
      $ret[$i]["tag"]=$arr["tag"];
      $ret[$i]["name"]=$arr["category"];
      $i++;
    }
    //read cw_option and write ast_config
    if(is_array($ret)){
      foreach($ret as $cat){
        $arr=getConfOption("",$cat["tag"],$section);
        if (is_array($arr)){
          foreach ($arr as $v){
            if ($v["value"]=="") $value=$v["default"]; else $value=$v["value"];
            //if ($v["commented"]==0) putAstConfig($filename, $cat["name"], $v["name"], $value, $v["comment"], $v["commented"]);
            putAstConfig($filename, $cat["name"], $v["name"], $value, $v["comment"], $v["commented"]);
          }
        }
      }
    }
  }
  //return
  return 1;
}
?>
