<?
/*********************** INCLUDES *********************************************/
  $includePath=realpath(dirname(__FILE__)."/../");
  require_once ($includePath.'/config/cfg.php');
  require_once ($includePath.'/lib/phpagi/phpagi.php');
/*********************** INITIALIZATION ***************************************/
  $agi = new AGI();
  // Get AGI parameters
  // check if $_GET array is available. If not use $_SERVER
  if((is_array($_GET))&&(count($_GET)>0)){
    if(isset($_GET["rule"])) $triggeredRuleId=$_GET["rule"]; else $triggeredRuleId=0;
    if(isset($_GET["entity"])) $triggeredEntityId=$_GET["entity"]; else $triggeredEntityId=0;
    if(isset($_GET["answered"])) $triggeredAnswered=$_GET["answered"]; else $triggeredAnswered=0;
    if(isset($_GET["channel"])) $triggeredChannelId=$_GET["channel"]; else $triggeredChannelId=0;
  }else{
    // (GET array may be null in many cases, parseArgv take $_SERVER content)
    parse_str($_SERVER["argv"][1], $var_GET);
    if(isset($var_GET["rule"])) $triggeredRuleId=$var_GET["rule"]; else $triggeredRuleId=0;
    if(isset($var_GET["entity"])) $triggeredEntityId=$var_GET["entity"]; else $triggeredEntityId=0;
    if(isset($var_GET["answered"])) $triggeredAnswered=$var_GET["answered"]; else $triggeredAnswered=0;
    if(isset($var_GET["channel"])) $triggeredChannelId=$var_GET["channel"]; else $triggeredChannelId=0;
  }
  // Extract caller Id
  $triggeredCallerid=$agi->get_variable("CALLERID(num)");
  $triggeredCallerid=$triggeredCallerid["data"];
  $cidOnChannel=$triggeredCallerid;
  preg_match("/(?:\"(.*)\"|(\s*))\s*(?:\<(.*)\>|(.*))/", $triggeredCallerid, $matches);
  $triggeredCallername = $matches[1];
  if ($matches[3]) $triggeredCallerid = $matches[3];
  else if ($matches[4]) $triggeredCallerid = $matches[4];
  // If callerid is empty or contains characters that are not alphanumeric (channel error) set triggeredCallerid to Anonymous
  if(trim($triggeredCallerid)==""){
    $triggeredCallerid = "ANONYMOUS";
  }else{
    for($i=0;$i<strlen($triggeredCallerid);$i++){
    	$ch=ord($triggeredCallerid[$i]);
    	if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
    	  $triggeredCallerid = "ANONYMOUS";
    	  break;
    	}
    }
  }
  // Clean and set cid number on channel to the cid name value (PORTECH BUG WORKAROUND)
  //if(strstr($triggeredCallerid,'sim')){
  //  $triggeredCallername=$agi->get_variable("CALLERID(name)");
  //  $triggeredCallername=$triggeredCallername["data"];
  //  $triggeredCallerid=$triggeredCallername;
  //  $agi->set_variable("CALLERID(name)","");
  //}
  // Extract Channel
  $triggeredChannel=$agi->get_variable("CHANNEL");
  $triggeredChannel=$triggeredChannel["data"];
