예제 #1
0
    function call_2did ($agi, &$RateEngine, $listdestination)
    {
    	$card_number = $this -> username; // username of the caller
        $nbused = $this -> nbused;
		$res = 0;
        $connection_charge = $listdestination[0][8];
        $selling_rate = $listdestination[0][9];

        if ($connection_charge == 0 && $selling_rate == 0) {
    	$call_did_free = true;
		$this -> debug( INFO, $agi, __FILE__, __LINE__, "[A2Billing] DID call free ");
	} else {
		$call_did_free = false;
		$this -> debug( INFO, $agi, __FILE__, __LINE__, "[A2Billing] DID call not free: (connection charge:".$connection_charge."|selling_rate:".$selling_rate );
	}
	
	if (($listdestination[0][2]==0) || ($listdestination[0][2]==2)) {
		$doibill = 1;
	} else {
		$doibill = 0;
	}
		
        if (!$call_did_free) {
			
            if ($this->typepaid == 0) {
                if ($this->credit < $this->agiconfig['min_credit_2call']) {
                	$time2call = 0;
                } else {
					$credit_without_charge = $this->credit - abs($connection_charge);
					if ($credit_without_charge>0 && $selling_rate!=0 ) {
						$time2call = intval($credit_without_charge / abs($selling_rate))*60;
					} else {
						$time2call =  $this->agiconfig['max_call_call_2_did'];
					}
                }
            } else {
				if ($this->credit <= -$this->creditlimit) {
					$time2call =0;
				} else {
					$credit_without_charge = $this->credit + abs($this->creditlimit) - abs($connection_charge);
					if ($credit_without_charge>0 && $selling_rate!=0 ) {
						$time2call = intval($credit_without_charge / abs($selling_rate))*60;
					} else {
						$time2call =  $this->agiconfig['max_call_call_2_did'];
					}
				}
            }
        } else {
            $time2call =$this->agiconfig['max_call_call_2_did'];
        }
        
        $this->timeout = $time2call;
	$callcount = 0;
	$accountcode = $this->accountcode;
	$username = $this->username;
	$useralias = $this->useralias;
	$set_inuse = $this->set_inuse;
	$my_id_card = $this->id_card;
		
	foreach ($listdestination as $inst_listdestination) {

	    $callcount++;
	    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[A2Billing] DID call friend: FOLLOWME=$callcount (cardnumber:".$inst_listdestination[6]."|destination:".$inst_listdestination[4]."|tariff:".$inst_listdestination[3].")\n");
	    $this->agiconfig['cid_enable']			= 0;
	    $this->accountcode= $this->username = $new_username = $inst_listdestination[6];
	    $this->tariff 					= $inst_listdestination[3];
	    $this->destination					= $inst_listdestination[10];
//	    $new_username					= $inst_listdestination[6];
	    $this->useralias					= $inst_listdestination[7];
	    $this->id_card					= $inst_listdestination[28];
	    $this->time_out					= $inst_listdestination[30];
	    $this->id_did					= $inst_listdestination[0];

	    // CHECK IF DESTINATION IS SET
	    if (strlen($inst_listdestination[4])==0)
            	continue;

	    if ($inst_listdestination[29]) {
		if (array_search($agi -> channel_status('',true), array(AST_STATE_UP, AST_STATE_DOWN)) === false) $this -> let_stream_listening($agi, true);
		$agi -> evaluate("STREAM FILE $inst_listdestination[29] \"#\" 0");
	    }

            // IF call on did is not free calculate time to call
            
            // IF VOIP CALL
            if ($inst_listdestination[5]==1) {
				
                // RUN MIXMONITOR TO RECORD CALL
		if ($this->monitor == 1 || $this->agiconfig['record_call'] == 1) {
					$this->dl_short = MONITOR_PATH . "/" . $this->username . "/" . date('Y') . "/" . date('n') . "/" . date('j') . "/";
					$command_mixmonitor = "MixMonitor ". $this->dl_short ."{$this->uniqueid}.{$this->agiconfig['monitor_formatfile']}|b";
					$command_mixmonitor = $this -> format_parameters ($command_mixmonitor);
					$myres = $agi->exec($command_mixmonitor);
					$this -> debug( INFO, $agi, __FILE__, __LINE__, $command_mixmonitor);
		}
				
		$max_long = 36000000; //Maximum 10 hours
		$dialstr = $inst_listdestination[4];
		if ($call_did_free) {
		    $this -> fct_say_time_2_call($agi,$time2call,0);
		    $dialparams = $this->agiconfig['dialcommand_param_call_2did'];

                } else {
		    $this -> debug( INFO, $agi, __FILE__, __LINE__, "TIME TO CALL : $time2call");
		    $this -> fct_say_time_2_call($agi,$time2call,$selling_rate);
		    $dialparams = $this->agiconfig['dialcommand_param'];
                }
		if (stripos($dialstr,"QUEUE ") !== 0) {
		    $dialparams = str_replace("%timeout%", min($time2call * 1000, $max_long), $dialparams);
		    $dialstr .= str_replace("%timeoutsec%", min($time2call, $max_long), $dialparams);
		}
		if ($call_did_free) $this -> debug( DEBUG, $agi, __FILE__, __LINE__, "[A2Billing] DID call friend: Dialing '$dialstr' Friend.\n");

		if ($agi -> channel_status('',true) == AST_STATE_DOWN) break;
                $myres = $this -> run_dial($agi, $dialstr);
                $this -> debug( INFO, $agi, __FILE__, __LINE__, "DIAL $dialstr");

		$answeredtime			= $agi->get_variable("ANSWEREDTIME", true);
		if ($answeredtime == "")
				  $answeredtime = $agi->get_variable("CDR(billsec)",true);
		if (stripos($dialstr,'QUEUE ') === 0) {
			if ($answeredtime>1356000000) {
				$answeredtime	= time() - $answeredtime;
				$dialstatus	= 'ANSWER';
			} else {
				$answeredtime	= 0;
				$dialstatus	= $this -> get_dialstatus_from_queuestatus($agi);
			}
		} else		$dialstatus	= $agi->get_variable("DIALSTATUS", true);

		if ($this->monitor == 1 || $this -> agiconfig['record_call'] == 1) {
                    $myres = $agi->exec($this -> format_parameters ("StopMixMonitor"));
                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "EXEC StopMixMonitor (".$this->uniqueid.")");
                }

                $this -> debug( INFO, $agi, __FILE__, __LINE__, "[".$inst_listdestination[4]." Friend][followme=$callcount]:[ANSWEREDTIME=".$answeredtime."-DIALSTATUS=".$dialstatus."]");

                //# Ooh, something actually happend!
                if ($dialstatus == "BUSY") {
					$answeredtime = 0;
					if ($this->agiconfig['busy_timeout'] > 0)
						$res_busy = $agi->exec("Busy ".$this->agiconfig['busy_timeout']);
					if (array_search($agi -> channel_status('',true), array(AST_STATE_UP, AST_STATE_DOWN)) === false) $this -> let_stream_listening($agi);
					$agi-> stream_file('prepaid-isbusy', '#');
					if (count($listdestination)>$callcount)
						continue;
                } elseif ($dialstatus == "NOANSWER") {
					$answeredtime = 0;
					if (array_search($agi -> channel_status('',true), array(AST_STATE_UP, AST_STATE_DOWN)) === false) $this -> let_stream_listening($agi);
					$agi-> stream_file('prepaid-noanswer', '#');
					if (count($listdestination) > $callcount)
						continue;
                } elseif ($dialstatus == "CANCEL") {
					// Call cancelled, no need to follow-me
//					return 1;
					$answeredtime = 0;
                } elseif ($dialstatus == "ANSWER") {
					$this -> debug( DEBUG, $agi, __FILE__, __LINE__,
									"[A2Billing] DID call friend: dialstatus : $dialstatus, answered time is ".$answeredtime." \n");
                } elseif (($dialstatus  == "CHANUNAVAIL") || ($dialstatus  == "CONGESTION")) {
					$answeredtime = 0;
					if (count($listdestination)>$callcount) continue;
                } else {
		    if (array_search($agi -> channel_status('',true), array(AST_STATE_UP, AST_STATE_DOWN)) === false) $this -> let_stream_listening($agi);
                    $agi-> stream_file('prepaid-callfollowme', '#');
                    if (count($listdestination)>$callcount) continue;
                }

                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - LOG CC_CALL: FOLLOWME=$callcount - (answeredtime=$answeredtime :: dialstatus=$dialstatus :: call_did_free=$call_did_free)]");

                    if (strlen($this -> dialstatus_rev_list[$dialstatus])>0) {
						$terminatecauseid = $this -> dialstatus_rev_list[$dialstatus];
                    } else {
						$terminatecauseid = 0;
                    }
		    if ($answeredtime == 0) $inst_listdestination[10] = $this -> realdestination;
		    elseif (strpos($dialstr,'&') || strpos($dialstr,'@') || stripos($dialstr,'QUEUE ') === 0) {
			$dialedpeernumber = $agi -> get_variable('QUEUEDNID',true);
			if (!$dialedpeernumber) $dialedpeernumber = $agi -> get_variable('DIALEDPEERNUMBER',true);
			$inst_listdestination[10] = preg_replace("|\D|", "", $dialedpeernumber);
			$this -> debug( INFO, $agi, __FILE__, __LINE__, "Destination: " . $inst_listdestination[10]);
		    }

		    if (!isset($this->card_caller)) $this->card_caller = $my_id_card;

                    // User ONNet use $this->id_card

                    // A-LEG below to the owner of the DID
                    if ($call_did_free || $answeredtime == 0) {
                    	//CALL2DID CDR is free
	                    /* CDR A-LEG OF DID CALL */
	                    $QUERY = "INSERT INTO cc_call (uniqueid, sessionid, card_id, card_caller, nasipaddress, starttime, sessiontime, calledstation, ".
	                            " terminatecauseid, stoptime, sessionbill, id_tariffgroup, id_tariffplan, id_ratecard, id_trunk, src, sipiax, id_did, dnid) VALUES ".
	                            "('".$this->uniqueid."', '".$this->channel."',  '".$my_id_card."',  '".$this->card_caller."', '".$this->hostname."',";
	                    $QUERY .= " CURRENT_TIMESTAMP - INTERVAL $answeredtime SECOND ";
	                    $QUERY .= ", '$answeredtime', '".$inst_listdestination[10]."', '$terminatecauseid', now(), '0', '0', '0', '0', '0', '$this->CallerID', '3', '$this->id_did', '$this->destination')";

	                    $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
	                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - LOG CC_CALL: SQL: $QUERY]:[result:$result]");

	                    if ($dialstatus == "CANCEL") {
	                        $this->username = $username;
	                        return 1;
	                    }
                    } else {
                    	//CALL2DID CDR is not free
                        $cost = ($answeredtime/60) * abs($selling_rate) + abs($connection_charge);
                        
                        /* CDR A-LEG OF DID CALL */
                        $QUERY = "INSERT INTO cc_call (uniqueid, sessionid, card_id, card_caller, nasipaddress, starttime, sessiontime, calledstation, ".
                                " terminatecauseid, stoptime, sessionbill, id_tariffgroup, id_tariffplan, id_ratecard, id_trunk, src, sipiax, id_did, dnid) VALUES ".
                                "('".$this->uniqueid."', '".$this->channel."',  '".$my_id_card."', '".$this->card_caller."', '".$this->hostname."',";
                        $QUERY .= " CURRENT_TIMESTAMP - INTERVAL $answeredtime SECOND ";
                        $QUERY .= ", '$answeredtime', '". $listdestination[0][10]."', '$terminatecauseid', now(), '$cost', '0', '0', '0', '0', '$this->CallerID', '3', '$this->id_did', '$this->destination')";

                        $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
                        $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - LOG CC_CALL: SQL: $QUERY]:[result:$result]");

                        // Update the account
                        if ($nbused > 0) {
                            $firstuse = "";
                        } else {
                            $firstuse = "firstusedate=now(),";
                        }
                        $QUERY = "UPDATE cc_card SET credit= credit - ".a2b_round(abs($cost))." ,  lastuse=now(),$firstuse nbused=nbused+1 WHERE username='******'";
                        $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
                        $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - UPDATE CARD: SQL: $QUERY]:[result:$result]");
                    }
                    
                    // CC_DID & CC_DID_DESTINATION - cc_did.id, cc_did_destination.id
                    $QUERY = "UPDATE cc_did SET secondusedreal = secondusedreal + $answeredtime WHERE id='$this->id_did'";
                    $result = $this->instance_table -> SQLExec ($this -> DBHandle, $QUERY, 0);
                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[UPDATE DID]:[result:$result]");

                    $QUERY = "UPDATE cc_did_destination SET secondusedreal = secondusedreal + $answeredtime WHERE id='".$inst_listdestination[1]."'";
                    $result = $this->instance_table -> SQLExec ($this -> DBHandle, $QUERY, 0);
                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[UPDATE DID_DESTINATION]:[result:$result]");

                    monitor_recognize($this);
                    
                    #This is a call from user to DID
                    #we will change the B-Leb using the did bill_did_aleg function
                    $this -> bill_did_aleg ($agi, $listdestination[0], $answeredtime);

            // ELSEIF NOT VOIP CALL
            } else {

                $this->agiconfig['use_dnid'] = 1;
                $this->agiconfig['say_timetocall'] = 0;

                $this->dnid = $this->destination;
                $this->extension = $this->destination = $inst_listdestination[4];
                if ($this->CC_TESTING) $this->extension = $this->dnid = $this->destination = "011324885";
				
                if ($this -> callingcard_ivr_authorize($agi, $RateEngine, 0)==1) {
		// check the min to call
		    if (!$call_did_free) {
			$this->timeout= min($this->timeout,$time2call);
		    }
		    $this -> fct_say_time_2_call($agi, $this->timeout,$selling_rate);
		    if ($agi -> channel_status('',true) == AST_STATE_DOWN) break;
                    // PERFORM THE CALL
                    $result_callperf = $RateEngine->rate_engine_performcall ($agi, $this -> destination, $this);
                    if (!$result_callperf && count($listdestination) == $callcount) {
	                    $prompt="prepaid-callfollowme";
	                    $agi-> stream_file($prompt, '#');
                    }

                    $dialstatus = $RateEngine->dialstatus;
                    $answeredtime = $RateEngine->answeredtime;
                    if ((($dialstatus == "NOANSWER") || ($dialstatus == "BUSY") ||
                            ($dialstatus == "CHANUNAVAIL") || ($dialstatus == "CONGESTION")) && count($listdestination) > $callcount) continue;
		    if ($dialstatus != "ANSWER") $this -> destination = $this -> realdestination;
					
                    // INSERT CDR  & UPDATE SYSTEM
                    $RateEngine->rate_engine_updatesystem($this, $agi, $this-> destination, $doibill, 2);
                    if ($dialstatus == "CANCEL") break;
                    if (!$result_callperf) continue;
                    
                    // CC_DID & CC_DID_DESTINATION - cc_did.id, cc_did_destination.id
                    $QUERY = "UPDATE cc_did SET secondusedreal = secondusedreal + ".$answeredtime." WHERE id='$this->id_did'";
                    $result = $this->instance_table -> SQLExec ($this -> DBHandle, $QUERY, 0);
                    $this -> debug( DEBUG, $agi, __FILE__, __LINE__, "[UPDATE DID]:[result:$result]");

                    $QUERY = "UPDATE cc_did_destination SET secondusedreal = secondusedreal + ".$answeredtime." WHERE id='".$inst_listdestination[1]."'";
                    $result = $this->instance_table -> SQLExec ($this -> DBHandle, $QUERY, 0);
                    $this -> debug( DEBUG, $agi, __FILE__, __LINE__, "[UPDATE DID_DESTINATION]:[result:$result]");

                    // THEN STATUS IS ANSWER
                    // UPDATE CDR
                     //CALL2DID CDR is not free
		    if ($nbused>0) {
                            $firstuse= "";
                    } else {
                           $firstuse= "firstusedate=now(),";
                    }
                    if (!$call_did_free) {
                        $cost = a2b_round(abs(($answeredtime/60) * abs($selling_rate) + abs($connection_charge)));

                        //update card
                        $QUERY = "UPDATE cc_call SET sessionbill = sessionbill + $cost, calledstation = ".$listdestination[0][10]." WHERE uniqueid=$this->uniqueid";

                        $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
                        $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - LOG CC_CALL: SQL: $QUERY]:[result:$result]");
                        $QUERY = "UPDATE cc_card SET credit= credit - $cost, lastuse=now(),$firstuse nbused=nbused+1 WHERE username='******'";
                        $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
                        $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - UPDATE CARD: SQL: $QUERY]:[result:$result]");
                    }

                    $QUERY = "UPDATE cc_card SET credit= credit - ".a2b_round(abs($cost))." ,  lastuse=now(),$firstuse nbused=nbused+1 WHERE username='******'";
                    $result = $this -> instance_table -> SQLExec ($this->DBHandle, $QUERY, 0);
                    $this -> debug( INFO, $agi, __FILE__, __LINE__, "[DID CALL - UPDATE CARD: SQL: $QUERY]:[result:$result]");
                    
                    
                    #This is a call from user to DID, we dont want to charge the A-leg
                    $this -> bill_did_aleg ($agi, $listdestination[0], $answeredtime);
                    
                    break;
                }
            }
		}// END FOR

		if ($this->voicemail) {
			if (($dialstatus =="CHANUNAVAIL") || ($dialstatus == "CONGESTION") || ($dialstatus == "NOANSWER") || ($dialstatus =="BUSY")) {
				// The following section will send the caller to VoiceMail with the unavailable priority.\
				$dest_username = $new_username;
				$this -> debug( INFO, $agi, __FILE__, __LINE__, "[STATUS] CHANNEL ($dialstatus) - GOTO VOICEMAIL ($dest_username)");
				
				$vm_parameters = $this -> format_parameters ($dest_username.'|s');
				$agi-> exec(VoiceMail, $vm_parameters);
			}
		}
		$this->accountcode = $accountcode;
		$this->username = $username;
		$this->useralias = $useralias;
		$this->set_inuse = $set_inuse;
		$this->id_card = $my_id_card;
	}
