<?
//****************               Zapata CARD               *********************
//****************          METHOD IMPLEMENTATION          *********************
//*****************************************************************************/

// - getZapGroupChannel(id:int):Card[] -----------------------------------------
function getZapGroupChannel($id) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE id=$id ";
  $qry="SELECT * FROM `cw_zapata_groupchannel` $condition";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) $ret[]=$arr;
  return $ret;
}

// ---- getZapChannel(id:int):Zone[] --------------------------------------

function getZapChannel($id) {
  global $db;
  $count=0;
  if ($id!="") $condition=" WHERE `port_id`='$id' ";
  $qry="SELECT * FROM `cw_zapata_channel` $condition ORDER BY `channelfrom` DESC";
  $res=$db->Execute($qry);
  
  while ($arr=$res->FetchRow()) $ret[]=$arr;
  
return $ret;
}

// ---- getZone(id:int):Zone[] -----------------------------------------------
function getZone($id) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE id=$id ";
  $qry="SELECT * FROM `cw_zapata_zone` ORDER BY `name` $condition";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) $ret[]=$arr;
  return $ret;
}

// ---- getZapOption(id:int):Card[] -----------------------------------------------

function getZapOption($line_type) {
  global $db;
  $count=0;
  if ($line_type!="") $condition="WHERE `line_type`='$line_type' ";
  $qry="SELECT * FROM `cw_zapata_protocol` $condition";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) $ret[]=$arr;
  return $ret;
}

// ---- getZap(id:int):Card[] -----------------------------------------------

function getZap($id) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE `id`='$id' ";
  $qry="SELECT * FROM `cw_zapata_card` $condition";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) $ret[]=$arr;
  return $ret;
}

// ---- putCard(id:int):int -----------------------------------------------
// you can add an isdn card by simply passing the id of the card type.

function putZap($id) {
  global $db;

  //read how many ports are already installed
  $qry="SELECT * FROM cw_zapata_port";
  $res=$db->Execute($qry);
  $installedPort=$res->RecordCount();
  //echo $installedPort."HJHJ";
  //read how many ports has the choosed card
  $qry="SELECT * FROM cw_zapata_card WHERE id=$id";
  $res=$db->Execute($qry);
  $arr=$res->FetchRow();
  $ports=$arr["ports"];
  //echo $ports." port";
  //read the id of the previous installed card 
  $qry="SELECT MAX(card_id) as lastid FROM cw_zapata_port";
  $res=$db->Execute($qry);
  $arr=$res->FetchRow();
  $card_id=$arr["lastid"];
  if ($card_id!="NULL") $card_id++; else $card_id=1;
 // echo $card_id."card"; die();
  $res=true;
  for ($i=1; $i<=$ports; $i++) {
    $qry="INSERT INTO cw_zapata_port (port,card,card_id) VALUES ($i,$id,$card_id)";
    $res&=$db->Execute($qry);
  }

  //write to AstConfig or File
  //writeMIsdn(false);

  //update the misdn-init.conf
  //---if ($installedPort>0) writeMisdnInitConfFile(true);
  //---else writeMisdnInitConfFile(false);
  
  if ($res===true) $res=$card_id;
  return $res;
}

// ---- delCard(id:int):int -----------------------------------------------

function delZap($id) {
  global $db;
  $res=true;
  //echo $id;die();
  $qry="SELECT * FROM `cw_zapata_port` WHERE `card_id`='$id'";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()){ $ret[]=$arr;}//print_r($ret);die("fdsf") 
  foreach ($ret as $a=>$b){
    //echo "$b[id]";die();
    $qry="DELETE FROM `cw_zapata_channel` WHERE `port_id`='$b[id]'";
    $res&=$db->Execute($qry);
  
    $qry="DELETE FROM `ast_config` WHERE `z_id`='$b[id]'";
    $res&=$db->Execute($qry);
  }
  //print_r($ret);die("fdfs");
  $qry="DELETE FROM cw_zapata_port WHERE card_id=$id";
  $res&=$db->Execute($qry);

  //  writeZapInitConfFile(true);
  return 1;
}


//-----putZapChannlConfig();---------------------------

