CRM challenge

  • Increase font size
  • Default font size
  • Decrease font size

Vtiger CRM 5.1.0, Asterisk Integration, inbound calls problem

Email Print PDF

The problem of making PBX Module under Vtiger CRM working is a challenge for many Asterisk and Vtiger users. Unfortunately this not worked for me and even surfing the Vtiger forum / web did not helped to find working (for me) solution but encouraged to solve it finally for myself.

So here are solution for Asterisk 1.4 and Asterisk 1.6 with Vtiger CRM Integration. This post concerned about inbound calls problem. This solution worked for me so this may also work for some people as well. But no 100% warranty as there are a lot of source codes presented at forum which worked for 1 person but not worked for another. So below are my versions of solution for 1) Asterisk 1.4 and 2) Asterisk 1.6 and also 3) some notes about bugs I found in Vtiger PBX module and related to the subject. These files far from perfect, especially for Asterisk 1.6 but they worked. Generally with Asterisk 1.6 it works slower so I prefer now 1.4 script.

1) Asterisk 1.4

here is source code of AsteriskClient.php for Asterisk 1.4 and direct download link

(rename it to AsteriskClient.php and upload to proper directory of Vtiger)

#!/usr/bin/php
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/

/**
* this file will be run as a shell script (in linux) or a batch file (under windows).
* the purpose of the file is to create a master socket which will be connecting to the asterisk server
* and to keep it (the socket) alive all the time.
*/

ini_set("include_path", "../../../");

require_once('modules/PBXManager/utils/AsteriskClass.php');
require_once('config.php');
require_once('include/utils/utils.php');
require_once('include/language/en_us.lang.php');
require_once('modules/PBXManager/AsteriskUtils.php');

asteriskClient();

/**
* this function defines the asterisk client
*/
function asteriskClient(){
global $app_strings, $current_user;
global $adb, $log;

$data = getAsteriskInfo($adb);
$server = $data['server'];
$port = $data['port'];
$username = $data['username'];
$password = $data['password'];
$version = $data['version'];

$errno = $errstr = NULL;
$sock = @fsockopen($server, $port, $errno, $errstr, 1);
stream_set_blocking($sock, false);
if( $sock === false ) {
echo "Socket cannot be created due to error: $errno: $errstr\n";
$log->debug("Socket cannot be created due to error: $errno: $errstr\n");
exit(0);
}else{
echo "Date: ".date("d-m-Y")."\n";
echo "Connecting to asterisk server.....\n";
$log->debug("Connecting to asterisk server.....\n");
}
echo "Connected successfully\n\n\n";
$asterisk = new Asterisk($sock, $server, $port);

authorizeUser($username, $password, $asterisk);

//keep looping continuosly to check if there are any calls
while (true) {
//check for incoming calls and insert in the database
sleep(2);
$incoming = handleIncomingCalls($asterisk, $adb, $version);
}
fclose($sock);
unset($sock);
}

/**
* this function checks if there are any incoming calls for the current user
* if any call is found, it just inserts the values into the vtiger_asteriskincomingcalls table
*
* @param $asterisk - the asterisk object
* @param $adb - the peardatabase type object
* @return incoming call information if successful
* false if unsuccessful
*/
function handleIncomingCalls($asterisk, $adb, $version="1.4"){
$response = $asterisk->getAsteriskResponse();


if(empty($response)){
return false;
}
$callerNumber = "Unknown";
$callerName = "Unknown";

//event can be both newstate and newchannel :: this is an asterisk bug and can be found at
//http://lists.digium.com/pipermail/asterisk-dev/2006-July/021565.html
if($version == "1.6"){
$state = "ChannelStateDesc";
}else{
$state = "State";
}

if(($response['Event'] == 'Newstate' || $response['Event'] == 'Newchannel') && ($response[$state] == 'Ring' || $response[$state] == 'Ringing')){
//get the caller information
if(!empty($response['CallerID'])){
$callerNumber = $response['CallerID'];
}elseif(!empty($response['CallerIDNum'])){
$callerNumber = $response['CallerIDNum'];
}
if(!empty($response['CallerIDName'])){
$callerName = $response['CallerIDName'];
}
while(true){
$response = $asterisk->getAsteriskResponse();


// if(($response['Event'] == 'Newexten') && (strstr($response['AppData'],"__DIALED_NUMBER") || strstr($response['AppData'],"EXTTOCALL"))){
if(($response['Event'] == 'Newexten') && ($response['Application'] == 'Dial')) {
$temp = array();
// if(strstr($response['Channel'], $callerNumber)){
if(strstr($response['Channel'], '-')){
$temp = explode("/",$response['Channel']);
$callerType = $temp[0];
}
// $temp = explode("=",$response['AppData']);

$extension = $response['Extension'];

if(checkExtension($extension, $adb)){
//insert into database
$sql = "insert into vtiger_asteriskincomingcalls values (?,?,?,?,?,?)";
$flag= 0;
$timer = time();
$params = array($callerNumber, $callerName, $extension, $callerType,$flag,$timer);

$adb->pquery($sql, $params);

addToCallHistory($extension, $callerType.":".$callerNumber, $extension, "incoming", $adb);
break; //break the while loop
}
}
}
}else{
return false;
}
}


