Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 661

Přidáno uživatelem Roman Ševčík před asi 14 roky(ů)

Přídány třídy k připojení k Asterisku přes asterisk manager. Přidána možnost callbacku.

Zobrazit rozdíly:

freenetis/trunk/kohana/application/helpers/form.php
{
if (empty($attr))
return '';
//napovedu odstranime - nechceme ji renderovat v inputu...
unset($attr['help']);
if ( ! empty($attr['name']) AND strpos($attr['name'], '[') === FALSE AND empty($attr['id']))
{
freenetis/trunk/kohana/application/controllers/web_interface.php
*/
class Web_interface_Controller extends Controller
{
protected $db;
function __construct()
{
$this->db = new Database();
......
{
}
function callback($user = null, $pass = null, $number = null)
{
if ($user == null || $pass == null || $number == null)
{
echo 'No input data';
exit;
}
if (!valid::digit($user) || !valid::digit($number))
{
echo 'Not valid input data';
exit;
}
$voip = $this->db->query('
SELECT DISTINCT name, secret
FROM voip_sips
WHERE name = '.$user
);
if (count($voip) == 0 || $voip->current()->secret != $pass)
{
echo 'Bad user or password';
exit;
}
else
{
$this->settings = new Settings();
$asm = new AsteriskManager();
$ahostname = $this->settings->get('voip_asterisk_hostname');
$auser = $this->settings->get('voip_asterisk_user');
$apass = $this->settings->get('voip_asterisk_pass');
if ($ahostname == null || $ahostname == '' || $auser == null || $auser == '' || $apass == null || $apass == '')
{
echo 'Error. Check freenetis settings.';
exit;
}
if($asm->connect($ahostname, $auser, $apass))
{
//http://www.voip-info.org/wiki/index.php?page=Asterisk+Manager+API+Action+Originate
$call = $asm->Originate('SIP/'.$user,
$number,
'internal',
1,
$application=NULL,
$data=NULL,
30000,
$user,
$variable=NULL,
$account=NULL,
$async=NULL,
$actionid=NULL);
$asm->disconnect();
echo 'Success';
}
else
{
echo 'Error. Could not connect to server.';
}
}
}
}
?>
freenetis/trunk/kohana/application/controllers/settings.php
// page title
$this->form->input('voip_number_interval')->label(url_lang::lang('texts.Number interval').':')->rules('length[19,19]|required')->value(addslashes($this->settings->get('voip_number_interval')))->callback(array($this,'valid_voip_number_interval'));
$this->form->input('voip_number_exclude')->label(url_lang::lang('texts.Exclude numbers').':')->rules('length[9,100]')->value(addslashes($this->settings->get('voip_number_exclude')))->callback(array($this,'valid_voip_number_exclude'));
$this->form->input('voip_sip_server')->label(url_lang::lang('texts.SIP server').':')->rules('length[1,30]|required')->value(addslashes($this->settings->get('voip_sip_server')));
$this->form->input('voip_sip_server')->label(url_lang::lang('texts.SIP server').':')->rules('length[1,30]|required')->value(addslashes($this->settings->get('voip_sip_server')));
$this->form->group('')->label(url_lang::lang('texts.Asterisk manager settings'));
$this->form->input('voip_asterisk_hostname')->label(url_lang::lang('texts.Hostname').':')->rules('length[1,50]')->value($this->settings->get('voip_asterisk_hostname'));
$this->form->input('voip_asterisk_user')->label(url_lang::lang('texts.User').':')->rules('length[1,50]')->value($this->settings->get('voip_asterisk_user'));
$this->form->input('voip_asterisk_pass')->label(url_lang::lang('texts.Password').':')->rules('length[1,50]')->value($this->settings->get('voip_asterisk_pass'));
$this->form->group('')->label(url_lang::lang('texts.Billing settings'));
$this->form->dropdown('voip_billing_driver')->label(url_lang::lang('texts.Driver').':')->rules('required')->options(array("inactive" => url_lang::lang('texts.Inactive'),"lbilling" => "lBilling - NFX"))->selected($this->settings->get('voip_billing_driver'));
$this->form->input('voip_billing_partner')->label(url_lang::lang('texts.Partner').':')->rules('length[1,50]')->value($this->settings->get('voip_billing_partner'));
$this->form->input('voip_billing_password')->label(url_lang::lang('texts.Password').':')->rules('length[1,50]')->value($this->settings->get('voip_billing_password'));
$this->form->submit('submit')->value(url_lang::lang('texts.Save'));
special::required_forge_style($this->form, ' *', 'required');
......
if (!empty($message))
$view->content->message = $message;
$hostname = $this->settings->get('voip_asterisk_hostname');
$user = $this->settings->get('voip_asterisk_user');
$pass = $this->settings->get('voip_asterisk_pass');
/*if ($hostname != null && $hostname != '' || $user != null && $user != '' || $pass != null && $pass != '')
{
$asm = new AsteriskManager();
if($asm->connect($hostname, $user, $pass))
{
$aditional_info[] = url_lang::lang('texts.Testing driver').' : Asterisk.....<span style="color:green">OK</span>';
}
else
{
$aditional_info[] = url_lang::lang('texts.Testing driver').' : Asterisk......<span style="color:red">'.url_lang::lang('texts.Failed').'</span>';
}
$asm->disconnect();
}*/
$billing = new Billing();
if ($billing->has_driver())
{
if($billing->test_conn())
{
$view->content->aditional_info = url_lang::lang('texts.Testing driver').' : lBilling - NFX......<span style="color:green">OK</span>';
$aditional_info[] = url_lang::lang('texts.Testing driver').' : lBilling - NFX......<span style="color:green">OK</span>';
}
else
{
$view->content->aditional_info = url_lang::lang('texts.Testing driver').' : lBilling - NFX......<span style="color:red">'.url_lang::lang('texts.Failed').'</span>';
$aditional_info[] = url_lang::lang('texts.Testing driver').' : lBilling - NFX......<span style="color:red">'.url_lang::lang('texts.Failed').'</span>';
}
}
$view->content->aditional_info = $aditional_info;
$view->render(TRUE);
}
freenetis/trunk/kohana/application/controllers/voip.php
$b_account = $billing->get_account($user->member_id);
$array[] = html::anchor(url_lang::base().'users/show/'.$voip->user_id, url_lang::lang('texts.Back to the user'));
$array[] = html::anchor(url_lang::base().'voip/edit_account/'.$voip->user_id, url_lang::lang('texts.Edit account'));
$array[] = html::anchor(url_lang::base().'voip/edit_voicemail/'.$voip->user_id, url_lang::lang('texts.Edit voicemail'));
if ($has_driver && ($b_account != null))
......
}
}
function change_voicemail_password($user_id = NULL)
function edit_account($user_id = NULL)
{
if (!isset($user_id))
Controller::warning(1);
$voip = ORM::factory('voip_sip')->find_by_user_id($user_id);
if (count($voip) == 0)
Controller::error(RECORD);
$this->user_id = $user_id;
$form = new Forge(url_lang::base()."voip/edit_account/".$user_id, '', 'POST', array('id' => 'article_form'));
$form->set_attr('class', 'form_class')->set_attr('method', 'post');
$form->group('')->label(url_lang::lang('texts.Maximum length of ring'));
$form->dropdown('status')->label(url_lang::lang('texts.Number of seconds').':')->options(array('10'=> '10','30'=> '30','60'=> '60','120'=> '120'))->selected('1');
$form->group('')->label(url_lang::lang('texts.Redirection'));
$form->password('password')->label(url_lang::lang('texts.New password').':')->rules('required|length[6,20]');
$form->password('confirm_password')->label(url_lang::lang('texts.Confirm new password').':')->rules('required|length[6,20]')->matches($form->password);
$form->submit('submit')->value(url_lang::lang('texts.Change'));
if($form->validate())
{
$form_data = $form->as_array();
$voip_sip = new Voip_sip_Model();
$voip = $voip_sip->find_by_user_id($user_id);
$user = ORM::factory('user')->where('id', $user_id)->find();
$username = text::cs_utf2ascii($user->name.' '.$user->surname);
$voip->callerid = $username.' <'.$voip->name.'>';
$voip->secret = $form_data['password'];
if ($voip->save())
{
$this->session->set_flash('message', url_lang::lang('texts.Password has been successfully changed.'));
}
else
{
$this->session->set_flash('message', url_lang::lang('texts.Error - cant change password.'));
}
url::redirect(url_lang::base().'voip/change_password/'.$user_id);
}
else
{
$view = new View('main');
$view->title = url_lang::lang('texts.Change password');
$view->content = new View('voip/change_password');
$view->content->form = $form->html();
$view->content->account = $voip->name;
$view->content->user_id = $user_id;
$view->content->message = $this->session->get_once('message');
$view->render(TRUE);
}
}
function change_voicemail_password($user_id = NULL)
{
if (!isset($user_id))
Controller::warning(1);
......
$form = new Forge(url_lang::base()."voip/edit_voicemail/".$user_id, '', 'POST', array('id' => 'article_form'));
$form->set_attr('class', 'form_class')->set_attr('method', 'post');
$form->dropdown('status')->label(url_lang::lang('texts.State'), help::show('voip'))->options(array('0'=> url_lang::lang('texts.Inactive'), '1'=> url_lang::lang('texts.Active')))->selected($voicemail->active)->help(help::show('voip_voicemail'));
$form->dropdown('status')->label(url_lang::lang('texts.State'))->options(array('0'=> url_lang::lang('texts.Inactive'), '1'=> url_lang::lang('texts.Active')))->selected($voicemail->active)->help(help::show('voip_voicemail'));
$form->input('email')->label(url_lang::lang('texts.email').':')->rules('length[6,50]|valid_email')->value($voicemail->email);
$form->submit('submit')->value(url_lang::lang('texts.Edit'));
......
function edit_member_type($member_id = NULL)
{
exit;
if (!isset($member_id))
Controller::warning(PARAMETER);
......
{
$form_data = $form->as_array();
$member->voip_billing_type = $form_data['type'];
$member->voip_billing_type = $form_data['type'];
if ($member->save())
{
freenetis/trunk/kohana/application/libraries/AsteriskManager.php
<?php
/**
* phpagi-asmanager.php : PHP Asterisk Manager functions
* Website: http://phpagi.sourceforge.net
*
* $Id: phpagi-asmanager.php,v 1.10 2005/05/25 18:43:48 pinhole Exp $
*
* Copyright (c) 2004, 2005 Matthew Asham <matthewa@bcwireless.net>, David Eder <david@eder.us>
* All Rights Reserved.
*
* This software is released under the terms of the GNU Lesser General Public License v2.1
* A copy of which is available from http://www.gnu.org/copyleft/lesser.html
*
* We would be happy to list your phpagi based application on the phpagi
* website. Drop me an Email if you'd like us to list your program.
*
* @package phpAGI
* @version 2.0
*/
/**
* Written for PHP 4.3.4, should work with older PHP 4.x versions.
* Please submit bug reports, patches, etc to http://sourceforge.net/projects/phpagi/
* Gracias. :)
*
*/
if(!class_exists('AGI'))
{
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'phpagi.php');
}
/**
* Asterisk Manager class
*
* @link http://www.voip-info.org/wiki-Asterisk+config+manager.conf
* @link http://www.voip-info.org/wiki-Asterisk+manager+API
* @example examples/sip_show_peer.php Get information about a sip peer
* @package phpAGI
*/
class AsteriskManager
{
/**
* Config variables
*
* @var array
* @access public
*/
var $config;
/**
* Socket
*
* @access public
*/
var $socket = NULL;
/**
* Server we are connected to
*
* @access public
* @var string
*/
var $server;
/**
* Port on the server we are connected to
*
* @access public
* @var integer
*/
var $port;
/**
* Parent AGI
*
* @access private
* @var AGI
*/
var $pagi;
/**
* Event Handlers
*
* @access private
* @var array
*/
var $event_handlers;
/**
* Constructor
*
* @param string $config is the name of the config file to parse or a parent agi from which to read the config
* @param array $optconfig is an array of configuration vars and vals, stuffed into $this->config['asmanager']
*/
function AsteriskManager($config=NULL, $optconfig=array())
{
// load config
if(!is_null($config) && file_exists($config))
$this->config = parse_ini_file($config, true);
elseif(file_exists(DEFAULT_PHPAGI_CONFIG))
$this->config = parse_ini_file(DEFAULT_PHPAGI_CONFIG, true);
// If optconfig is specified, stuff vals and vars into 'asmanager' config array.
foreach($optconfig as $var=>$val)
$this->config['asmanager'][$var] = $val;
// add default values to config for uninitialized values
if(!isset($this->config['asmanager']['server'])) $this->config['asmanager']['server'] = 'localhost';
if(!isset($this->config['asmanager']['port'])) $this->config['asmanager']['port'] = 5038;
if(!isset($this->config['asmanager']['username'])) $this->config['asmanager']['username'] = 'phpagi';
if(!isset($this->config['asmanager']['secret'])) $this->config['asmanager']['secret'] = 'phpagi';
}
/**
* Send a request
*
* @param string $action
* @param array $parameters
* @return array of parameters
*/
function send_request($action, $parameters=array())
{
$req = "Action: $action\r\n";
foreach($parameters as $var=>$val)
$req .= "$var: $val\r\n";
$req .= "\r\n";
fwrite($this->socket, $req);
return $this->wait_response();
}
/**
* Wait for a response
*
* If a request was just sent, this will return the response.
* Otherwise, it will loop forever, handling events.
*
* @param boolean $allow_timeout if the socket times out, return an empty array
* @return array of parameters, empty on timeout
*/
function wait_response($allow_timeout=false)
{
$timeout = false;
do
{
$type = NULL;
$parameters = array();
$buffer = trim(fgets($this->socket, 4096));
while($buffer != '')
{
$a = strpos($buffer, ':');
if($a)
{
if(!count($parameters)) // first line in a response?
{
$type = strtolower(substr($buffer, 0, $a));
if(substr($buffer, $a + 2) == 'Follows')
{
// A follows response means there is a miltiline field that follows.
$parameters['data'] = '';
$buff = fgets($this->socket, 4096);
while(substr($buff, 0, 6) != '--END ')
{
$parameters['data'] .= $buff;
$buff = fgets($this->socket, 4096);
}
}
}
// store parameter in $parameters
$parameters[substr($buffer, 0, $a)] = substr($buffer, $a + 2);
}
$buffer = trim(fgets($this->socket, 4096));
}
// process response
switch($type)
{
case '': // timeout occured
$timeout = $allow_timeout;
break;
case 'event':
$this->process_event($parameters);
break;
case 'response':
break;
default:
$this->log('Unhandled response packet from Manager: ' . print_r($parameters, true));
break;
}
} while($type != 'response' && !$timeout);
return $parameters;
}
/**
* Connect to Asterisk
*
* @example examples/sip_show_peer.php Get information about a sip peer
*
* @param string $server
* @param string $username
* @param string $secret
* @return boolean true on success
*/
function connect($server=NULL, $username=NULL, $secret=NULL)
{
// use config if not specified
if(is_null($server)) $server = $this->config['asmanager']['server'];
if(is_null($username)) $username = $this->config['asmanager']['username'];
if(is_null($secret)) $secret = $this->config['asmanager']['secret'];
// get port from server if specified
if(strpos($server, ':') !== false)
{
$c = explode(':', $server);
$this->server = $c[0];
$this->port = $c[1];
}
else
{
$this->server = $server;
$this->port = $this->config['asmanager']['port'];
}
// connect the socket
$errno = $errstr = NULL;
$this->socket = @fsockopen($this->server, $this->port, $errno, $errstr);
if($this->socket == false)
{
$this->log("Unable to connect to manager {$this->server}:{$this->port} ($errno): $errstr");
return false;
}
// read the header
$str = fgets($this->socket);
if($str == false)
{
// a problem.
$this->log("Asterisk Manager header not received.");
return false;
}
else
{
// note: don't $this->log($str) until someone looks to see why it mangles the logging
}
// login
$res = $this->send_request('login', array('Username'=>$username, 'Secret'=>$secret));
if($res['Response'] != 'Success')
{
$this->log("Failed to login.");
$this->disconnect();
return false;
}
return true;
}
/**
* Disconnect
*
* @example examples/sip_show_peer.php Get information about a sip peer
*/
function disconnect()
{
$this->logoff();
fclose($this->socket);
}
// *********************************************************************************************************
// ** COMMANDS **
// *********************************************************************************************************
/**
* Set Absolute Timeout
*
* Hangup a channel after a certain time.
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+AbsoluteTimeout
* @param string $channel Channel name to hangup
* @param integer $timeout Maximum duration of the call (sec)
*/
function AbsoluteTimeout($channel, $timeout)
{
return $this->send_request('AbsoluteTimeout', array('Channel'=>$channel, 'Timeout'=>$timeout));
}
/**
* Change monitoring filename of a channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ChangeMonitor
* @param string $channel the channel to record.
* @param string $file the new name of the file created in the monitor spool directory.
*/
function ChangeMonitor($channel, $file)
{
return $this->send_request('ChangeMontior', array('Channel'=>$channel, 'File'=>$file));
}
/**
* Execute Command
*
* @example examples/sip_show_peer.php Get information about a sip peer
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Command
* @link http://www.voip-info.org/wiki-Asterisk+CLI
* @param string $command
* @param string $actionid message matching variable
*/
function Command($command, $actionid=NULL)
{
$parameters = array('Command'=>$command);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('Command', $parameters);
}
/**
* Enable/Disable sending of events to this manager
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Events
* @param string $eventmask is either 'on', 'off', or 'system,call,log'
*/
function Events($eventmask)
{
return $this->send_request('Events', array('EventMask'=>$eventmask));
}
/**
* Check Extension Status
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ExtensionState
* @param string $exten Extension to check state on
* @param string $context Context for extension
* @param string $actionid message matching variable
*/
function ExtensionState($exten, $context, $actionid=NULL)
{
$parameters = array('Exten'=>$exten, 'Context'=>$context);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('ExtensionState', $parameters);
}
/**
* Gets a Channel Variable
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+GetVar
* @link http://www.voip-info.org/wiki-Asterisk+variables
* @param string $channel Channel to read variable from
* @param string $variable
* @param string $actionid message matching variable
*/
function GetVar($channel, $variable, $actionid=NULL)
{
$parameters = array('Channel'=>$channel, 'Variable'=>$variable);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('GetVar', $parameters);
}
/**
* Hangup Channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Hangup
* @param string $channel The channel name to be hungup
*/
function Hangup($channel)
{
return $this->send_request('Hangup', array('Channel'=>$channel));
}
/**
* List IAX Peers
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+IAXpeers
*/
function IAXPeers()
{
return $this->send_request('IAXPeers');
}
/**
* List available manager commands
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ListCommands
* @param string $actionid message matching variable
*/
function ListCommands($actionid=NULL)
{
if($actionid)
return $this->send_request('ListCommands', array('ActionID'=>$actionid));
else
return $this->send_request('ListCommands');
}
/**
* Logoff Manager
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Logoff
*/
function Logoff()
{
return $this->send_request('Logoff');
}
/**
* Check Mailbox Message Count
*
* Returns number of new and old messages.
* Message: Mailbox Message Count
* Mailbox: <mailboxid>
* NewMessages: <count>
* OldMessages: <count>
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+MailboxCount
* @param string $mailbox Full mailbox ID <mailbox>@<vm-context>
* @param string $actionid message matching variable
*/
function MailboxCount($mailbox, $actionid=NULL)
{
$parameters = array('Mailbox'=>$mailbox);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('MailboxCount', $parameters);
}
/**
* Check Mailbox
*
* Returns number of messages.
* Message: Mailbox Status
* Mailbox: <mailboxid>
* Waiting: <count>
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+MailboxStatus
* @param string $mailbox Full mailbox ID <mailbox>@<vm-context>
* @param string $actionid message matching variable
*/
function MailboxStatus($mailbox, $actionid=NULL)
{
$parameters = array('Mailbox'=>$mailbox);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('MailboxStatus', $parameters);
}
/**
* Monitor a channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Monitor
* @param string $channel
* @param string $file
* @param string $format
* @param boolean $mix
*/
function Monitor($channel, $file=NULL, $format=NULL, $mix=NULL)
{
$parameters = array('Channel'=>$channel);
if($file) $parameters['File'] = $file;
if($format) $parameters['Format'] = $format;
if(!is_null($file)) $parameters['Mix'] = ($mix) ? 'true' : 'false';
return $this->send_request('Monitor', $parameters);
}
/**
* Originate Call
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Originate
* @param string $channel Channel name to call
* @param string $exten Extension to use (requires 'Context' and 'Priority')
* @param string $context Context to use (requires 'Exten' and 'Priority')
* @param string $priority Priority to use (requires 'Exten' and 'Context')
* @param string $application Application to use
* @param string $data Data to use (requires 'Application')
* @param integer $timeout How long to wait for call to be answered (in ms)
* @param string $callerid Caller ID to be set on the outgoing channel
* @param string $variable Channel variable to set (VAR1=value1|VAR2=value2)
* @param string $account Account code
* @param boolean $async true fast origination
* @param string $actionid message matching variable
*/
function Originate($channel,
$exten=NULL, $context=NULL, $priority=NULL,
$application=NULL, $data=NULL,
$timeout=NULL, $callerid=NULL, $variable=NULL, $account=NULL, $async=NULL, $actionid=NULL)
{
$parameters = array('Channel'=>$channel);
if($exten) $parameters['Exten'] = $exten;
if($context) $parameters['Context'] = $context;
if($priority) $parameters['Priority'] = $priority;
if($application) $parameters['Application'] = $application;
if($data) $parameters['Data'] = $data;
if($timeout) $parameters['Timeout'] = $timeout;
if($callerid) $parameters['CallerID'] = $callerid;
if($variable) $parameters['Variable'] = $variable;
if($account) $parameters['Account'] = $account;
if(!is_null($async)) $parameters['Async'] = ($async) ? 'true' : 'false';
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('Originate', $parameters);
}
/**
* List parked calls
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ParkedCalls
* @param string $actionid message matching variable
*/
function ParkedCalls($actionid=NULL)
{
if($actionid)
return $this->send_request('ParkedCalls', array('ActionID'=>$actionid));
else
return $this->send_request('ParkedCalls');
}
/**
* Ping
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Ping
*/
function Ping()
{
return $this->send_request('Ping');
}
/**
* Queue Add
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+QueueAdd
* @param string $queue
* @param string $interface
* @param integer $penalty
*/
function QueueAdd($queue, $interface, $penalty=0)
{
$parameters = array('Queue'=>$queue, 'Interface'=>$interface);
if($penalty) $parameters['Penalty'] = $penalty;
return $this->send_request('QueueAdd', $parameters);
}
/**
* Queue Remove
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+QueueRemove
* @param string $queue
* @param string $interface
*/
function QueueRemove($queue, $interface)
{
return $this->send_request('QueueRemove', array('Queue'=>$queue, 'Interface'=>$interface));
}
/**
* Queues
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Queues
*/
function Queues()
{
return $this->send_request('Queues');
}
/**
* Queue Status
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+QueueStatus
* @param string $actionid message matching variable
*/
function QueueStatus($actionid=NULL)
{
if($actionid)
return $this->send_request('QueueStatus', array('ActionID'=>$actionid));
else
return $this->send_request('QueueStatus');
}
/**
* Redirect
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Redirect
* @param string $channel
* @param string $extrachannel
* @param string $exten
* @param string $context
* @param string $priority
*/
function Redirect($channel, $extrachannel, $exten, $context, $priority)
{
return $this->send_request('Redirect', array('Channel'=>$channel, 'ExtraChannel'=>$extrachannel, 'Exten'=>$exten,
'Context'=>$context, 'Priority'=>$priority));
}
/**
* Set the CDR UserField
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+SetCDRUserField
* @param string $userfield
* @param string $channel
* @param string $append
*/
function SetCDRUserField($userfield, $channel, $append=NULL)
{
$parameters = array('UserField'=>$userfield, 'Channel'=>$channel);
if($append) $parameters['Append'] = $append;
return $this->send_request('SetCDRUserField', $parameters);
}
/**
* Set Channel Variable
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+SetVar
* @param string $channel Channel to set variable for
* @param string $variable name
* @param string $value
*/
function SetVar($channel, $variable, $value)
{
return $this->send_request('SetVar', array('Channel'=>$channel, 'Variable'=>$variable, 'Value'=>$value));
}
/**
* Channel Status
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Status
* @param string $channel
* @param string $actionid message matching variable
*/
function Status($channel, $actionid=NULL)
{
$parameters = array('Channel'=>$channel);
if($actionid) $parameters['ActionID'] = $actionid;
return $this->send_request('Status', $parameters);
}
/**
* Stop monitoring a channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+StopMonitor
* @param string $channel
*/
function StopMontor($channel)
{
return $this->send_request('StopMonitor', array('Channel'=>$channel));
}
/**
* Dial over Zap channel while offhook
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapDialOffhook
* @param string $zapchannel
* @param string $number
*/
function ZapDialOffhook($zapchannel, $number)
{
return $this->send_request('ZapDialOffhook', array('ZapChannel'=>$zapchannel, 'Number'=>$number));
}
/**
* Toggle Zap channel Do Not Disturb status OFF
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapDNDoff
* @param string $zapchannel
*/
function ZapDNDoff($zapchannel)
{
return $this->send_request('ZapDNDoff', array('ZapChannel'=>$zapchannel));
}
/**
* Toggle Zap channel Do Not Disturb status ON
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapDNDon
* @param string $zapchannel
*/
function ZapDNDon($zapchannel)
{
return $this->send_request('ZapDNDon', array('ZapChannel'=>$zapchannel));
}
/**
* Hangup Zap Channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapHangup
* @param string $zapchannel
*/
function ZapHangup($zapchannel)
{
return $this->send_request('ZapHangup', array('ZapChannel'=>$zapchannel));
}
/**
* Transfer Zap Channel
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapTransfer
* @param string $zapchannel
*/
function ZapTransfer($zapchannel)
{
return $this->send_request('ZapTransfer', array('ZapChannel'=>$zapchannel));
}
/**
* Zap Show Channels
*
* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+ZapShowChannels
* @param string $actionid message matching variable
*/
function ZapShowChannels($actionid=NULL)
{
if($actionid)
return $this->send_request('ZapShowChannels', array('ActionID'=>$actionid));
else
return $this->send_request('ZapShowChannels');
}
// *********************************************************************************************************
// ** MISC **
// *********************************************************************************************************
/*
* Log a message
*
* @param string $message
* @param integer $level from 1 to 4
*/
function log($message, $level=1)
{
if($this->pagi != false)
$this->pagi->conlog($message, $level);
else
error_log(date('r') . ' - ' . $message);
}
/**
* Add event handler
*
* Known Events include ( http://www.voip-info.org/wiki-asterisk+manager+events )
* Link - Fired when two voice channels are linked together and voice data exchange commences.
* Unlink - Fired when a link between two voice channels is discontinued, for example, just before call completion.
* Newexten -
* Hangup -
* Newchannel -
* Newstate -
* Reload - Fired when the "RELOAD" console command is executed.
* Shutdown -
* ExtensionStatus -
* Rename -
* Newcallerid -
* Alarm -
* AlarmClear -
* Agentcallbacklogoff -
* Agentcallbacklogin -
* Agentlogoff -
* MeetmeJoin -
* MessageWaiting -
* join -
* leave -
* AgentCalled -
* ParkedCall - Fired after ParkedCalls
* Cdr -
* ParkedCallsComplete -
* QueueParams -
* QueueMember -
* QueueStatusEnd -
* Status -
* StatusComplete -
* ZapShowChannels - Fired after ZapShowChannels
* ZapShowChannelsComplete -
*
* @param string $event type or * for default handler
* @param string $callback function
* @return boolean sucess
*/
function add_event_handler($event, $callback)
{
$event = strtolower($event);
if(isset($this->event_handlers[$event]))
{
$this->log("$event handler is already defined, not over-writing.");
return false;
}
$this->event_handlers[$event] = $callback;
return true;
}
/**
* Process event
*
* @access private
* @param array $parameters
* @return mixed result of event handler or false if no handler was found
*/
function process_event($parameters)
{
$ret = false;
$e = strtolower($parameters['Event']);
$this->log("Got event.. $e");
$handler = '';
if(isset($this->event_handlers[$e])) $handler = $this->event_handlers[$e];
elseif(isset($this->event_handlers['*'])) $handler = $this->event_handlers['*'];
if(function_exists($handler))
{
$this->log("Execute handler $handler");
$ret = $handler($e, $parameters, $this->server, $this->port);
}
else
$this->log("No event handler for event '$e'");
return $ret;
}
}
?>
freenetis/trunk/kohana/application/libraries/AGI.php
<?php
/**
* phpagi.php : PHP AGI Functions for Asterisk
* Website: http://phpagi.sourceforge.net/
*
* $Id: phpagi.php,v 2.14 2005/05/25 20:30:46 pinhole Exp $
*
* Copyright (c) 2003, 2004, 2005 Matthew Asham <matthewa@bcwireless.net>, David Eder <david@eder.us>
* All Rights Reserved.
*
* This software is released under the terms of the GNU Lesser General Public License v2.1
* A copy of which is available from http://www.gnu.org/copyleft/lesser.html
*
* We would be happy to list your phpagi based application on the phpagi
* website. Drop me an Email if you'd like us to list your program.
*
*
* Written for PHP 4.3.4, should work with older PHP 4.x versions.
*
* Please submit bug reports, patches, etc to http://sourceforge.net/projects/phpagi/
* Gracias. :)
*
*
* @package phpAGI
* @version 2.0
*/
/**
*/
if(!class_exists('AsteriskManager'))
{
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'phpagi-asmanager.php');
}
define('AST_CONFIG_DIR', '/etc/asterisk/');
define('AST_SPOOL_DIR', '/var/spool/asterisk/');
define('AST_TMP_DIR', AST_SPOOL_DIR . '/tmp/');
define('DEFAULT_PHPAGI_CONFIG', AST_CONFIG_DIR . '/phpagi.conf');
define('AST_DIGIT_ANY', '0123456789#*');
define('AGIRES_OK', 200);
define('AST_STATE_DOWN', 0);
define('AST_STATE_RESERVED', 1);
define('AST_STATE_OFFHOOK', 2);
define('AST_STATE_DIALING', 3);
define('AST_STATE_RING', 4);
define('AST_STATE_RINGING', 5);
define('AST_STATE_UP', 6);
define('AST_STATE_BUSY', 7);
define('AST_STATE_DIALING_OFFHOOK', 8);
define('AST_STATE_PRERING', 9);
define('AUDIO_FILENO', 3); // STDERR_FILENO + 1
/**
* AGI class
*
* @package phpAGI
* @link http://www.voip-info.org/wiki-Asterisk+agi
* @example examples/dtmf.php Get DTMF tones from the user and say the digits
* @example examples/input.php Get text input from the user and say it back
* @example examples/ping.php Ping an IP address
*/
class AGI
{
/**
* Request variables read in on initialization.
*
* Often contains any/all of the following:
* agi_request - name of agi script
* agi_channel - current channel
* agi_language - current language
* agi_type - channel type (SIP, ZAP, IAX, ...)
* agi_uniqueid - unique id based on unix time
* agi_callerid - callerID string
* agi_dnid - dialed number id
* agi_rdnis - referring DNIS number
* agi_context - current context
* agi_extension - extension dialed
* agi_priority - current priority
* agi_enhanced - value is 1.0 if started as an EAGI script
* agi_accountcode - set by SetAccount in the dialplan
* agi_network - value is yes if this is a fastagi
* agi_network_script - name of the script to execute
*
* NOTE: program arguments are still in $_SERVER['argv'].
*
* @var array
* @access public
*/
var $request;
/**
* Config variables
*
* @var array
* @access public
*/
var $config;
/**
* Asterisk Manager
*
* @var AsteriskManager
* @access public
*/
var $asmanager;
/**
* Input Stream
*
* @access private
*/
var $in = NULL;
/**
* Output Stream
*
* @access private
*/
var $out = NULL;
/**
* Audio Stream
*
* @access public
*/
var $audio = NULL;
/**
* Constructor
*
* @param string $config is the name of the config file to parse
* @param array $optconfig is an array of configuration vars and vals, stuffed into $this->config['phpagi']
*/
function AGI($config=NULL, $optconfig=array())
{
// load config
if(!is_null($config) && file_exists($config))
$this->config = parse_ini_file($config, true);
elseif(file_exists(DEFAULT_PHPAGI_CONFIG))
$this->config = parse_ini_file(DEFAULT_PHPAGI_CONFIG, true);
// If optconfig is specified, stuff vals and vars into 'phpagi' config array.
foreach($optconfig as $var=>$val)
$this->config['phpagi'][$var] = $val;
// add default values to config for uninitialized values
if(!isset($this->config['phpagi']['error_handler'])) $this->config['phpagi']['error_handler'] = true;
if(!isset($this->config['phpagi']['debug'])) $this->config['phpagi']['debug'] = false;
if(!isset($this->config['phpagi']['admin'])) $this->config['phpagi']['admin'] = NULL;
if(!isset($this->config['phpagi']['tempdir'])) $this->config['phpagi']['tempdir'] = AST_TMP_DIR;
// festival TTS config
if(!isset($this->config['festival']['text2wave'])) $this->config['festival']['text2wave'] = $this->which('text2wave');
// swift TTS config
if(!isset($this->config['cepstral']['swift'])) $this->config['cepstral']['swift'] = $this->which('swift');
ob_implicit_flush(true);
// open stdin & stdout
$this->in = defined('STDIN') ? STDIN : fopen('php://stdin', 'r');
$this->out = defined('STDOUT') ? STDOUT : fopen('php://stdout', 'w');
// initialize error handler
if($this->config['phpagi']['error_handler'] == true)
{
set_error_handler('phpagi_error_handler');
global $phpagi_error_handler_email;
$phpagi_error_handler_email = $this->config['phpagi']['admin'];
error_reporting(E_ALL);
}
// make sure temp folder exists
$this->make_folder($this->config['phpagi']['tempdir']);
// read the request
$str = fgets($this->in);
while($str != "\n")
{
$this->request[substr($str, 0, strpos($str, ':'))] = trim(substr($str, strpos($str, ':') + 1));
$str = fgets($this->in);
}
// open audio if eagi detected
if($this->request['agi_enhanced'] == '1.0')
{
if(file_exists('/proc/' . getmypid() . '/fd/3'))
$this->audio = fopen('/proc/' . getmypid() . '/fd/3', 'r');
elseif(file_exists('/dev/fd/3'))
{
// may need to mount fdescfs
$this->audio = fopen('/dev/fd/3', 'r');
}
else
$this->conlog('Unable to open audio stream');
if($this->audio) stream_set_blocking($this->audio, 0);
}
$this->conlog('AGI Request:');
$this->conlog(print_r($this->request, true));
$this->conlog('PHPAGI internal configuration:');
$this->conlog(print_r($this->config, true));
}
// *********************************************************************************************************
// ** COMMANDS **
// *********************************************************************************************************
/**
* Answer channel if not already in answer state.
*
* @link http://www.voip-info.org/wiki-answer
* @example examples/dtmf.php Get DTMF tones from the user and say the digits
* @example examples/input.php Get text input from the user and say it back
* @example examples/ping.php Ping an IP address
*
* @return array, see evaluate for return information. ['result'] is 0 on success, -1 on failure.
*/
function answer()
{
return $this->evaluate('ANSWER');
}
/**
* Get the status of the specified channel. If no channel name is specified, return the status of the current channel.
*
* @link http://www.voip-info.org/wiki-channel+status
* @param string $channel
* @return array, see evaluate for return information. ['data'] contains description.
*/
function channel_status($channel='')
{
$ret = $this->evaluate("CHANNEL STATUS $channel");
switch($ret['result'])
{
case -1: $ret['data'] = trim("There is no channel that matches $channel"); break;
case AST_STATE_DOWN: $ret['data'] = 'Channel is down and available'; break;
case AST_STATE_RESERVED: $ret['data'] = 'Channel is down, but reserved'; break;
case AST_STATE_OFFHOOK: $ret['data'] = 'Channel is off hook'; break;
case AST_STATE_DIALING: $ret['data'] = 'Digits (or equivalent) have been dialed'; break;
case AST_STATE_RING: $ret['data'] = 'Line is ringing'; break;
case AST_STATE_RINGING: $ret['data'] = 'Remote end is ringing'; break;
case AST_STATE_UP: $ret['data'] = 'Line is up'; break;
case AST_STATE_BUSY: $ret['data'] = 'Line is busy'; break;
case AST_STATE_DIALING_OFFHOOK: $ret['data'] = 'Digits (or equivalent) have been dialed while offhook'; break;
case AST_STATE_PRERING: $ret['data'] = 'Channel has detected an incoming call and is waiting for ring'; break;
default: $ret['data'] = "Unknown ({$ret['result']})"; break;
}
return $ret;
}
/**
* Deletes an entry in the Asterisk database for a given family and key.
*
* @link http://www.voip-info.org/wiki-database+del
* @param string $family
* @param string $key
* @return array, see evaluate for return information. ['result'] is 1 on sucess, 0 otherwise.
*/
function database_del($family, $key)
{
return $this->evaluate("DATABASE DEL \"$family\" \"$key\"");
}
/**
* Deletes a family or specific keytree within a family in the Asterisk database.
*
* @link http://www.voip-info.org/wiki-database+deltree
* @param string $family
* @param string $keytree
* @return array, see evaluate for return information. ['result'] is 1 on sucess, 0 otherwise.
*/
function database_deltree($family, $keytree='')
{
$cmd = "DATABASE DELTREE \"$family\"";
if($keytree != '') $cmd .= " \"$keytree\"";
return $this->evaluate($cmd);
}
/**
* Retrieves an entry in the Asterisk database for a given family and key.
*
* @link http://www.voip-info.org/wiki-database+get
* @param string $family
* @param string $key
* @return array, see evaluate for return information. ['result'] is 1 on sucess, 0 failure. ['data'] holds the value
*/
function database_get($family, $key)
{
return $this->evaluate("DATABASE GET \"$family\ \"$key\"");
}
/**
* Adds or updates an entry in the Asterisk database for a given family, key, and value.
*
* @param string $family
* @param string $key
* @param string $value
* @return array, see evaluate for return information. ['result'] is 1 on sucess, 0 otherwise
*/
function database_put($family, $key, $value)
{
$value = str_replace("\n", '\n', addslashes($value));
return $this->evaluate("DATABASE PUT \"$family\" \"$key\" \"$value\"");
}
/**
* Executes the specified Asterisk application with given options.
*
* @link http://www.voip-info.org/wiki-exec
* @link http://www.voip-info.org/wiki-Asterisk+-+documentation+of+application+commands
* @param string $application
* @param mixed $options
* @return array, see evaluate for return information. ['result'] is whatever the application returns, or -2 on failure to find application
*/
function exec($application, $options)
{
if(is_array($options)) $options = join('|', $options);
return $this->evaluate("EXEC $application $options");
}
/**
* Plays the given file and receives DTMF data.
*
* This is similar to STREAM FILE, but this command can accept and return many DTMF digits,
* while STREAM FILE returns immediately after the first DTMF digit is detected.
*
* Asterisk looks for the file to play in /var/lib/asterisk/sounds by default.
*
* If the user doesn't press any keys when the message plays, there is $timeout milliseconds
* of silence then the command ends.
*
* The user has the opportunity to press a key at any time during the message or the
* post-message silence. If the user presses a key while the message is playing, the
* message stops playing. When the first key is pressed a timer starts counting for
* $timeout milliseconds. Every time the user presses another key the timer is restarted.
* The command ends when the counter goes to zero or the maximum number of digits is entered,
* whichever happens first.
*
* If you don't specify a time out then a default timeout of 2000 is used following a pressed
* digit. If no digits are pressed then 6 seconds of silence follow the message.
*
* If you don't specify $max_digits then the user can enter as many digits as they want.
*
* Pressing the # key has the same effect as the timer running out: the command ends and
* any previously keyed digits are returned. A side effect of this is that there is no
* way to read a # key using this command.
*
* @example examples/ping.php Ping an IP address
*
* @link http://www.voip-info.org/wiki-get+data
* @param string $filename file to play. Do not include file extension.
* @param integer $timeout milliseconds
* @param integer $max_digits
* @return array, see evaluate for return information. ['result'] holds the digits and ['data'] holds the timeout if present.
*
* This differs from other commands with return DTMF as numbers representing ASCII characters.
*/
function get_data($filename, $timeout=NULL, $max_digits=NULL)
{
return $this->evaluate(rtrim("GET DATA $filename $timeout $max_digits"));
}
/**
* Fetch the value of a variable.
*
* Does not work with global variables. Does not work with some variables that are generated by modules.
*
* @link http://www.voip-info.org/wiki-get+variable
* @link http://www.voip-info.org/wiki-Asterisk+variables
* @param string $variable name
* @return array, see evaluate for return information. ['result'] is 0 if variable hasn't been set, 1 if it has. ['data'] holds the value.
*/
function get_variable($variable)
{
return $this->evaluate("GET VARIABLE $variable");
}
/**
* Hangup the specified channel. If no channel name is given, hang up the current channel.
*
* With power comes responsibility. Hanging up channels other than your own isn't something
* that is done routinely. If you are not sure why you are doing so, then don't.
*
* @link http://www.voip-info.org/wiki-hangup
* @example examples/dtmf.php Get DTMF tones from the user and say the digits
... Rozdílový soubor je zkrácen, protože jeho délka přesahuje max. limit.

Také k dispozici: Unified diff