function startCall()
{
    global $current_user, $adb, $log;
    require_once 'include/utils/utils.php';
    require_once 'modules/PBXManager/utils/AsteriskClass.php';
    require_once 'modules/PBXManager/AsteriskUtils.php';
    $id = $current_user->id;
    $number = $_REQUEST['number'];
    $record = $_REQUEST['recordid'];
    $result = $adb->query("select * from vtiger_asteriskextensions where userid=" . $current_user->id);
    $extension = $adb->query_result($result, 0, "asterisk_extension");
    $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);
    }
    $asterisk = new Asterisk($sock, $server, $port);
    loginUser($username, $password, $asterisk);
    $asterisk->transfer($extension, $number);
    //adds to pbx manager
    addToCallHistory($extension, $extension, $number, "outgoing", $adb);
    // add to the records activity history
    addOutgoingcallHistory($current_user, $extension, $record, $adb);
}
function asterisk_handleResponse3($mainresponse, $adb, $asterisk)
{
    $uid = false;
    $receiver_callerinfo = false;
    // Asterisk 1.4 (Event: Link), Asterisk 1.6 (Event: Bride, Bridgestate: Link)
    if ($mainresponse['Event'] == 'Link' || $mainresponse['Event'] == 'Bridge' && $mainresponse['Bridgestate'] == 'Link') {
        $uid = $mainresponse['Uniqueid1'];
        $uid2 = $mainresponse['Uniqueid2'];
        $callerNumber = $mainresponse['CallerID1'];
        $extensionCalled = $mainresponse['CallerID2'];
        // Ignore the case wheren CallerIDs are same!
        if ($callerNumber == $extensionCalled) {
            // case handled but we ignored.
            return false;
        }
        $callerType = '';
        $status = "received";
        $sourceChannel = $mainresponse['Channel1'];
        // Check if Popup has already been shown to user?
        // Due to (asterisk 1.4 bug: https://issues.asterisk.org/view.php?id=11757)
        // Popup display for Call made to queue is defered and will be handled below
        // So we need to pick up events with (flag = 0, asterisk 1.6) or (flag = -1, asterisk 1.4)
        // asterisk 1.4 - from_number is NULL,
        // TODO check the state of from_number in asterisk 1.6
        $checkres = $adb->pquery("SELECT * FROM vtiger_asteriskincomingevents WHERE uid=? and (flag = 0 or flag = -1) and (from_number is NULL or from_number = 0)", array($uid));
        if ($adb->num_rows($checkres) > 0) {
            if (empty($checkresrow['from_name'])) {
                $checkresrow['from_name'] = "Unknown";
            }
            $checkresrow = $adb->fetch_array($checkres);
            $sql = "UPDATE vtiger_asteriskincomingevents SET from_number=?, to_number=?, timer=?, flag=? WHERE uid=?";
            $adb->pquery($sql, array($callerNumber, $extensionCalled, time(), 0, $uid));
            // Check if the user has checked Incoming Calls in My Preferences
            if (checkExtension($extensionCalled, $adb)) {
                $query = "INSERT INTO vtiger_asteriskincomingcalls (refuid, from_number, from_name, to_number, callertype, flag, timer) VALUES(?,?,?,?,?,?,?)";
                $adb->pquery($query, array($uid, $callerNumber, $checkresrow['from_name'], $extensionCalled, '', 0, time()));
            }
        }
        // END
    } else {
        if ($mainresponse['Event'] == 'Newexten' && $mainresponse['AppData'] == "DIALSTATUS=CONGESTION" || $mainresponse['Event'] == 'Hangup') {
            $status = "missed";
            $uid = $mainresponse['Uniqueid'];
            $extensionCalled = false;
        }
    }
    // TODO Need to detect the caller number using the Event Information
    $callerNumberInfo = $adb->pquery("SELECT from_number, callertype FROM vtiger_asteriskincomingevents WHERE uid=? AND from_number is not NULL LIMIT 1", array($uid));
    if ($callerNumberInfo && $adb->num_rows($callerNumberInfo)) {
        $callerNumber = $adb->query_result($callerNumberInfo, 0, 'from_number');
        $receiver_callerinfo = getCallerInfo($callerNumber);
    }
    if ($uid !== false) {
        // Create Record if not yet done and link to the event for further use
        $eventResult = $adb->pquery("SELECT * FROM vtiger_asteriskincomingevents WHERE uid = ? and pbxrecordid is NULL AND flag =0", array($uid));
        if ($adb->num_rows($eventResult)) {
            $eventResultRow = $adb->fetch_array($eventResult);
            $callerNumber = $eventResultRow['from_number'];
            if ($extensionCalled === false) {
                $extensionCalled = $eventResultRow['to_number'];
            }
            // If we are not knowing the caller informatio (Asterisk 1.4, Event: Link not yet called)
            if ($callerNumber != 'Unknown' && $callerNumber != '0') {
                $pbxrecordid = addToCallHistory($extensionCalled, $callerNumber, $extensionCalled, "incoming-{$status}", $adb, $receiver_callerinfo);
                $adb->pquery("UPDATE vtiger_asteriskincomingevents SET pbxrecordid = ? WHERE uid = ?", array($pbxrecordid, $uid));
                if (!empty($receiver_callerinfo['id'])) {
                    $adb->pquery("UPDATE vtiger_asteriskincomingevents SET relcrmid = ? WHERE uid = ?", array($receiver_callerinfo['id'], $uid));
                }
            }
            return false;
        }
    }
    return true;
}
/**
 * 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"))) {
                $temp = array();
                if (strstr($response['Channel'], $callerNumber)) {
                    $temp = explode("/", $response['Channel']);
                    $callerType = $temp[0];
                }
                $temp = explode("=", $response['AppData']);
                $extension = $temp[1];
                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;
    }
}