<?
/**
 * VoiceOne Webservices Methods
 *  
 * @package voiceone_webservices
 * @subpackage operator_panel
 */
//******************************************************************************
//******************           PUBLIC FUNCTIONS            *********************
//******************************************************************************
// ---- Function op_getExtensions ----------------------------------------------
/**
* Get extensions defined on the system
*
* @return:op_extensionArray -> array of extension structures 
*/
function op_getExtensions(){
  //get Extensions
  $extensions=array();
	$ret=getClient(0,0);
  if(is_array($ret)){
  	foreach($ret as $c){
    	//check int fields
      if(trim($c["rule"])=="") $c["rule"]=0;
      if(trim($c["technology"])=="") $c["technology"]=0;
    	//get mailbox
      $mailbox="";
      if((is_array($v["voicemail"]))&&(isset($v["voicemail"]["mailbox"]))){
      	$mailbox=$v["voicemail"]["mailbox"];
      }
      //create trunk from technology
      $trunk="";
      switch($c["technology"]){
      	case SIP:
        	$trunk="SIP/".$c["extension"];
        	break;
        case IAX2:
        	$trunk="IAX2/".$c["extension"];
        	break; 
				case MISDN:
        	$trunk="mISDN/".$c["extension"];
        	break;  
				case ZAP:
        	$trunk="ZAP/".$c["extension"];
					break;
       }
    	//build extensions structure
    	$extensions[$c["id"]]=array(
      		"name" => $c["name"],
          "surname" => $c["surname"],
          "extension" => $c["extension"],
          "trunk" => $trunk,
          "voicemail" => $mailbox,
          "groups" => $c["groups"],
          "linkedClients" => array()
      	);
    }
  }
  //get Virtual Extensions
  $virtual_extensions=array();
	$ret=getVirtualExtension(0);
  if(is_array($ret)){
  	foreach($ret as $v){
    	//check int fields
      if(trim($v["rule"])=="") $v["rule"]=0;
      if(trim($v["technology"])=="") $v["technology"]=0;
    	//get descriptions of linked clients
      if(is_array($v["linked_clients"])){
      	foreach($v["linked_clients"] as $c_id){
        	$c=$extensions[$c_id];
        	$linked_clients[]=array(
          		"extension" => $c["extension"],
              "trunk" => $c["trunk"],
          	);
          unset($extensions[$c_id]);
        }
      }
      //get mailbox
      $mailbox="";
      if((is_array($v["voicemail"]))&&(isset($v["voicemail"]["mailbox"]))){
      	$mailbox=$v["voicemail"]["mailbox"];
      }
      //build extensions structure
    	$virtual_extensions[$v["id"]]=array(
      		"name" => $v["name"],
          "surname" => $v["surname"],
          "extension" => $v["extension"],
          "trunk" => "",
          "voicemail" => $mailbox,
          "groups" => $v["groups"],
          "linkedClients" => $linked_clients
      	);
    }
  }
  //merge extensions and virtual extensions
  $merged_extensions=array();
  if(is_array($extensions)){
  	foreach($extensions as $e){
    	$merged_extensions[$e["extension"]]=$e;
    }
  }
  if(is_array($virtual_extensions)){
  	foreach($virtual_extensions as $v){
    	$merged_extensions[$v["extension"]]=$v;
    }
  }
  //sort extensions
  $res=array();
  if(is_array($merged_extensions)){
  	ksort($merged_extensions,SORT_STRING);
  	foreach($merged_extensions as $e) $res[]=$e;
  }
  //return res
  return $res;
}
// ---- Function op_getQueues() ------------------------------------------------
/**
* Get queues defined on the system
*
* @return:op_queueArray -> array of queue structures 
*/
function op_getQueues(){
	//get agents
  $agents=array();
  $ret=getAgent(0);
  if(is_array($ret)){
  	$registered_agents=getRegisteredAgent();
  	foreach($ret as $a){
    	//get agent status
      $status=0;
      if((is_array($registered_agents))&&(array_search(trim($a["extension"]),$registered_agents,true)!==false)){
      	$status=1;
      }
      //build agents structure
    	$agents[$a["id"]]=array(
      		"extension" => $a["extension"],
          "status" => $status
      	);
    }
  }
	//get queues
  $queues=array();
	$ret=getQueue(0);
  if(is_array($ret)){
  	$queueInfo=getQueueInfo();
  	foreach($ret as $q){
    	//extract members
      $members=array();
      if(is_array($q["member"])){
      	foreach($q["member"] as $m){
        	$members[]=array(
          		"extension" => $agents[$m["id"]]["extension"],
              "penalty" => $m["penalty"],
              "status" => $agents[$m["id"]]["status"]
          	);
        }
      }
      //extract calls in queue
      $strategy="";
      $calls=array();
      if(is_array($queueInfo)){
      	$strategy=$queueInfo[$q["id"]]["strategy"];
      	$calls=$queueInfo[$q["id"]]["calls"];
      }
    	//build queue structure
    	$queues[]=array(
      		"name" => $q["name"],
          "strategy" => $strategy,
          "members" => $members,
          "calls" => $calls
      	);
    }
  }
  //return
  return $queues;
}
// ---- Function op_getLines() -------------------------------------------------
/**
* Get lines defined on the system
*
* @return:op_linesArray -> array of line structures 
*/
function op_getLines(){
	$channels=array();
  //retreive lines informations
	$ret=getTrunk();
  if(is_array($ret)){
  	foreach($ret as $c){
    	/***********************************/
       /**
        * TODO: implement channel call limit
        */
    	 $c["call_limit"]=4;
      /***********************************/
    	//create alias structure
      $alias=array();
      switch($c["technology"]){
      	case SIP:
        case IAX2:
        case ZAP:
        	$alias[]=$c["name"];
        	break; 
				case MISDN:
          $pg=getIsdnGroup($c["key"]);
          if((is_array($pg))&&(is_array($pg[0]))&&(is_array($pg[0]["port"]))){
          	foreach($pg[0]["port"] as $port){
            	$alias[]=trim(substr($c["name"],0,(strpos($c["name"],"/")+1)).$port);
            }
          }
          break;  
       }
      //add line structure to the return list
    	$channels[]=array(
      		"name" => $c["name"],
          "aliases" => $alias,
          "speeddial" => $c["speeddial"],
          "callLimit" => $c["call_limit"],
          "numbers" => $c["cid_list"]
      	);
    }
  }
  $res=sendCommand("show queues");
  //return
  error_log("XXX--> ".sendRequest("STATUS"));
  return $channels;
}
//******************************************************************************
//*****************           PRIVATE FUNCTIONS            *********************
//******************************************************************************
function getQueueInfo($id=0){
  $ret=array();
  //send command
  if((trim($id)!="")&&($id!=0)){ 
  	$res=sendCommand("show queue queue_".$id);
  }else{
  	$res=sendCommand("show queues");
  }
  //parse command
  if($res!=""){
  	$calls=array();
    $isCall=false;
    $lines=explode("\n",$res);
    foreach($lines as $l){
    	$l=trim($l);
    	//queue statement
      if(strpos($l,"queue_")!==false){
        $id=substr($l,strlen("queue_"),(strpos($l," ")-strlen("queue_")));
        $lArr=explode("'",$l,3);
        if(is_array($lArr)) $strategy=$lArr[1]; else $strategy="";
      }
      //start call description
      else if(strpos($l,"Callers")!==false) $isCall=true;
      //call row
      else if(($isCall===true)&&(trim($l)!="")){
      	$l=str_replace(array("(",":",")",".",",","wait ","prio "),"",$l);
        list($number,$channel,$wait,$prio)=explode(" ",$l);
        $wait=intval(substr($wait,-2))+(intval(substr($wait,0,-2))*60);
        $trunk=substr($channel,0,strpos($channel,"-"));
        list($callerid,$calleridName)=getCidFromChannel($channel);
      	$calls[]=array(
        		"number" => intval($number),
            "channel" => trim($channel),
            "trunk" => $trunk,
            "callerid" => $callerid,
            "calleridName" => $calleridName,
            "wait" => $wait,
            "priority" => intval($prio),
          );
      }
      //end of call descriptions
      else if((trim($l)=="")&&($id!="")&&($id!=0)){
      	$ret[$id]=array(
        		"strategy" => $strategy,
        		"calls" => $calls
          );
        $calls=array();
        $isCall=false;
        $id=0;
      }
    }
  }
  //return
  return $ret;
}
function getCidFromChannel($channel){
	$callerid="";
  $calleridName="";
  if(trim($channel)!=""){
  	//send command
 		$res=sendCommand("show channel ".$channel);
  	//parse response
    if($res!=""){
      $lines=explode("\n",$res);
      foreach($lines as $l){
      	$l=trim($l);
        if(strpos($l,"Caller ID: ")!==false){
        	$callerid=substr($l,strlen("Caller ID: "));
          if($calleridName!="") break;
        }
        if(strpos($l,"Caller ID Name: ")!==false){
        	$calleridName=substr($l,strlen("Caller ID Name: "));
          if($callerid!="") break;
        }
      }
  	}
  }
  return array($callerid,$calleridName); 
}
/*
function getChannelInfo(){
	$active_channels=0;
  $active_calls=0;
	$channels=array();
  //send command
 	$res=sendCommand("show channels");
  //parse response
  if($res!=""){
    $isCall=false;
    $lines=explode("\n",$res);
    foreach($lines as $l){
    	$l=trim($l);
      //start channels description
      if(strpos($l,"Channel")!==false) $isChannel=true;
      //end channels description
      else if(is_numeric(substr($l,0,1))){
      	$isChannel=false;
        if(strpos($l,"active channels")!==false) $active_channels=intval($l);
        if(strpos($l,"active calls")!==false) $active_calls=intval($l);
      }
      //channels row 
      else if(($isChannel===true)&&(trim($l)!="")){
        list($name,$location,$state,$application)=preg_split("/[\s]+/",$l,4);
        $tech=trim(substr($name,0,strpos($name,"/")));
        if(($tech!="")&&(!in_array($tech,array("Local","Agent"))){
        	$trunk=substr($name,0,strpos($name,"-"));
          list($callerid,$calleridName)=getCidFromChannel($name);
          $channels[]=array(
          		"name" => $name,
              "trunk" => $trunk,
              "callerid" => $callerid,
            	"calleridName" => $calleridName,
              "state" => $state 
          	);
  		}
    }
  }
  //return
  $ret=array( 
      "channels" => $channels
  	);
  return $ret;
}
*/
?>