function putZapChanneltoGroupChannel(){
  global $db;
  $qry="SELECT * FROM `cw_zapata_port` WHERE `frame_protocol`!='' ORDER BY `order`";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $channelrange=$arr['bchan'];
    $default=$arr['default'];
    $portid=$arr['id']; 
    $protocol=$arr['protocol'];
    $frame_protocol=$arr['frame_protocol'];
    $groupname=$arr['group'];
    if ($default=='0') {
      if ($frame_protocol=='FXO' or $frame_protocol=='FXS') {
        $qry="INSERT INTO `cw_zapata_groupchannel`(`port_id`,`channel`,`signalling`) VALUES ('$portid', '$channelrange','$protocol')";
      }
      $rec=$db->Execute($qry);
      $qry="SELECT * FROM `cw_zapata_channel` WHERE `port_id`='$portid'  ";
      $ree=$db->Execute($qry);
      while ($arr2=$ree->FetchRow()) {
        $channelfrom=$arr2['channelfrom'];
        $channelto=$arr2['channelto'];
        $signalling=$arr2['signalling'];
        $channel=$channelfrom;
        while ($channel<=$channelto) {
          $qry="INSERT INTO `cw_zapata_groupchannel`(`port_id`,`channel`,`signalling`) VALUES ('$portid', '$channel','$signalling')";
          $rec=$db->Execute($qry);
          $channel++;
        }
      }
    } elseif ($default=='1') {
      $channelarr=split('[,-]',$channelrange);
      $channel=$channelarr[0]; 
       
      while ($channel<=$channelarr[1]) {
        $qry="INSERT INTO `cw_zapata_groupchannel`(`port_id`,`channel`,`signalling`) VALUES ('$portid', '$channel','$signalling')";
        $rec=$db->Execute($qry);
        $channel++;
      }
      if ($frame_protocol=='E1') {
        $channel=$channelarr[2]; 
        while ($channel<=$channelarr[3]) {
          $qry="INSERT INTO `cw_zapata_groupchannel`(`port_id`,`channel`,`signalling`) VALUES ('$portid', '$channel','$signalling')";
          $rec=$db->Execute($qry);
          $channel++;
        }
      } 
      // echo "<pre>";  print_r($channelarr);
    } // close if else default 
  }// close port loop
}// close function

//-----putZapChannlConfig();---------------------------

function putZapChannelConfig(){
global $db;
  $qry="SELECT * FROM `cw_zapata_channel` ORDER BY `channelfrom`";
  $res=$db->Execute($qry);

  while ($arr=$res->FetchRow()) {
    $groupname=$arr['group'];
    $port_id=$arr['port_id'];
    $channelfrom=$arr['channelfrom'];
    $channelto=$arr['channelto'];
    $signalling=$arr['signalling'];
    $xlaw=$arr['xlaw'];

    if($groupname!='')$domain=$groupname; else $domain=$port_id;
    if ($signalling) {
      $signal_value=substr($signalling,0,3)."_".substr($signalling,3,2);
      putAstConfigZap('zapata.conf','channels','signalling',$signal_value,'','0',$domain);
    }
    if ($channelfrom != $channelto)$channelrange=$channelfrom."-".$channelto; else $channelrange=$channelfrom; 
    putAstConfigZap('zapata.conf','channels','channel',$channelrange,'','0',$domain);
  }
}

// ---- writeZaptelInitConfFile():int ----------------------------------------------
//private