/**
* this function takes a XML response and converts it to an array format
* @param string $response - the xml response
* @return the xml formatted into an array
*/
function getArray($xml){
$lines = explode("\r\n", $xml);

$response = array();
foreach($lines as $line){
list($key, $value) = explode(":", $line);
$response[$key] = $value;
}
return $response;
}

/**
* this function checks if the given extension is a valid vtiger extension or not
* if yes it returns true
* if not it returns false
*
* @param string $ext - the extension to be checked
* @param object $adb - the peardatabase object
*/
function checkExtension($ext, $adb){
$sql = "select * from vtiger_asteriskextensions where asterisk_extension='$ext'";
$result = $adb->pquery($sql, array());

if($adb->num_rows($result)>0){
return true;
}else{
return false;
}
}
?>

2) Asterisk 1.6

here is source code of AsteriskClient.php for Asterisk 1.6 and direct download link

(rename it to AsteriskClient.php and upload to proper directory of Vtiger)

#!/usr/bin/php
<?php
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/

/**
* this file will be run as a shell script (in linux) or a batch file (under windows).
* the purpose of the file is to create a master socket which will be connecting to the asterisk server
* and to keep it (the socket) alive all the time.
*/

ini_set("include_path", "../../../");

require_once('modules/PBXManager/utils/AsteriskClass.php');
require_once('config.php');
require_once('include/utils/utils.php');
require_once('include/language/en_us.lang.php');
require_once('modules/PBXManager/AsteriskUtils.php');

//$debug_asterisk = false;

asteriskClient();

/**
* this function defines the asterisk client
*/
function asteriskClient(){
global $app_strings, $current_user;
global $adb, $log;

$data = getAsteriskInfo($adb);
$server = $data['server'];
$port = $data['port'];
$username = $data['username'];
$password = $data['password'];
$version = $data['version'];

$errno = $errstr = NULL;
$sock = @fsockopen($server, $port, $errno, $errstr, 1);
stream_set_blocking($sock, false);
if( $sock === false ) {
echo "Socket cannot be created due to error: $errno: $errstr\n";
$log->debug("Socket cannot be created due to error: $errno: $errstr\n");
exit(0);
}else{
echo "Date: ".date("d-m-Y")."\n";
echo "Connecting to asterisk server.....\n";
$log->debug("Connecting to asterisk server.....\n");
}
echo "Connected successfully\n\n\n";
$asterisk = new Asterisk($sock, $server, $port);

authorizeUser($username, $password, $asterisk);

//keep looping continuosly to check if there are any calls
while (true) {
//check for incoming calls and insert in the database
// sleep(2);
$incoming = handleIncomingCalls($asterisk, $adb, $version);
}
fclose($sock);
unset($sock);
}