예제 #2
0
	function rate_engine_updatesystem (&$A2B, &$agi, $calledstation, $doibill = 1, $didcall=0, $callback=0, $trunk_id=0, $td=NULL)
	{
		$K = $this->usedratecard;
		
		// ****************  PACKAGE PARAMETERS ****************
		if (count($this -> ratecard_obj)>0) {
			$id_cc_package_offer = $this -> ratecard_obj[$K][45];
			$additional_grace_time = $this -> ratecard_obj[$K][58];
		} else $id_cc_package_offer = 'NONE';
		
		$id_card_package_offer = null;
		
		if ($A2B -> CC_TESTING) {
			$sessiontime = 120;
			$dialstatus = 'ANSWERED';
		} else {
			$sessiontime = $this -> answeredtime;
			$dialstatus = $this -> dialstatus;
		}

		$A2B -> debug( INFO, $agi, __FILE__, __LINE__, ":[sessiontime:$sessiontime - id_cc_package_offer:$id_cc_package_offer - package2apply:".$this ->package_to_apply[$K]."]\n\n");
		
		if ($sessiontime > 0) {
			// HANDLE FREETIME BEFORE CALCULATE THE COST
			$this -> freetimetocall_used = 0;
			if ($this -> debug_st) print_r($this -> freetimetocall_left[$K]);

			if (($id_cc_package_offer!=-1) && ($this ->package_to_apply[$K] !=null )) {
				$id_package_offer = $this ->package_to_apply[$K]["id"];
	
                switch ($this -> package_to_apply[$K]["type"]) {
                	//Unlimited
                	case 0 : 
        				$this->freetimetocall_used = $sessiontime;
        				break;
                	//free calls
                	case 1 : 
        				$this->freetimetocall_used = $sessiontime;
        				break;
                	//free minutes
                	case 2 :
						if ($this -> freetimetocall_left[$K] >= $sessiontime) {
							$this->freetimetocall_used = $sessiontime;
						} else {
							$this->freetimetocall_used = $this -> freetimetocall_left[$K];
						}
						break;
                }
				$this -> rate_engine_calculcost ($A2B, $sessiontime, 0);
				// rate_engine_calculcost could have change the duration of the call
				$sessiontime = $this -> answeredtime;
				
				// add grace time
				if ($sessiontime>0 && $additional_grace_time>0) {
					$sessiontime = $sessiontime + $additional_grace_time;
				}

				$QUERY_FIELS = 'id_cc_card, id_cc_package_offer, used_secondes';
				$QUERY_VALUES = "'".$A2B -> id_card."', '$id_package_offer', '$this->freetimetocall_used'";
				$id_card_package_offer = $A2B -> instance_table -> Add_table ($A2B -> DBHandle, $QUERY_VALUES, $QUERY_FIELS, 'cc_card_package_offer', 'id');
				$A2B -> debug( INFO, $agi, __FILE__, __LINE__, ":[ID_CARD_PACKAGE_OFFER CREATED : $id_card_package_offer]:[$QUERY_VALUES]\n\n\n\n");
				
			} else {
				
				$this -> rate_engine_calculcost ($A2B, $sessiontime, 0);
				// rate_engine_calculcost could have change the duration of the call
				
				$sessiontime = $this -> answeredtime;
				if ($sessiontime > 0 && $additional_grace_time > 0) {
					$sessiontime = $sessiontime + $additional_grace_time;
				}
			}
			
		} else {
			$sessiontime = 0;
		}
		if (count($this -> ratecard_obj)>0) {
			$calldestination = $this -> ratecard_obj[$K][5];
			$id_tariffgroup  = $this -> ratecard_obj[$K][2];
			$id_tariffplan	 = $this -> ratecard_obj[$K][3];
			$id_ratecard	 = $this -> ratecard_obj[$K][6];
			$buyrateapply	 = $this -> ratecard_obj[$K][9];
			$rateapply	 = $this -> ratecard_obj[$K][12];
		}
		$buycost = 0;
		if ($doibill==0 || $sessiontime < $A2B->agiconfig['min_duration_2bill']) {
			$cost = 0;
			$buycost = abs($this -> lastbuycost);
		} else {
			$cost = $this -> lastcost;
			$buycost = abs($this -> lastbuycost);
		}

		if ($cost<0) {
			$signe = '-';
			$signe_cc_call = '+';
		} else {
			$signe = '+';
			$signe_cc_call = '-';
		}

		$A2B -> debug( DEBUG, $agi, __FILE__, __LINE__, "[CC_RATE_ENGINE_UPDATESYSTEM: usedratecard K=$K - (sessiontime=$sessiontime :: dialstatus=$dialstatus :: buycost=$buycost :: cost=$cost : signe_cc_call=$signe_cc_call: signe=$signe)]");

		if (strlen($this -> dialstatus_rev_list[$dialstatus]) > 0) {
			$terminatecauseid = $this -> dialstatus_rev_list[$dialstatus];
        } else {
			$terminatecauseid = 0;
        }

        // CALLTYPE -  0 = NORMAL CALL ; 1 = VOIP CALL (SIP/IAX) ; 2= DIDCALL + TRUNK ; 3 = VOIP CALL DID ; 4 = CALLBACK call
        if ($didcall == 3) {
			$calltype = $didcall;
        } elseif ($didcall) {
			$calltype = 2;
        } elseif ($callback) {
			$calltype = 4;
		$terminatecauseid = 1;
        } elseif ($A2B->recalltime) {
			$calltype = 5;
        } else {
			$calltype = 0;
        }

		$card_id =  (!is_numeric($A2B->id_card)) ? '-1' : "'". $A2B->id_card ."'";
		$real_sessiontime = (!is_numeric($this->real_answeredtime)) ? 'NULL' : "'". $this->real_answeredtime ."'";
		$id_tariffgroup = (!isset($id_tariffgroup) || !is_numeric($id_tariffgroup)) ? 'NULL' : "'$id_tariffgroup'";
		$id_tariffplan = (!isset($id_tariffplan) || !is_numeric($id_tariffplan)) ? 'NULL' : "'$id_tariffplan'";
		$id_ratecard = (!isset($id_ratecard) || !is_numeric($id_ratecard)) ? 'NULL' : "'$id_ratecard'";
		$trunk_id =  ($trunk_id) ? "'". $trunk_id ."'" : "'". $this->usedtrunk ."'";
		$id_card_package_offer = (!is_numeric($id_card_package_offer)) ? 'NULL' : "'$id_card_package_offer'";
		$calldestination = (!isset($calldestination) || !is_numeric($calldestination) || ($didcall && $dialstatus != 'ANSWERED')) ? -1 : $calldestination;
		$card_caller = (isset($A2B->card_caller)) ? "'$A2B->card_caller'" : "'0'";
		$id_did = (!isset($A2B->id_did) || !is_numeric($A2B->id_did)) ? 'NULL' : "'$A2B->id_did'";

		$QUERY_COLUMN = "uniqueid, sessionid, card_id, card_caller, nasipaddress, starttime, sessiontime, real_sessiontime, calledstation, ".
			" terminatecauseid, stoptime, sessionbill, id_tariffgroup, id_tariffplan, id_ratecard, " .
			" id_trunk, src, sipiax, buycost, id_card_package_offer, dnid, destination, id_did";
		$QUERY = "INSERT INTO cc_call ($QUERY_COLUMN) VALUES ('".$A2B->uniqueid."', '".$A2B->channel."', ".
			"$card_id, $card_caller, '".$A2B->hostname."', ";

		if ($A2B->config["global"]['cache_enabled']) {
			$QUERY .= " datetime( strftime('%s','now') - $sessiontime, 'unixepoch','localtime')";	
		} else {
			$QUERY .= "SUBDATE(CURRENT_TIMESTAMP, INTERVAL $sessiontime SECOND) ";
		}

		$QUERY .= 	", '$sessiontime', $real_sessiontime, '$calledstation', $terminatecauseid, ";
		if ($A2B->config["global"]['cache_enabled']) {
			$QUERY .= "datetime('now','localtime')";
		} else {
			$QUERY .= "now()";
		}

		$QUERY .= " , '$signe_cc_call".a2b_round(abs($cost))."', ".
					" $id_tariffgroup, $id_tariffplan, $id_ratecard, $trunk_id, '".$A2B->CallerID."', '$calltype', ".
					" '$buycost', $id_card_package_offer, '".$A2B->dnid."', $calldestination, $id_did)";

		if ($A2B->config["global"]['cache_enabled']) {
			 //insert query in the cache system
			$create = false;
			if (! file_exists( $A2B -> config["global"]['cache_path']))
				$create = true;
			if ($db = sqlite_open($A2B -> config["global"]['cache_path'], 0666, $sqliteerror)) {
			    if ($create)
					sqlite_query($db,"CREATE TABLE cc_call ($QUERY_COLUMN)");
			    sqlite_query($db,$QUERY);
			    sqlite_close($db);
			} else {
				$A2B -> debug( ERROR, $agi, __FILE__, __LINE__, "[Error to connect to cache : $sqliteerror]\n");
			}
		} else {
			$result = $A2B->instance_table -> SQLExec ($A2B -> DBHandle, $QUERY, 0);
			$A2B -> debug( INFO, $agi, __FILE__, __LINE__, "[CC_asterisk_stop : SQL: DONE : result=".$result."]");
			$A2B -> debug( DEBUG, $agi, __FILE__, __LINE__, "[CC_asterisk_stop : SQL: $QUERY]");
		}
		if ($sessiontime>0) {
			
			if (!isset($td)) $td = (isset($this->td))?$this->td:"";
			if ($didcall==0 && $callback==0) {
				$myclause_nodidcall = " , redial='".$calledstation."' ";
			} else {
				$myclause_nodidcall='';
			}
			
			if (!defined($myclause_nodidcall)) {
				$myclause_nodidcall = null;
			}
			//Update the global credit
			$A2B -> credit = $A2B -> credit + $cost;
			
			if ($A2B->nbused>0) {
				$QUERY = "UPDATE cc_card SET credit= credit$signe".a2b_round(abs($cost))." $myclause_nodidcall,  lastuse=now(), nbused=nbused+1 WHERE username='******'";
			} else {
				$QUERY = "UPDATE cc_card SET credit= credit$signe".a2b_round(abs($cost))." $myclause_nodidcall,  lastuse=now(), firstusedate=now(), nbused=nbused+1 WHERE username='******'";
			}
			
			$A2B -> debug( DEBUG, $agi, __FILE__, __LINE__, "[CC_asterisk_stop 1.2: SQL: $QUERY]");
			$result = $A2B->instance_table -> SQLExec ($A2B -> DBHandle, $QUERY, 0);

			$QUERY = "SELECT period$td, UNIX_TIMESTAMP(periodexpiry$td), periodcount$td FROM cc_trunk WHERE id_trunk=$trunk_id LIMIT 1";
			$result = $A2B->instance_table -> SQLExec ($A2B -> DBHandle, $QUERY);
			if (is_array($result) && count($result)>0) {
				$QUERY = "UPDATE cc_trunk SET secondusedreal = secondusedreal + $sessiontime, periodcount$td = ";
				$tqr = " / billblocksec$td) * billblocksec$td, lastcallstoptime$td=now()";
				$tqrperiod = ", periodexpiry$td = ";
				$period		= $result[0][0];
				$periodexpiry	= $result[0][1];
				$periodcount	= $result[0][2];
				if ($period == 31) {
				    if ($periodexpiry <= time()) {
					while ($periodexpiry <= time()) {
					    $preperiodexpiry = $periodexpiry;
					    $periodexpiry = strtotime('1 month', $periodexpiry);
					    $periodcount = 0;
					}
				    } else $preperiodexpiry = strtotime('-1 month', $periodexpiry);
				    $tqr .= $tqrperiod . "FROM_UNIXTIME($periodexpiry) ";
				} else {
				    $period *= 86400;
				    if ($period>1) {
					if ($periodexpiry <= time()) {
					    while ($periodexpiry <= time()) $periodexpiry += 86400;
					    $periodexpiry += $period - 86400;
					    $periodcount = 0;
					}
					$tqr .= $tqrperiod . "FROM_UNIXTIME($periodexpiry) ";
				    }
				$preperiodexpiry = $periodexpiry - $period;
				}
				if (time()-$sessiontime <= $preperiodexpiry && $period > 1 ) {
					$limitsessiontime = time() - $preperiodexpiry;
				} else {
					$limitsessiontime = $sessiontime;
				}
				$QUERY .= "$periodcount + ceil($limitsessiontime" . $tqr . "WHERE id_trunk=$trunk_id";
			} else $QUERY = "UPDATE cc_trunk SET secondusedreal = secondusedreal + $sessiontime WHERE id_trunk=$trunk_id";
			$A2B -> debug( DEBUG, $agi, __FILE__, __LINE__, $QUERY);
			$result = $A2B->instance_table -> SQLExec ($A2B -> DBHandle, $QUERY, 0);

			$QUERY = "UPDATE cc_tariffplan SET secondusedreal = secondusedreal + $sessiontime WHERE id=$id_tariffplan";
			$A2B -> debug( DEBUG, $agi, __FILE__, __LINE__, $QUERY);
			$result = $A2B->instance_table -> SQLExec ($A2B -> DBHandle, $QUERY, 0);
		}
		monitor_recognize($A2B);
	}