function writeZaptelInitConfFile($stop=false) {
  global $db,$voiceoneWSDocumentRoot,$VoTools;
  //global $db,$zaptelInit,$zaptel_conf,$zaptel_sh,$safe_asterisk;
  $txt="";
  $qry="SELECT * FROM `cw_zapata_port` WHERE `protocol`!='' AND `frame_protocol`!='' GROUP BY `order` ASC"; 
  $ree=$db->Execute($qry);
  while( $arr=$ree->FetchRow()){$result[]=$arr; } 
  $ports=$result;
  $count=1;
  
  ///////////span=spannum,timing,LBO,Framing,Coding,CRC
  foreach ($ports as $p) {
    $frame_protocol=$p["frame_protocol"];
    $timing=$p["timing"];
    $lbo=$p["lbo"];
    $protocol=$p[protocol];
    $framing=$p["framing"];
    $coding=$p["coding"];
    $yellow=$p["yellow"];
    if ($frame_protocol=="E1" or $frame_protocol=="T1" ) {
      if ($protocol!=''){
        $txt.="span=".$count.",".$timing.",".$lbo.",".$framing.",".$coding;
        $count++;   
        if ($yellow!="") $txt.=",".$yellow;
        $txt.="\n";
      }
    }
  }  
  $txt.="\n";
  foreach ($ports as $p) {
    $id=$p["id"];
    $frame_protocol=$p["frame_protocol"];
    $card_id=$p["card_id"];
    $card=$p["card"];
    $port=$p["port"];
    $timing=$p["timing"];
    $lbo=$p["lbo"];
    $framing=$p["framing"];
    $coding=$p["coding"];
    $protocol=$p["protocol"];  
    $dchan=$p["dchan"];
    $bchan=$p["bchan"];
    $port_xlaw=$p["xlaw"];
    $default=$p["default"];
    if ($frame_protocol=='FXS') {
      $txt2.=$protocol."=".$bchan."\n";
      if ($port_xlaw!='') $txt2.=$port_xlaw."=".$bchan."\n";
    } 
    if($frame_protocol=="FXO") {
      $txt1.=$protocol."=".$bchan."\n";
      if ($port_xlaw!='') $txt1.=$port_xlaw."=".$bchan."\n";
    } 
    if ($frame_protocol=="T1" or $frame_protocol=="E1") {
      //$default='';
      $channel=getZapChannel($id);
      //echo "<PRE>";print_r($channel);
      foreach ($channel as $h) {
        $channelfrom=$h[channelfrom];
        $channelto=$h[channelto];
        if ($channelfrom==$channelto or $channelto=='') $channelrange=$channelfrom; 
        else $channelrange=$channelfrom."-".$channelto;
        $signalling=$h[signalling];
        $xlaw=$h[xlaw]; 
        if ($protocol=='fx') {
          $txt.=$signalling.'='.$channelrange."\n";
          if ($xlaw!='') $txt.=$xlaw."=".$channelrange."\n";
        }
        if ($protocol=='pri' and $default!='1') {
          $txt.='bchan='.$channelrange."\n";
          if ($port_xlaw!='') $txt.=$port_xlaw."=".$channelrange."\n";
          if ($old_dc!=$dchan) $txt.='dchan='.$dchan."\n";
          $old_dc=$dchan; 
        }
      }
      if ($default=='1') {
        $txt.="bchan=".$bchan."\n";
        if ($port_xlaw!="") $txt.=$port_xlaw."=".$bchan."\n";
        if ($dchan!="") $txt.="dchan=".$dchan."\n";
      }
    }//close if T1 or E1 
  }  //end of while
  //die();
  if($txt1!="") $txt.="\n".$txt1;
  if($txt2!="") $txt.="\n".$txt2;
  //if($txt1!="")$txt.="\nbchan=".substr($txt1,0,-1);
  //if($txt2!="")$txt.="\nbchan=".substr($txt2,0,-1);
  $ports=getZone(0);
  //echo "<PRE>";print_r($ports);die("fdsf"); 
  $count=1; // CHANGE ME no Idea what Yuen is thinking about here ???
  foreach ($ports as $p) {
    $loadzone=$p["loadzone"];
    $def=$p["defaultzone"];
    $name=$p["name"];
    if($loadzone=="1") $loadz.=$name.",";
    if($def=="1") $defaultzone=$name;
  }
  // echo $loadz;die();
  $loadz=substr($loadz,0,-1);
  $txt.="\n\nloadzone=".$loadz."\n";
  $txt.="defaultzone=".$defaultzone."\n";

  $filename=$voiceoneWSDocumentRoot."/sandbox/zaptel.conf";
  $ret=file_put_contents($filename,$txt); 

  unset($out);

  //restart the asterisk
  if ($stop===true) {
    $count++; // CHANGE ME and check if we changed something somewhere
    error_log("sudo $VoTools safe_asterisk stop");exec("sudo $VoTools safe_asterisk stop",$out);errArr($out); //stop the asterisk server
    error_log("sudo $VoTools zaptel_init stop");exec("sudo $VoTools zaptel_init stop",$out);errArr($out);     //unload zaptel driver
  }
  error_log("sudo ".$VoTools);exec("sudo ".$VoTools." zaptel_conf \"$voiceoneWSDocumentRoot/sandbox\" ",$out);errArr($out); //move the zaptel configuration file
  errArr($out);
  if ($count>1) {
    error_log("sudo $VoTools zaptel_init restart");exec("sudo $VoTools zaptel_init restart",$out); errArr($out); // load drivers again
    sleep(5);
    error_log("sudo $VoTools safe_asterisk start");exec("sudo $VoTools safe_asterisk start",$out); errArr($out); // start the asterisk server
  }      
  error_log("Completed!");

  return $ret;
}

//******************            Zapata GROUP              *********************
//******************************************************************************

// -- getzapataGroup(id:int):Group[] -------------------------------------------

function getZapataGroup($id,$onlyCustomOption=false) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE id=$id ";
  $qry="SELECT * FROM cw_zapata_group $condition";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) { 
    unset($opt);
    $group_id=$arr["id"];
    $name=$arr["name"];
    
    $msns=$arr["msns"];
    //$channel_order=$arr["Channel_order"];
    $channel=getChannel(getChannelFromEntity($group_id));
    $arr["speeddial"]=$channel[0]["speeddial"];
    $arr["channel_order"]=$channel[0]["order"];
    
    //extract the ports of the group
    unset($port);
    $qry="SELECT * FROM `cw_zapata_channel` WHERE `group`='$name'";
    $res2=$db->Execute($qry);
    while ($arr2=$res2->FetchRow()) { 
      $channelto=$arr2[channelto];
      $channelfrom=$arr2[channelfrom];
      if ($channelfrom==$channelto or $channelto='') $channel1[]=$arr2["channelfrom"];
      else $channel1[]=$arr2["channelfrom"].'-'.$arr2['channelto'];
    }
    $arr["channel"]=$channel1;
    //extract the phonenumber of the group
    $arr["msns"]=split("\|",$msns);
    //read the specific group option
    $arr["option"]=getEntityOption($id);

    $ret[]=$arr;
  }
  
  return $ret;
}