/**
* this function checks if there are any incoming calls for the current user
* if any call is found, it just inserts the values into the vtiger_asteriskincomingcalls table
*
* @param $asterisk - the asterisk object
* @param $adb - the peardatabase type object
* @return incoming call information if successful
* false if unsuccessful
*/
function handleIncomingCalls($asterisk, $adb, $version){
$response = $asterisk->getAsteriskResponse();

if(empty($response)){
return false;
}
$callerNumber = "Unknown";
$callerName = "Unknown";

//event can be both newstate and newchannel :: this is an asterisk bug and can be found at
//http://lists.digium.com/pipermail/asterisk-dev/2006-July/021565.html
if($version == "1.6"){
$state = "ChannelStateDesc";
}else{
$state = "State";
}

if(($response['Event'] == 'Newstate' || $response['Event'] == 'Newchannel') && ($response[$state] == 'Ring' || $response[$state] == 'Ringing')){
//get the caller information

$callerNumber = "Unknown";
$callerName = "Unknown";

if(!empty($response['CallerID'])){
$callerNumber = $response['CallerID'];
}elseif(!empty($response['CallerIDNum'])){
$callerNumber = $response['CallerIDNum'];
}
if(!empty($response['CallerIDName'])){
$callerName = $response['CallerIDName'];
}
while(true){
$response = $asterisk->getAsteriskResponse();


// if(($response['Event'] == 'Newexten') && (strstr($response['AppData'],"__DIALED_NUMBER") || strstr($response['AppData'],"EXTTOCALL"))){

$check1=strstr($response['Channel'], $callerNumber);

if(($response['Event'] == 'Newexten') && ($response['Application'] == 'Dial') && ($check1 != '')) {

$check1='';
$temp = array();
// if(strstr($response['Channel'], $callerNumber)){
if(strstr($response['AppData'], ',')){
//$xx=strstr($response['AppData'], ',');
$temp = explode("/",$response['AppData']);
// $temp = explode("/",$xx);
$callerType = $temp[0];
$temp = explode(",",$temp[1]);
}

// $temp = explode("=",$response['AppData']);

$extension = $temp[0];
// $extension = $response['Extension'];

if(checkExtension($extension, $adb)){
//insert into database
$sql = "insert into vtiger_asteriskincomingcalls values (?,?,?,?,?,?)";
$flag= 0;
$timer = time();
$params = array($callerNumber, $callerName, $extension, $callerType,$flag,$timer);

$adb->pquery($sql, $params);

addToCallHistory($extension, $callerType.":".$callerNumber, $extension, "incoming", $adb);
break; //break the while loop
}
}
}
}else{
return false;
}
}


/**
* this function takes a XML response and converts it to an array format
* @param string $response - the xml response
* @return the xml formatted into an array
*/
function getArray($xml){
$lines = explode("\r\n", $xml);

$response = array();
foreach($lines as $line){
list($key, $value) = explode(":", $line);
$response[$key] = $value;
}
return $response;
}

/**
* this function checks if the given extension is a valid vtiger extension or not
* if yes it returns true
* if not it returns false
*
* @param string $ext - the extension to be checked
* @param object $adb - the peardatabase object
*/
function checkExtension($ext, $adb){
$sql = "select * from vtiger_asteriskextensions where asterisk_extension='$ext'";
$result = $adb->pquery($sql, array());

if($adb->num_rows($result)>0){
return true;
}else{
return false;
}
}
?>

3. Some notes of bugs

a) Situation: After login to Vtiger you go to "preferences" and fill out "Asterisk Extension" field. Some time later (or immediately after saving extension info) you again edit this field and remove info about extension (so field became empty).

Problem: In MySQL database this user still has a record in "AsteriskExtensions" table but record is empty. This cause error in executing AsteriskClient.php once inbound call happens.

Temporary solution: once you fill this field with any data and save, never make it empty after. Better put inside any figures or/and switch "Receive Calls" to OFF.

b) Situation: You already setup the system for inbound calls and you see popup windows on inbound calls. Now you get incoming call from somebody and you pretty sure this person phone is in your contacts. But you don't see in pop-up window name of this person - inbound call is from Unknown.

