<?php


/**
 * Dialer class definition
 *
 * @author     JYG
 * @version    CVS:
 */

class Dialer
{
    protected $dialer='/usr/sbin/dialer';
    protected $campaign='default';
    protected $dialerpid;
    public $status;
    public $progress;
    public $attempts;
    public $todo;
    public $count;
    public $config;
    public $maxlines;

    // Constructor
    public function Dialer()
    {
        $this->config = $this->readDialerConf();

        @$this->dialerpid= file_get_contents('/tmp/dialer.lock');
        //status
        exec("/bin/ps ".$this->dialerpid,$t,$result);
        if($result==0 && $this->dialerpid ){
            $this->status='running';
        }
        else
            $this->status='stopped';


        //Read stats
        exec($this->dialer.' -a statistics -c '.$this->campaign,$brutstats,$statret);
        //var_dump($brutstats);
        if (isset($brutstats))
        foreach($brutstats as $line){
            $tmp=explode(':',$line);
            if (isset($tmp[1]))
            $stats[trim($tmp[0])]=trim($tmp[1]);
        }
        $this->progress= @round(($stats['Attempts']/$stats['Count'])*100);
        $this->attempts=$stats['Attempts'];
        $this->todo=$stats['Todo'];
        $this->count=$stats['Count'];

    }

    public function readDialerConf(){
        $params=array();
        foreach( explode("\n",file_get_contents('/etc/dialer.conf')) as $value ) {
            switch(substr($value,0,1))
            {
            case ';':
            case '':
                break;
            case '[':
                $section=trim(str_replace(array('[',']'),'',$value));
                break;
            default:
                $equal=strpos($value,'=');
                $params[$section][trim(substr($value,0,$equal))]=trim(substr($value,$equal+1));
            }
        }
        return $params;
    }


/*    function readConfig() {
        if (file_exists($file)) {
        	$fr = fopen($file,'r');
            if (!is_resource($fr))
                return;

            $sectionFound=false;
        	while(!feof($fr)) {
        		$line = fgets($fr);
        		$line = ltrim(trim($line));

                if (strpos($line,"[default]") !== false) {
                    $sectionFound = true;
                    continue;
                }
                if ($sectionFound) {
                    if (strpos($line,"maxlines") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->maxlines    = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"retries") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->retries     = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"timeout") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->timeout     = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"mode") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->mode        = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"callerid") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->callerid    = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"dialformat") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->dialformat  = ltrim(trim($explodeLine[1]));
                    }
                    else if (strpos($line,"attempts") !== false) {
                        $explodeLine = preg_split('/=/', $line);
                        $this->attempts  = ltrim(trim($explodeLine[1]));
                    }
                }
            }
            fclose($fr);
        }
    }
*/
    function loadFile($filename) {

        error_log('Dialer:exec: PATH=$PATH:/usr/bin '.$this->dialer.' --stop');
        $ret = exec('PATH=$PATH:/usr/bin '.$this->dialer.' --stop');
        $ret .= "<br>";

        error_log('Dialer:exec: '.$this->dialer.' -a drop '.$this->campaign);
        $ret .= exec($this->dialer.' -a drop '.$this->campaign);
        $ret .= "<br>";

        error_log('Dialer:exec: '.$this->dialer.' -a create '.$this->campaign);
        $ret .= exec($this->dialer.' -a create '.$this->campaign);
        $ret .= "<br>";

        error_log('Dialer:exec: '.$this->dialer.' -a file -c '.$this->campaign.' -p '.$filename);
        $ret .=  exec($this->dialer.' -a file -c '.$this->campaign.' -p '.$filename);
        $ret .= "<br>";
        return $ret;
    }

    function start() {
        error_log('Dialer:exec: PATH=$PATH:/usr/bin /usr/bin/nohup '.$this->dialer.' --start  >/dev/null &');
        $ret = exec('PATH=$PATH:/usr/bin /usr/bin/nohup '.$this->dialer.' --start  >/dev/null &');
        error_log('Dialer:exec: Start passed');
        sleep(1);
        return $ret;
    }

    function stop() {
        error_log('Dialer:exec: PATH=$PATH:/usr/bin /usr/bin/nohup '.$this->dialer.' --stop  >/dev/null &');
        $ret = exec('PATH=$PATH:/usr/bin /usr/bin/nohup '.$this->dialer.' --stop  >/dev/null &');
        error_log('Dialer:exec: Stop passed');
        sleep(1);
        return $ret;
    }

    function getLogs() {
        $nicedate=date("Ymd-Hi");

        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"".$this->campaign."-".$nicedate.".csv\"");
        //$ret = exec($this->dialer.' -a fulldump -c '.$this->campaign);
        //echo $ret;
        //error_log($ret);
        passthru($this->dialer.' -a fulldump -c '.$this->campaign);
        exit;
    }
    
	  function ajaxHandler() {

		switch ($_REQUEST['command']) {
  		case "deletemessage":
  			\FreePBX::create()->Notifications->safe_delete($_REQUEST['raw'], $_REQUEST['id']);
  			return array("status" => true);
  			break;
  		case "resetmessage":
  			\FreePBX::create()->Notifications->reset($_REQUEST['raw'], $_REQUEST['id']);
  			return array("status" => true);
  			break;
  		default:
        
  			return array("status" => true);      
  			break;
  	}
	}    
}
?>