// ---- putZapataGroup(group:IsdnGroup):int ----------------------------------------------

function putZapataGroup($group) {
  global $db,$zapPrefix;
  //echo "<pre>";print_r($group); die("fdsf"); 
  //del group if already exists
  $groupno=$group["groupno"];
  if (isset($group["id"]) and $group["id"]!="") {
    $channel["id"]=getChannelFromEntity($group["id"]);
    delZapataGroup($group["id"],false);
    $entity["id"]=$group["id"];
  }

  $ret=1;
  $name=$group["name"];
  $oldname=$group["oldname"]; 
  //$channel_order=$group["Channel_order"];//delete??
  $msns=msns2string($group["msns"]);
  $ports=$group["port"];
  $did=$group["did"];
  $rule="0";
  //create a new entity
  $entity["key"]="0";
  $entity["type"]=ZAPATA_GROUP;
  $entity_id=putEntity($entity);
  // print_r($entity);
  if (is_object($entity_id) or $entity_id==0) return 0;

  //extract the rule set ID
  errArr($group["option"]);
  $rule=extractRuleFromOption($group["option"],ZAP);
  //insert the isdn group
  $qry = "INSERT INTO cw_zapata_group (`id`,`name`,`rule`,`group`,`msns`,`did`) VALUES ($entity_id,'$name','$rule','$groupno','$msns','$did')";
  $res=$db->Execute($qry);
  if ($res===false) return new soap_fault('Server','','Zap Group creation error, mysql INSERT command failed'); 
  //save the group specific options 
  putEntityOption($group["option"],ZAP,$entity_id,$group);
  //insert the ports
  if (is_array($ports)) $qry = "update `cw_zapata_port` set `group`='' where `group`='$oldname'";
  $res=$db->Execute($qry);
  foreach($ports as $p) {
    $qry = "INSERT INTO cw_zapata_portgroup (`channel`,`group`) VALUES ($p,$entity_id)";
    $res=$db->Execute($qry);
    delAstConfigZap("zapata.conf","channels",'','',$p);
    $qry = "UPDATE `cw_zapata_channel` SET `group`='$name', `available`='0'  WHERE `id`='$p'";
    $res=$db->Execute($qry);
    $z_id.=$p.','; 
  }
  $z_id=substr($z_id,0,-1);
  $arrPort=getZapChannel(0);
  $portList="";
  //print_r($arrPort);die();
  if (@is_array($arrPort)) {
    foreach ($arrPort as $p) {
      $channelfrom=$p[channelfrom];
      $channelto=$p[channelto];
      if ($channelfrom == $channelto or $channelto=='') $channelrange=$channelfrom;
      else $channelrange=$channelfrom."-".$channelto;
      if (in_array($p["id"],$ports)) $portList.=$channelrange.",";
    }
  }
  $portList=substr($portList,0,-1);
  //echo $portList;  
  // echo $z_id; die();
  $res=putAstConfigZap("zapata.conf", "channels", "group", $groupno,'','0',$name);
  $res=putAstConfigZap("zapata.conf", "channels", "channel", $portList,'','0',$name);
  //put the new Channel
  $channel['technology']=ZAP;
  $channel['resource']="g".$groupno;
  // if ($channel['technology']==ZAP) {$channel['resource']="g".$name;}
  $channel['key']=$entity_id;
  $channel['msns']=$group["msns"];
  $channel['rule']=$rule;
  $channel['did']=$did;
  $channel['trunk']=1;
  $channel['speeddial']=$group["speeddial"];
  //print_r($channel);
  $channelId=putChannel($channel);  
  //update the incoming context
  // $res=delAstConfigZap("zapata.conf", "$name", "context");
  // $res=putAstConfigZap("zapata.conf", "$name", "context", "trunk_".$channelId);
  
  //write the global Variables
  generateGlobalVar();

  //write to AstConfig or File
  //writeMIsdn();
  
  //restart asterisk (workaround until chan_mISDN fixed)
  //error_log("sudo $safe_asterisk stop");exec("sudo $safe_asterisk stop",$out);errArr($out);//stop the asterisk
  //error_log("sudo $safe_asterisk start");exec("sudo $safe_asterisk start",$out);errArr($out);//start the asterisk

  //reload the chan_misdn
  //sendCommand("unload chan_misdn.so");
  sendCommand("unload chan_zapata.so");
  //error_log($ret);
  sleep(2);

  //sendCommand("load chan_misdn.so");
  sendCommand("load chan_zapata.so");
  //error_log($ret);
  sleep(2);

  sendCommand("reload");
  //error_log($ret);
  sleep(3);
  
  if ($ret>0) $ret=$entity_id;
  return $ret;
}

// ---- delZapataGroup(id:int):int --------------------------------------------------