Problem: In case you have Contact with more then 1 phone, and if Contact calling you from second phone is your list, system do not recognize phone in Contact. Seems Vtiger now recognize only first Phone number in a list of numbers for Contact. In other words, if you fill in Working Number and Mobile Number - Vtiger will recognize contact only if person calls from Working number. If person calls from Mobile - it will be not recognized. But if you remove Working number from contact details, and now this person call from Mobile - it will be recognized.

Solution: not available from me, hopefully - Vtiger team corrections to source code

Last Updated on Sunday, 03 October 2010 21:08  

Comments  

 
0 #16 770 account 2014-10-11 20:44
Highly energetic article, I loved that bit.
Will there be a part 2?
Quote
 
 
0 #15 Car Rental 2014-04-09 23:21
Great web site. A lot of useful information here.
I’m sending it to some friends ans also sharing in delicious.
And naturally, thanks for your effort!
Quote
 
 
+1 #14 Angel Chavez 2012-06-15 16:15
Hi I run Asteriskclient.php in first time and it works well but now the window popup for incoming call doesn't appear. I ran the Asteriskclient.php again and this time it works wrong. What I have to do to window popup incoming call appear again?
Quote
 
 
+1 #13 Pratik 2012-04-04 04:00
Try to make your own.
http://codebyte.blogspot.com/2012/03/integrating-vtiger-crm-with-asterisk_23.html

Quoting vladimir:
Hello,

tried your code but without success....outgoing calls work and they are registered in pbxmanager but incoming popup with no success... phone rings and I establish a call...

vtiger 5.2.0
asterisk 1.6

what logs or other info can I provide to help me incoming popup to work.... does browser has anything to do with popup (firefox 3.6.7)?? Outgoing popup works (it is shown).
Quote
 
 
+1 #12 Pratik 2012-04-04 03:58
Hi,
For me AsteriskClient.php did not work. I mean it starts but after some time, it hangs with no response and no pop ups. So, I made my own AsteriskClient using Asterisk-Java API. I have give hint on making this API in my blog.

http://codebyte.blogspot.com/2012/03/integrating-vtiger-crm-with-asterisk_23.html
Quote
 
 
+1 #11 berrayahkamel 2012-01-05 23:34
[quote name="berrayahkamel"]hi

the __DIALED_NUMBER and EXTTOCALL i think it used un trixbox or freebox ousomthing like this ; howver you can fixe this var in extensions.conf , something like :

exten => xx,1, setvar(exten => s,1,Setvar(__DIALE D_NUMBER =${value})
Quote
 
 
+1 #10 berrayahkamel 2012-01-05 23:07
hi

the __DIALED_NUMBER and EXTTOCALL i think it used un trixbox or freebox ousomthing like this ; howver you can fixe this var in extensions.conf , something like :

exten => xx,1, setvar(xten => s,1,Set(__DIALED_N UMBER =${value})
Quote
 
 
+1 #9 Miguel 2011-08-28 06:10
Where do I put Asterisk_Client .php? I'm using vTiger 5.1.0
Quote
 
 
+2 #8 Bill 2011-03-03 05:18
On but 3(b) with not finding numbers, I also had a problem with vtiger not pattern matching the caller id (digits only) to a formatted number saved in vtiger. I wrote a hack to use a custom query for the lookup that addresses both the pattern matching and searching all the phone fields in Accounts, Contacts, and Leads. It's a hack. And it's ugly. But you're welcome to it if you want it.

I posted it on the vtiger forum here
http://forums.vtiger.com/viewtopic.php?f=104&t=43294
Quote
 
 
+1 #7 jon dyke 2011-01-21 11:44
How do i intergrate vtigercrm 5.2.0 into asterisk 1.8. I am having problems with changing data via phpmyadmin . I have followed. I change the asterisk version to 1.8 but when I save it it disappears.
Quote
 

Add comment


Security code
Refresh

Preferred proofreading online service with huge crew of professionals and good support.

Article(s) will appear soon... (now being written)

1. Test-drive of some software for showing IP PBX incoming calls pop-up window (ADA, ASTassistant, 3cx assistant and some more) and its CRM integration (incl.vtiger as alternative to PBXManager).

2. OpenTaps ERP + CRM incoming call pop-up window - make it working

Other abc7.eu free-hosted sites