<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once($includePath.'/config/cfg.php');
  //require($includePath.'/constants.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
  //require($includePath.'/agi/agifunction.php');

/*********************** INITIALIZATION ***************************************/

  $agi = new AGI();
  $extension    =$agi->request["agi_extension"];
  $ruleContext  =$agi->request["agi_context"];
  error_log($ruleContext);
  $res=$db->Execute("SELECT id FROM cw_rule WHERE name='$ruleContext'");
  $arr=$res->FetchRow();
  $ruleId=$arr["id"];

  $entityId=$_GET["entity"];
  $entityGroup=$_GET["group"];
  $entityExt=str_replace(".","",str_replace("_","",$_GET["extension"]));

  $mandatoryChannel=$agi->get_variable("MANDATORYCHANNEL");
  $mandatoryChannel=$mandatoryChannel["data"];
  
  //if a mandatory Channel is set, then dial with a dialout
  if ($mandatoryChannel!="") {
    $entityId="";
    $entityGroup=GROUP_OF_PHONENUMBER;
  }
  
  $canContinue=true;
  
  error_log("-----------------------------------------------");
  error_log("Outgoing Rule Set id: $ruleId (ext:$extension - grp: $entityGroup)");
  error_log("-----------------------------------------------");
/*********************** PAGE LOGIC ********************************************/
  
  // DIAL SOMETHING
  $qry="SELECT * FROM cw_rule_outgoing WHERE rule=$ruleId ORDER BY priority";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $id=$arr["id"];
    $rule=$arr["rule"];
    $priority=$arr["priority"];
    $timesegment=$arr["timesegment"];
    $group=$arr["group"];
    $entity=$arr["entity"];
    $resource=$arr["resource"];
    $provider=$arr["provider"];
    $action=$arr["action"];
    if ($resource!="0") $channel=_getTrunk($resource);
    
    error_log("Rule: $id (entity: $entity, group: $group)");
    if (checkTime($timesegment)===false) continue;    
    
    //check if some rule are triggered
    //if  ( (($entityId==$entity) or (in_array($group,getGroup($entityId))) or ($group==GROUP_OF_ALL)) AND $canContinue  ) {
    if  ( (($entityId==$entity) or (in_array($group,_getGroup($entityId)) or ($entityId=="" AND $group==$entityGroup)) or ($group==GROUP_OF_ALL)) AND $canContinue  ) { 
      error_log("  TRIGGERED RULE $id!");
      switch ($entityGroup) {
        case GROUP_OF_EXTENSION:
          error_log("  This is an extension: $entityExt");
          if ($action==RULE_ALLOW) {
            error_log("  allowed");
            $techName=_extractTech($entityId);
            $channelName=$techName."/".$extension;
            error_log("  ----------------> macro stdexten|$extension|$channelName");
            //$agi->exec("macro stdexten|$extension|$channelName");
            $agi->exec("macro stdexten|$channelName");
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            error_log("  DENIED!");
            //$agi->text2wav ("You don't have the permission to call this extension");
            $agi->exec("Congestion");
            $canContinue=false;
          } 
        break;
        case GROUP_OF_PHONENUMBER:
          error_log("  This is a phone number: $entityExt");
          
          if ($channel!=$mandatoryChannel and $mandatoryChannel!="" and $resource!="0") $action=RULE_DENY;
          
          if ($action==RULE_ALLOW) {
            if ($resource!="0" and $mandatoryChannel=="") {
              $agi->set_variable("TRUNK", $channel);
              error_log("  Set Trunk to $channel");
            } else if ($mandatoryChannel!="") {
              $agi->set_variable("TRUNK", $mandatoryChannel);
              error_log("  Set Trunk to the mandatory $mandatoryChannel");
            } else error_log("  It's Allowed (Trunk: *)");
                          
            $extension=substr($extension,strlen($outgoing_prefix));
            error_log("  ----------------> macro dialout|$extension");
            //$agi->text2wav ("You are calling the number $extension");
            $agi->exec("macro dialout|$extension");
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            error_log("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        case GROUP_OF_RESOURCE:
          error_log("  This is a resource: $entityExt");
          if ($action==RULE_ALLOW) {
            error_log("  ok, it's allowed");
            $qry="SELECT * FROM cw_channel WHERE `key`=".$entityId;
            $resT=$db->Execute($qry);
            $arrT=$resT->FetchRow();
            $agi->set_variable("MANDATORYCHANNEL", $arrT["name"]);
            error_log("  Set MandatoryChannel to ".$arrT["name"]);
            $newExtension=substr($extension,strlen($entityExt));
            //$agi->exec_setlanguage("it"); 
            //$agi->text2wav ("You have set the trunk to ".$arrT["name"]);
            $agi->set_priority(1);
            $agi->set_extension($newExtension);
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            error_log("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        case GROUP_OF_APPLICATION:
          error_log("  This is an Application: $entityExt");
          if ($action==RULE_ALLOW) {
            error_log("  allowed ");
            $qry="SELECT * FROM cw_application WHERE id=".$entityId;
            $resA=$db->Execute($qry);
            $arrA=$resA->FetchRow();

            if ($arrA["code"]!="") {
              $lineArr=split("\n",$arrA["code"]);
              if (is_array($lineArr)) foreach($lineArr as $line) {
                error_log("  Executing code: $line");
                $agi->exec($line);
              }
            }
            if ($arrA["macro"]!="") {
              $arrMacro=prepareMacro($arrA["macro"],$arrA["parameter"]);
              error_log("  Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
              $agi->exec("macro ".$arrMacro[0].$arrMacro[1]);
            }
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            error_log("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        case GROUP_OF_OFFICE:
          error_log("  This is an office: $entityExt");
          error_log($channel);
          if ($action==RULE_ALLOW) {

            $qry="SELECT * FROM cw_channel WHERE `key`=".$entityId;
            $resT=$db->Execute($qry);
            $arrT=$resT->FetchRow();
            $agi->set_variable("TRUNK", $arrT["name"]);
                          
            $extension=substr($extension,strlen($outgoing_prefix));
            $destination=substr($extension,strlen($entityExt));
            if ($destination=="") $destination="s";
            error_log("  ----------------> macro dialout|$destination");
            //$agi->text2wav ("You are calling the number $extension");
            $agi->exec("macro dialout|$destination");
            $canContinue=false;
          }
          if ($action==RULE_DENY) {
            error_log("  DENIED!");
            $agi->exec("Congestion");
            $canContinue=false;
          }
        break;
        default:
          error_log("  This is an Unknown entity");
        break;
      }
    } 
      
  }
  error_log("Exit from dial.php");
    

?>