function delZapataGroup($id,$reload=true) {
  global $db,$zapPrefix;
  
  //retrieve the queue name
  $g=getZapataGroup($id);
  $name=$g[0]["name"];
  $qry="UPDATE `cw_zapata_channel` SET `group`='', `available`='1' WHERE `group`='$name'";
  $res=$db->Execute($qry);

  //remove the options written in the asterisk table
  delEntityOptionZap($id, ZAP);
  $qry="DELETE FROM cw_zapata_group WHERE id='$id'";
  $res=$db->Execute($qry);
  if ($res===false) return new soap_fault('Server','','Zap group remove error, mysql DELETE command failed');

  $qry="DELETE FROM cw_zapata_portgroup WHERE `group`='$id'";
  $res=$db->Execute($qry);
  if ($res===false) return new soap_fault('Server','','Zap port group remove error, mysql DELETE command failed');

  //update the Channels
  $channelId=getChannelFromEntity($id);
  if ($channelId!=0) delChannel($channelId);

  $ret=delEntity($id);
  if ($reload!==false) {
    //restart asterisk (workaround until chan_mISDN fixed)
    //error_log("sudo $safe_asterisk stop");exec("sudo $safe_asterisk stop",$out);errArr($out);//stop the asterisk
    //error_log("sudo $safe_asterisk start");exec("sudo $safe_asterisk start",$out);errArr($out);//start the asterisk

    //reload the chan_misdn
    $ret=sendCommand("unload chan_zap.so");
    //error_log($ret);
    sleep(2);

    $ret=sendCommand("load chan_zap.so");
    //error_log($ret);
    sleep(2);

    $ret=sendCommand("reload");
    //error_log($ret);
    sleep(3);
  }

  return 1;
}

// ---- getZapPort(id:int):Port[] --------------------------------------------

function getZapPort($id) {
  global $db;
  $count=0;
  if ($id!="") $condition="WHERE id=$id ";
  $qry="SELECT * FROM cw_zapata_port $condition ORDER BY card_id, port";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    //check if available
    $res2=$db->Execute("SELECT * FROM cw_zapata_portgroup WHERE port=".$arr["id"]);
    if ($res2->RecordCount()>0) $arr["available"]=0; else $arr["available"]=1;
    $ret[]=$arr;
  }
  return $ret;
}

// ---- updateZapPort(ports:Port[]):int ----------------------------------------