/*********************** PAGE LOGIC ********************************************/
	agiError("-----------------------------------------------");
  agiError("Incoming Rule Set: [$triggeredRuleId] (callerid: $triggeredCallerid [on channel $cidOnChannel])");
  agiError("-----------------------------------------------");
  //Extract call type and called number
  $callInfo=_getCallInfo($triggeredChannel);
  switch($callInfo["channelTech"]){
    case SIP:
      // retrieve provider information
      if(($triggeredChannelId!=0)&&($callInfo["calledNumber"]!="")){
        $accountInfo=_getCalledAccount($triggeredChannelId,$callInfo["calledNumber"]);
        if(is_array($accountInfo)){
          agiError("   ACCOUNT: [".$accountInfo["id"]."] ".$accountInfo["name"]." on ch.".$accountInfo["channel"]." (".$accountInfo["msns"].")");
          agiError("   RULESET: [".$accountInfo["rule"]."] matching context \"".$triggeredAnswered."\"");
          //set correct incoming channel
          $triggeredChannelId=$accountInfo["channel"];
          $triggeredEntityId="";
          $triggeredRuleId=$accountInfo["rule"];
        }else agiError("   ACCOUNT: UNDEFINED INCOMIG NUMBER (".$callInfo["calledNumber"].")");
      }else agiError("   ACCOUNT: UNABLE TO RETRIEVE INFORMATION (called number is null)");
    break;
    default:
      agiError("ANSWERED: ".$triggeredAnswered." on channel ".$triggeredChannel);
    break;
  }
  //Clean international prefix depending on channel location
  $triggeredCallerid=_cleanCidNumber($triggeredCallerid,$triggeredChannelId);
  agiError("   CLEANED CID NUMBER: ".$triggeredCallerid);
  $agi->set_variable("CALLERID(num)",$triggeredCallerid);
  //Verify if there is a jump for incoming ruleset
  $jump_target=_verifyJump($triggeredRuleId);
  if((is_array($jump_target))&&($jump_target["id"]!=0)){
    agiError("RULESET JUMP: FROM [".$triggeredRuleId."] TO [".$jump_target["id"]."]".$jump_target["name"]." (active until ".$jump_target["until"].")");
    $triggeredRuleId=$jump_target["id"];
  }
  //Process incoming call
  agiError("[ RULES ]");
  $canContinue=true;
  $qry="SELECT * FROM cw_rule_incoming WHERE rule=$triggeredRuleId ORDER BY priority";
  $res=$db->Execute($qry);
  while ($arr=$res->FetchRow()) {
    $id=$arr["id"];
    $rule=$arr["rule"];
    $priority=$arr["priority"];
    $timesegment=$arr["timesegment"];
    $callertype=$arr["callertype"];
    $callerid=$arr["callerid"];
    $channel=$arr["from_channel"];
    $number=$arr["from_number"];
    $numberArr=explode("|",$number);
    $macro=$arr["macro"];
    $parameter=$arr["parameter"];
    $duration=$arr["duration"];
    agiError("Rule: $id (Type:$callertype, callerid: $callerid, channel: $channel)");
    //fetch the entity type
    if ($triggeredEntityId!="") {
      $qry="SELECT * FROM cw_channel WHERE `key`=$triggeredEntityId";
      $resT=$db->Execute($qry);
      $t=$resT->FetchRow();
      $channelId=$t["id"];
    } else $channelId=$triggeredChannelId;
    //check rule
    if  (
          (
            //(now we are in the rule's timesegment)
            (checkTime($timesegment)===true)
          )
          AND
          (
            //(rule match callerid)
            (_isCallerIncluded($callerid,$callertype,$triggeredCallerid)===true)
          )
          AND
          (
            //(rule match all numbers)
            ($number=="") OR
            //(rule match some number) and (one of them is the triggered one)
            ($number!="" AND in_array($triggeredAnswered,$numberArr,true)) OR
            //(rule match some number) and (one of them is the called number) --> SIP Provider
            ($number!="" AND in_array($callInfo["calledNumber"],$numberArr)) OR
            // ??????????? some numbers are dialed and a catch all matched ????????????
            (in_array("X",$numberArr) AND $triggeredAnswered!="s" )
          )
          AND
          (
            //(rule match all channels) or ((rule match a channel) and (it is the triggered one))
            (($channel==0) OR ($channel!=0 AND $channel==$channelId))
          )
          AND
          (
            //no rules has been triggered before
            ($canContinue===true)
          )
        )
    {
      agiError("  TRIGGERED RULE $id!");
      //set cid name on channel
      $cidName=_getCallerCidName($triggeredCallerid);
			if($cidName==""){
      	agiError("  CID NAME: No match in contacts list");
      }else{
      	agiError("  CID NAME: ".$cidName);
        $agi->set_variable("CALLERID(name)",$cidName);
      }
      // execute macro
      $arrMacro=prepareMacro($macro,$parameter);
      agiError("  Executing macro ".$arrMacro[0].$arrMacro[1]." ...");
      $agi->exec("macro ".$arrMacro[0].$arrMacro[1], '');
      /**
       * CALL FINDER
       *
      $incomingcallidArr=$agi->get_variable("UNIQUEID");
      $incomingcallid=$incomingcallidArr["data"];
      $qry="INSERT INTO `incomingcall` ( `id` , `caller_number` ) ";
      $qry.="VALUES ('".$incomingcallid."','".$triggeredCallerid."'); ";
      $resT=$db->Execute($qry);
       */
      // set canContinue
      if ($duration=="1") $canContinue=true; else $canContinue=false;
    }
  }
  agiError("Exit from incoming.php");

?>