php-asmanager.php

来自「最近在做软交换时研究的一个软交换的东东」· PHP 代码 · 共 783 行 · 第 1/2 页

PHP
783
字号
<?php/*** phpagi-asmanager.php : PHP Asterisk Manager functions* Website: http://phpagi.sourceforge.net** Copyright (c) 2004 Matthew Asham <matthewa@bcwireless.net>* All Rights Reserved.** This software is released under the terms of the GNU Public License v2*  A copy of which is available from http://www.fsf.org/licenses/gpl.txt* **  You are requested to drop me an Email letting me know that you're *  using it.  This is more of a courtesy than anything else, but I am *  interested to know how it is being used.** @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. :)**/  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("AMP_CONF", "/etc/amportal.conf");  define('AST_DIGIT_ANY', '0123456789#*');  define('AGI_PORT', 4573);  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);/*** 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 AGI_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 AGI_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();					if (feof($this->socket))				return false;			$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)		{			$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);	}		/**	* Set Absolute Timeout	*	* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+AbsoluteTimeout	* @param string $channel	* @param integer $timeout	*/	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	* @param string $file	*/	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 $commadn	*/	function Command($command)	{			return $this->send_request('Command', array('Command'=>$command));	}		/**	* 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	* @param string $context	* @param string $actionid	*/	function ExtensionState($exten, $context, $actionid)	{		return $this->send_request('ExtensionState', array('Exten'=>$exten, 'Context'=>$context, 'ActionID'=>$actionid));	}		/**	* Gets a Channel Variable	*	* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+GetVar	* @param string $channel	* @param string $variable	*/	function GetVar($channel, $variable)	{		return $this->send_request('GetVar', array('Channel'=>$channel, 'Variable'=>$variable));	}		/**	* Hangup Channel	*	* @link http://www.voip-info.org/wiki-Asterisk+Manager+API+Action+Hangup	* @param string $channel	*/	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	*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?