//function updateZapPort($ports,$type) {
function updateZapPort($ports) {
  //echo "<PRE>";print_r($ports);die();
  global $db;
  $res=true;

  $qry="UPDATE cw_zapata_zone SET `defaultzone`='0',`loadzone`='0'"; 
  $res=$db->Execute($qry);

  foreach ( $ports[loadzone] as $v => $b) {
    $loadzone=$b[loadzone];
    $qry="UPDATE cw_zapata_zone SET `loadzone`='1' WHERE name='$loadzone'"; 
    $res=$db->Execute($qry);
    $new_loadzone.=$loadzone.",";
  }
  $defzone=$ports[defzone];
  $qry="UPDATE cw_zapata_zone SET `defaultzone`='1' WHERE name='$defzone'"; 
  $res=$db->Execute($qry);

  $result=array();
  $order=1;
  $count=count($ports["frame_protocol"]);
  ////////////get old data of config for zap port//////////
  //for($x=0;$x<$count;$x++) {
  //$id=$ports["frame_protocol"][$x]["id"];
  $qry="SELECT * FROM `ast_config` WHERE `filename`='zapata.conf'and `z_id`!='' AND `cat_metric`!='0' AND `var_name`!='channel'"; 
  $ree=$db->Execute($qry);
  while( $arr=$ree->FetchRow()) $result_old[]=$arr;
  //}
  //echo "<PRE>";print_r($result_old);die('gfgf');
  //count($result);
  //print_r($result);
  //delAstConfigZap('zapata.conf','channels','channel');//del all data of all ports
  //    delAstConfigZap('zapata.conf','channels','signalling');//del all data of all ports
  //foreach ($result_old as $v){
  //echo $v[id];die();
  //putAstConfigZap('zapata.conf','Port_id='.$v[z_id],$v[var_name],$v[var_val],$v[z_id]);
  //}
  $bchan[0]=1;
  $fxoId=array();
  $fxsId=array();
  $channel=0;
  $qry1='';
  $qry="TRUNCATE TABLE `cw_zapata_channel` ";
  $db->Execute($qry);
  $qry="DELETE FROM `cw_zapata_groupchannel` WHERE `groupname`='' ";
  $db->Execute($qry);

  for($x=0;$x<$count;$x++) {
    $id=$ports["frame_protocol"][$x]["id"];
    $frame_protocol=$ports["frame_protocol"][$x]['frame_protocol'];
    $timing=$ports["timing"][$x]['timing'];
    $lbo=$ports["lbo"][$x]['lbo'];
    $default=$ports["default1"][$x]['default1'];
    $framing=$ports["framing"][$x]['framing'];
    $coding=$ports["coding"][$x]['coding'];
    $yellow=$ports["yellow"][$x]['yellow'];
    $protocol=$ports["protocol"][$x]['protocol'];
    $groupname=$ports["groupname"][$x]['groupname'];
    $portxlaw=$ports["portxlaw"][$x]['portxlaw']; 
    $countchannel=count($ports["channel1"][$x]['channel1']);

    for ($j=1;$j<=$countchannel; $j++) {
      $channelfrom=$ports["channel1"][$x]['channel1'][$j];
      $channelto=$ports["channel2"][$x]['channel2'][$j];
      $type=$ports["type"][$x]['type'][$j];
      $signalling=$ports["signalling"][$x]['signalling'][$j];
      $xlaw=$ports["xlaw"][$x]['xlaw'][$j];
      if (substr($frame_protocol,0,2)!="FX" AND $frame_protocol!=''and $protocol!='' and $channelfrom and $channelto and $default=='0') {
        $channel=$channelfrom;
        /*    while ($channel<=$channelto){
        $qry="insert into `cw_zapata_groupchannel`(`id`,`port_id`,`group`,`channel`,`signalling`) values ('','$id','$groupname','$channel','$signalling')";
        $res=$db->Execute($qry);
        }*/
        //echo "<PRE>";print_r($channelarr); 
        $qry="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`,`type`) VALUES ('','$id','$groupname','$channelfrom','$channelto','$signalling','$xlaw','$type')";
        $res=$db->Execute($qry);
        if ($protocol=='fx') {
          if ($groupname!='') $domain=$groupname; 
          else $domain=$id;
          //putAstConfigZap('zapata.conf','channels','signalling',$signalling,'','0',$domain);
        }
        if ($channelfrom != $channelto) $channelrange=$channelfrom."-".$channelto;
        else $channelrange=$channelfrom; 
        //if($protocol=='pri') putAstConfigZap('zapata.conf','channels','channel',$channelrange,'','0',$domain);
        //$default="false"; 
      }
    }

    if ($frame_protocol=='E1') {
      $bchan[2]=$bchan[0]+14;
      $dchan=$bchan[0]+15;
      $bchan[3]=$bchan[0]+16;$bchan[4]=$bchan[0]+30;
      $new_bc=$bchan[0]."-".$bchan[2].",".$bchan[3]."-".$bchan[4];
      $new_dc=$dchan;
      if ($default=='1') {
        $qry="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`) VALUES ('','$id','$groupname','$bchan[0]','$bchan[2]','','$portxlaw')";
        $res=$db->Execute($qry);
        $qry="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`) VALUES ('','$id','$groupname','$bchan[3]','$bchan[4]','','$portxlaw')";
        $res=$db->Execute($qry);
      }
      $bchan[0]=$bchan[4]+1;
    }
    if ($frame_protocol=='T1') {
      $bchan[2]=$bchan[0]+22;
      $dchan=$bchan[0]+23;
      $new_bc=$bchan[0]."-".$bchan[2];
      $new_dc=$dchan;
      if ($default=='1') {
        $qry="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`) VALUES ('','$id','$groupname','$bchan[0]','$bchan[2]','','$portxlaw')";
        $res=$db->Execute($qry);
      }
      $bchan[0]=$bchan[2]+2;
    }
    if ($frame_protocol=='FXS') {
      $fxsId[]=$id;
      $fsxlaw[][law]=$portxlaw;
      $fxssig[][sig]=$protocol;
      $fxs[][group]=$groupname;
      $new_bc="";
      $new_dc="";
      $lbo="";
      $framing="";
      $coding="";
      $yellow="";
    }
    if ($frame_protocol=='FXO') {
      $fxoId[]=$id;
      $fxolaw[][law]=$portxlaw;
      $fxosig[][sig]=$protocol;
      $fxo[][group]=$groupname;
      $new_bc="";
      $new_dc="";
      $lbo="";
      $framing="";
      $coding="";
      $yellow="";
    }
    if ($protocol=='fx') $portxlaw='';

    $qry="UPDATE cw_zapata_port SET `default`='$default', `xlaw`='$portxlaw', `protocol`='$protocol',`yellow`='$yellow', `order`='$order', `frame_protocol`='$frame_protocol',`timing`='$timing',`lbo`='$lbo',`framing`='$framing',`coding`='$coding',`bchan`='$new_bc',`dchan`='$new_dc' WHERE id=$id"; 
    $res=$db->Execute($qry);
    
    if ($frame_protocol=="T1" or $frame_protocol=="E1" ) {
      if($groupname) $id=$groupname;
      //if ($default!='0') putAstConfigZap('zapata.conf','channels','channel',$new_bc,'','0',$id);
      //putAstConfigZap('zapata.conf','channels'.$order,'example1',$new_bc,$id);
    }
    if ($frame_protocol=='T1' or $frame_protocol=="E1") $order++;
  
  }//close for loop

  //WRITE FXO CHANNEL
  if (count($fxoId)>0) {
    //print_r($fxosig);die();
    for ($x=0;$x<count($fxoId);$x++) { 
      $new_bc=$bchan[0];
      $fxosig1=$fxosig[$x]['sig'];
      $xlaw=$fxolaw[$x]['law'];
      $qry1="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`) VALUES ('','$fxoId[$x]','','$bchan[0]','$bchan[0]','$fxosig1','$xlaw')";
      $db->Execute($qry1);
      $qry="UPDATE `cw_zapata_port` SET `order`='$order', `bchan`='$new_bc' WHERE `frame_protocol`='FXO' AND `id`='$fxoId[$x]'";
      $db->Execute($qry);
      if($fxo[$x][group]) $fxoId[$x]=$fxo[$x][group];
      $signal_value=substr($fxosig[$x][sig],0,3)."_".substr($fxosig[$x][sig],3,2);
      //putAstConfigZap('zapata.conf','channels','signalling',$signal_value,"","0",$fxoId[$x]);
      //putAstConfigZap('zapata.conf','channels','channel',$new_bc,"","0",$fxoId[$x]);
      $bchan[0]++;
      $order++;
    }
  }

  //WRITE FXS CHANNEL
  if (count($fxsId)>0) {
    for ($x=0;$x<count($fxsId);$x++) {
      $new_bc=$bchan[0];
      $sig=$fxssig[$x]['sig'];
      $xlaw=$fxslaw[$x]['law'];
      $qry1="INSERT INTO `cw_zapata_channel`(`id`,`port_id`,`group`,`channelfrom`,`channelto`,`signalling`,`xlaw`) VALUES ('','$fxsId[$x]','','$bchan[0]','$bchan[0]','$sig','$xlaw')";
      $db->Execute($qry1);
      $qry="UPDATE `cw_zapata_port` SET `order`='$order', `bchan`='$new_bc' WHERE `frame_protocol`='FXS' AND `id`='$fxsId[$x]'";
      $db->Execute($qry);
      $bchan[0]++;
      if($fxs[$x][group]) $fxsId[$x]=$fxs[$x][group];
      $signal_value=substr($fxssig[$x][sig],0,3)."_".substr($fxssig[$x][sig],3,2);
      //putAstConfigZap('zapata.conf','channels','signalling',$signal_value,"","0",$fxoId[$x]);
      //putAstConfigZap('zapata.conf','channels','channel',$new_bc,"","0",$fxsId[$x]);
      $order++;
    }
  }
  $qry="UPDATE cw_zapata_port SET `protocol`='',`xlaw`='', `yellow`='', `order`='',`timing`='',`lbo`='',`framing`='',`coding`='',`bchan`='',`dchan`='' WHERE `frame_protocol`='' OR `protocol`=''"; 
  $res=$db->Execute($qry);
  //echo "<PRE>";print_r($channelarr); die ('fds');
  // putZapChanneltoGroupChannel();
  //putZapChannelConfig();
  writeZaptelInitConfFile(true);

  return $res;
}


