#!/usr/bin/php -q
<?php
$server = "127.0.0.1";
$amiuser = "agi";
$amipass = "123";
$hintcontext = "default";
// toggle debugging output (more verbose but slower)
$debug = true;
$logfile = "/var/log/asterisk/PHP_AGI.log";
##############################
ob_implicit_flush(true);
set_time_limit(10);
error_reporting(0);
$in = fopen("php://stdin","r");
// Do function definitions before we start the main loop
if ($debug==true) $stdlog = fopen($logfile, "w");
function read() {
global $in, $debug, $stdlog;
$input = str_replace("\n", "", fgets($in, 4096));
if ($debug) fputs($stdlog, "read: $input\n");
return $input;
}
function errlog($line) {
global $debug, $err, $stdlog;
if ($debug) fputs($stdlog, "errlog: $line\n");
# echo "VERBOSE \"$line\"\n";
}
function write($line) {
global $debug, $stdlog;
if ($debug) fputs($stdlog, "write: $line\n");
echo $line."\n";
}
// parse agi headers into array
while ($env=read()) {
$s = split(": ",$env);
$agi[str_replace("agi_","",$s[0])] = trim($s[1]);
if (($env == "") || ($env == "\n")) {
break;
}
}
##############################
// main program
if ($socket = fsockopen($server, 5038)) {
stream_set_timeout($socket, 0, 300000);
}
function ami($command) {
global $socket;
fwrite ($socket, $command);
$response = stream_get_contents($socket);
if ($response == false) return "Fehlen beim lesen der Serverantwort.";
else return $response;
}
$amiresult = ami("Action: Login\r\nUserName: $amiuser\r\nSecret: $amipass\r\n\r\n");
errlog ("AMI Login: " . $amiresult);
$extstatus="other";
$amiresult = ami("Action: ExtensionState\r\nContext: $hintcontext\r\nExten: " . $agi['extension'] . "\r\n\r\n");
errlog ("AMI ExtensionState: " . $amiresult);
$amiarray = split("\r\n",$amiresult);
foreach ($amiarray AS $amival) {
errlog ("Array - " . $amival);
if(substr($amival,0,7)=="Status:") $extstatus.=" (".substr($amival,7).")";
if( (trim($amival)=="Status: 0") || (trim($amival)=="Status:0") ) $extstatus="idle";
}
$amiresult = ami("Action: Logoff\r\n\r\n");
errlog ("AMI Logoff: " . $amiresult);
fclose($socket);
write ('SET VARIABLE extstatus "' .$extstatus . '"');
read ();
##############################
// clean up file handlers etc.
fclose($in);
fclose($stdlog);
exit;
?>