#!/usr/bin/php -q
<?php
/*
This Callback script takes 3 arguments:
1- number to dial
2- context.exten.priority to dump number into
3- time in seconds to sleep before calling back

eg: callback 14032448089 ext-meetme.200.1
*/

//Copyright (C) 2004 Coalescent Systems Inc. (info@coalescentsystems.ca)
//Modified by John Fawcett john@gufonero.com to use call files
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
?>

<?php
define("AMP_CONF", "/etc/amportal.conf");
ob_implicit_flush(true);

/**************************************************************/

// from  ben-php dot net at efros dot com   at  php.net/install.unix.commandline
if (version_compare(phpversion(),'4.3.0','<') || !defined("STDIN")) {
	define('STDIN',fopen("php://stdin","r"));
	define('STDOUT',fopen("php://stdout","r"));
	define('STDERR',fopen("php://stderr","r"));
	register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
}

// **** Make sure we have PEAR's GetOpts.php, and include it

outn("Checking for PEAR Console::Getopt..");
if (! @ include("Console/Getopt.php")) {
	out("FAILED");
	fatal("PEAR must be installed (requires Console/Getopt.php). Include path: ".ini_get("include_path"));
}
out("OK");


outn("Reading ".AMP_CONF."..");
$amp_conf = parse_amportal_conf(AMP_CONF);
if (count($amp_conf) == 0) {
	fatal("FAILED");
}
out("OK");

// include manager functions
include $amp_conf['AMPWEBROOT'].'/admin/common/php-asmanager.php';

// **** Parse out command-line args
out("Getting passed arguments:");
$con  = new Console_Getopt;
$args = $con->readPHPArgv();
array_shift($args);

$callback_number = $args[0];
$callback_destination = $args[1];
$pause_seconds = $args[2];

// figure out context, exten, priority
$dest = explode(".",$callback_destination);
$callback_context = $dest[0];
$callback_exten = $dest[1];
$callback_priority = $dest[2];

$callback_prefix = isset($amp_conf['CALLBACK_PREFIX']) ? $amp_conf['CALLBACK_PREFIX'] : '';
$callback_cli = isset($amp_conf['CALLBACK_CLI']) ? $amp_conf['CALLBACK_CLI'] : 'Callback';
$callback_retry = isset($amp_conf['CALLBACK_RETRY']) ? $amp_conf['CALLBACK_RETRY'] : 2;
$callback_interval = isset($amp_conf['CALLBACK_INTERVAL']) ? $amp_conf['CALLBACK_INTERVAL'] : 15;
$callback_wait = isset($amp_conf['CALLBACK_WAIT']) ? $amp_conf['CALLBACK_WAIT'] : 20;
$callback_archive = isset($amp_conf['CALLBACK_ARCHIVE']) ? $amp_conf['CALLBACK_ARCHIVE'] : 'No';
$callback_api_timeout = isset($amp_conf['CALLBACK_API_TIMEOUT']) ? $amp_conf['CALLBACK_API_TIMEOUT'] : 30000;
$ast_spool = isset($amp_conf['ASTSPOOLDIR']) ? $amp_conf['ASTSPOOLDIR'] : '/var/spool/asterisk';
$callback_method = isset($amp_conf['CALLBACK_METHOD']) ? $amp_conf['CALLBACK_METHOD'] : 'file';
$callback_allowed = isset($amp_conf['CALLBACK_ALLOWED']) ? $amp_conf['CALLBACK_ALLOWED'] : '';

//if callbackcl_allowed defined, check if callback_number is in allowed list
if ($callback_allowed <>'')
{
	$allowed = explode(",",$callback_allowed);
	$found=0;
	foreach ($allowed as $a)
	{
		if (strpos($callback_number,$a)!==FALSE)
		{
			$found=1;
			break;
		}
	}
	if ($found==0)
	{
		out("callback to $callback_number not allowed");
		exit;
	}
}

//define the args for callback
$channel = "Local/".$callback_prefix.$callback_number."@from-internal";
//$channel = "zap/g0/".$uservm[$vmcontext][$vmextension]['options']['callme'];
$exten = $callback_exten;
$context = $callback_context;
$priority = $callback_priority;
$callerid = $callback_cli;
$retry = $callback_retry;
$retry_time = $callback_interval;
$wait_time = $callback_wait;
$variable = "";
$account = "";
$application = "";
$data = "";
$archive = $callback_archive;
$timeout = $callback_api_timeout;

if ($callback_method=='api')
{
	//connect to manager and dial
	$astman = new AGI_AsteriskManager();
	if ($res = $astman->connect("127.0.0.1", $amp_conf["AMPMGRUSER"] , $amp_conf["AMPMGRPASS"])) {
	        $res = $astman->Originate($channel, $exten, $context, $priority, $timeout, $callerid, $variable, $account, $application, $data);
		if($res['Response']<>"Success")
			out("api result: ".$res['Response']." => ".$res['Message']);
	} else {
	        fatal("Cannot connect to Asterisk Manager with ".$amp_conf["AMPMGRUSER"]."/".$amp_conf["AMPMGRPASS"]);
	}
	$astman->disconnect();
}
else
{
	//use callback number for call file name, remove any spaces
	$callfilename='cb-'.time().'-'.str_replace(' ','',$callback_number);
	$callfile = '/tmp/'.$callfilename;
	$callfile_dest = $ast_spool.'/outgoing/'.$callfilename;

	//open call file
	$cf = fopen($callfile,'w+');
	if (!$cf)
	{
		fatal("Cannot open file ".$callfile);
	}
	//output file
	fputs($cf,"Channel: $channel\n");
	fputs($cf,"Context: $context\n");
	fputs($cf,"Extension: $exten\n");
	fputs($cf,"Priority: $priority\n");
	fputs($cf,"MaxRetries: $retry\n");
	fputs($cf,"RetryTime: $retry_time\n");
	fputs($cf,"WaitTime: $wait_time\n");
	fputs($cf,"CallerID: $callerid\n");
	fputs($cf,"Archive: $archive\n");
	fclose($cf);
	out("call file written ".$callfile);
	//modify time
	if(!touch($callfile,time()+$pause_seconds)) 
		error("cannot modify time of callfile ".$callfile);
	//move to asterisk outgoing dir
	if(!rename($callfile,$callfile_dest))
		error("cannot move callfile ".$callfile." to asterisk outgoing directory ".$callfile_dest);
}
exit;

function parse_amportal_conf($filename) {
	$file = file($filename);
	foreach ($file as $line) {
		if (preg_match("/^\s*([a-zA-Z0-9_]+)\s*=\s*(.*)\s*([;#].*)?/",$line,$matches)) { 
			$conf[ $matches[1] ] = $matches[2];
		}
	}
	return $conf;
}

function out($text) {
	echo $text."\n";
}

function outn($text) {
	echo $text;
}

function error($text) {
	echo "[ERROR] ".$text."\n";
}

function fatal($text) {
	echo "[FATAL] ".$text."\n";
	exit(1);
}

?>