// *****************************************************************************
// ****************         COPIED AND MODIFIED                   **************
// ****************         FROM interface.php                    **************
// *****************************************************************************


// ---- viewAstConfigZap(filename:string):string ---------------------------------------

function viewAstConfigZap($f) {
  global $db;
  $qry="SELECT DISTINCT filename FROM ast_config WHERE filename='$f'";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $filename=$arr["filename"];

    $qry="SELECT DISTINCT category FROM ast_config WHERE filename='$filename' ORDER BY cat_metric";
    $res2=$db->Execute($qry);
    while ($arr=$res2->FetchRow()) {
      $category=$arr["category"];
      $ret.= "\n";
      $ret.= "[".$category."]\n";

      $qry="SELECT * FROM ast_config WHERE filename='$filename' AND category='$category' ORDER BY  cat_metric, var_metric";
      $res3=$db->Execute($qry);
      while ($arr=$res3->FetchRow()) {
        $var_name=$arr["var_name"];
        $var_val=$arr["var_val"];
        $comment=$arr["comment"];
        $commented=$arr["commented"];
        if ($var_name!="" and $commented!=1)
          if ($var_name=='channel') $ret.="$var_name => $var_val";
          else $ret.= "$var_name = $var_val";
        if ($comment!="" and $var_name!="") $ret.= "\t ;$comment";
        $ret.="\n";
      }
    }
  }
  return $ret;
}

  
// ---- putAstConfigZap($file:string, $context:string, $var:string, $var_data:string): int 

function putAstConfigZap($file,$context,$var,$var_data,$comment="",$commented=0,$id="") {
  global $db;

    $context=string2sql($context);
    $var=string2sql($var);
    $var_data=string2sql($var_data);
    $comment=string2sql($comment);
    
    //check if any other same astconfig entry is already into the table
    $qry="SELECT * FROM ast_config WHERE filename=\"$file\" AND category=\"$context\" AND var_name=\"$var\" AND var_val=\"$var_data\"";
    $res=$db->Execute($qry);
    if ($res->RecordCount()>0) {
      $arr=$res->FetchRow();
      return $arr["id"];  
    }
  
    //------------------- zapata part----------------------
    //calculate the var_metric
    if ($id!="") {
      $qry="SELECT * FROM ast_config WHERE filename='$file' and category='$context' and `z_id`='$id'";
      $res=$db->Execute($qry);
      $count=$res->RecordCount();
      $arrCat=$res->FetchRow();
      if ($count>0) {//if find
        $qry="SELECT MAX(var_metric) as maxvar FROM ast_config WHERE filename='$file' and category='$context'";
        $res=$db->Execute($qry);
        $arr=$res->FetchRow();
        $var_metric=$arr["maxvar"]+1;
        $cat_metric=$arrCat["cat_metric"];
      } else {//if not find
        $qry="SELECT MAX(cat_metric) as maxcat,MAX(var_metric) as maxvar FROM  ast_config WHERE  filename='$file'";
        $res=$db->Execute($qry);
        $arr=$res->FetchRow();
        $cat_metric=$arr["maxcat"]+1;    
        $var_metric=0;
      } 
      $g="";
      $g="SELECT * from `cw_zapata_port` WHERE `id`='$id' ";
      $res=$db->Execute($g);
      $count=$res->RecordCount();
      if ($count<=0) {
        $g="SELECT * from `cw_zapata_port` WHERE `group`= '$id' ";
        $res=$db->Execute($g);
      }
      while ($arr=$res->FetchRow()) {
        foreach($arr as $field=>$value) $v[$field]=$value;
        $ret[]=$v;
      }
      //echo count($ret);echo "<PRE>";print_r($ret);die();
      $res=$db->Execute($g);
      $arr=$res->FetchRow();
      $card_id=$arr['card_id'];
      $port=$arr['order'];
      // echo $id;print_r($arr);die();
      if (count($ret)>1) {
        $port="";$card_id="";
        foreach ($ret as $v=>$b) $port.=$b['order'].',';$card_id.=$b['card_id'].',';
        $port=substr($port,0,-1);$card_id=substr($card_id,0,-1);
      }
      if ($var=='channel') {  
        $comment="Card ".$card_id." Port ".$port;
        if ($count>0) $comment.=" and Port ID ".$id; 
        else $comment.=" in group ".$id;
      }
    } else {
      //calculate the var_metric
      $qry="SELECT * FROM ast_config WHERE filename='$file' and category='$context'";
      $res=$db->Execute($qry);
      $count=$res->RecordCount();
      $arrCat=$res->FetchRow();
      if ($count>0) {
        $qry="SELECT MAX(var_metric) as maxvar FROM ast_config WHERE filename='$file' and category='$context'";
        $res=$db->Execute($qry);
        $arr=$res->FetchRow();
        $var_metric=$arr["maxvar"]+1;
        $cat_metric=$arrCat["cat_metric"];
      } else {
        $qry="SELECT MAX(cat_metric) as maxcat FROM  ast_config WHERE  filename='$file'";
        $res=$db->Execute($qry);
        $arr=$res->FetchRow();
        $cat_metric=$arr["maxcat"]+1;    
        $var_metric=0;
      }    
    }  
    //$var=string2sql($var);
    //$var_data=string2sql($var_data); 
    //$comment=string2sql($comment); 
    
    $qry="INSERT INTO ast_config (cat_metric,var_metric,commented,filename,category,var_name,var_val,comment,z_id)";
    $qry.="VALUES($cat_metric,$var_metric,$commented,\"$file\",\"$context\",\"$var\",\"$var_data\",\"$comment\",\"$id\")";
    $res=$db->Execute($qry);
    $astconfig_id=$db->Insert_ID();
    return $astconfig_id;
}


// ---- delAstConfigZap($file:string, $context:string, $var:string): int 

function delAstConfigZap($file,$category,$var_name="",$var_val="",$z_id="") {
  global $db;
  if ($file=="zapata.conf") {
    $qry="DELETE FROM ast_config WHERE filename=\"$file\" AND `cat_metric` != '0'";
    if ($z_id!="") $qry.=" AND `z_id` LIKE \"".$z_id."\"";
  } else $qry="DELETE FROM ast_config WHERE filename=\"$file\" AND category like \"$category\" ";
  if ($var_name!="")  $qry.=" AND var_name  like \"".$var_name."\"";
  if ($var_val!="") $qry.=" AND var_val like \"".$var_val."\"";
  $res=$db->Execute($qry);
  return $res;
}

?>