<?php
### DO THIS FIRST:
    
require_once("/BANGK!/master_config.php");
require_once($master_config_root_path . "shared/functions.shared");
require_once($master_config_root_path . "shared/session.shared");

//test('_SERVER', $_SERVER);

logger3("




#################################
### NEW SESSION: BANGK!/gateway/over_browser_audio_management.inc:

",$x);

if(!is_array($_SESSION['authorization'])) $_SESSION['authorization'] = array();


//EMAIL UPDATE LINK
if(isset($_GET['action'])){
    if($_GET['action'] == 'emailUpdateLink'){
        echo emailBiometricUpdateLink();        
        exit;
    }
}



//$blob = $_REQUEST['blob'];
$_REQUEST['ext'] = '.wav';
$ext = $_REQUEST['ext'];
logger3("ext",$ext);

$type = $_REQUEST['type'];
logger3("type",$type);

//$rootpath = '../uploads/';
$rnd = md5(time().uniqid());
$filename_without_ext = hash_me(); // $rnd . '_' . time();
$_SESSION['vocapass']['filename'] = '../link_www/audio_recorder/recordings/' . $filename_without_ext;
$filename = $filename_without_ext . $ext;

//file_put_contents($filename, $blob);
//test('_FILES', $_FILES);

//$str = file_get_contents('php://input');

$target_path = $master_config_root_path."www/audio_recorder/recordings/";

$result = "fail";

$uploaded = false;
if(isset($_FILES['file']) and !$_FILES['file']['error']) {    
    move_uploaded_file($_FILES['file']['tmp_name'],  $target_path.$filename);
}
else if(stristr($_SESSION['incoming_api_session']['VOICE_SOURCE'],"https://")){
    //AUDIO FROM URL
    $remote_url = $_SESSION['incoming_api_session']['VOICE_SOURCE']; // Any remote url with direct file path
    logger3('remote_url', $remote_url);
    
    $content = get_headers($remote_url,1);
    $content = array_change_key_case($content, CASE_LOWER);
    if ($content['content-disposition']) {
        $tmp_name = explode('=', $content['content-disposition']);
        if ($tmp_name[1]) 
            $realfilename = trim($tmp_name[1],'";\'');
    } else  
    {
        $stripped_url = preg_replace('/\\?.*/', '', $remote_url);
        $realfilename = basename($stripped_url);
    } 
    $tmp_name = explode('.', $realfilename);
    $ext1 = $tmp_name[count($tmp_name)-1];
    $local_file_path = $target_path.$filename_without_ext.'.'.$ext1;
    
    $remote_file_contents = file_get_contents($remote_url );    
    logger3('local_file_path', $local_file_path);
    $audio_copied = file_put_contents($local_file_path, $remote_file_contents);
}
else{
    $content = file_get_contents('php://input');
    $fh = fopen($target_path.$filename, 'w');
    fwrite($fh, $content);
    fclose($fh);
}
if(file_exists($target_path.$filename)) $uploaded = true;

logger3("uploaded",$uploaded);

if($uploaded) {   
    $audio_filename = $filename;
    $ip = $_SESSION['incoming_api_session']['CUSTOMER_IP'];// $_SERVER['REMOTE_ADDR'];
    $telephone_number = '';

    if(stristr($_SESSION['voice_authorization_api'][authorization_template_details][template_name],"BIOMETRIC ENROLLMENT")) {
        $_SESSION['vocapass']['base_audio']['filename'] = $filename;
        $_SESSION['vocapass']['base_audio']['source'] = "RECORDED";
 

        $converted_filename = convert_audio_to_alaw($audio_filename,$path_to_audio=$target_path);
        logger3("converted_filename",$converted_filename);

        $_SESSION['vocapass']['base_audio']['vocamatch_audio_id'] = add_vocamatch_audio($audio_filename=$converted_filename,$ip,$telephone_number);
        logger3("_SESSION['vocapass']['base_audio']['vocamatch_audio_id']",$_SESSION['vocapass']['base_audio']['vocamatch_audio_id']);

        $_SESSION['vocapass']['base_audio']['biometric_registration_status'] = biometric_registration_vocamatch_RECORDED($_SESSION['vocapass']['base_audio']['vocamatch_audio_id'],$voice_file_type="BASE");
        logger3("_SESSION['vocapass']['base_audio']['biometric_registration_status']",$_SESSION['vocapass']['base_audio']['biometric_registration_status']);

        //add customer emailaddress into B!->email_addresses        
        $biometric_id = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
        $emailaddress = $_SESSION['session']['biometric_registration_session']['emailaddress'];
        //addEmailAddress($biometric_id, $emailaddress, $status='VERIFIED');        

        if(stristr($_SESSION['vocapass']['base_audio']['biometric_registration_status'],"INSUFFICIENT AUDIO")){
            echo $_SESSION['vocapass']['base_audio']['biometric_registration_status'];
            silentPost($action="BiometricEnrollment", $status=strtoupper($_SESSION['vocapass']['base_audio']['biometric_registration_status']));           
            exit;
        }        
        silentPost($action="BiometricEnrollment", $status="APPROVED");
        updateBiometricStatus($voiceprintid=$_SESSION['vocapass']['base_audio']['biometric_registration_status'], $status="APPROVED");
        
        //echo $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
        echo "Request Received";
        
        #################################
        #CREATE ACCOUNT AND MEMBER RECORD
        #################################        
        include($_SESSION['template']['company']['file_path'] . "www/audio_recorder/save_member_account.php");                        
        exit;       
    }

    ################################
    #Biometric Verification
    ################################
    
    if(stristr($_SESSION['voice_authorization_api'][authorization_template_details][template_name],"Biometric Verification")
            ||
            stristr($_SESSION['voice_authorization_api'][authorization_template_details][template_name],"Biometric Passphrase Verification")) {
        $_SESSION['vocapass']['comparison_audio']['filename'] = $filename;
        $_SESSION['vocapass']['comparison_audio']['source'] = "RECORDED";


        $converted_filename = convert_audio_to_alaw($audio_filename,$path_to_audio=$target_path);
        $_SESSION['vocapass']['comparison_audio']['vocamatch_audio_id'] = add_vocamatch_audio($audio_filename=$converted_filename,$ip,$telephone_number);

		//logger3("",$);
        logger3("1. _SESSION['vocapass']['comparison_audio']['vocamatch_audio_id']",$_SESSION['vocapass']['comparison_audio']['vocamatch_audio_id']);
        $_SESSION['vocapass']['comparison_audio']['biometric_registration_status'] = biometric_registration_vocamatch_RECORDED($_SESSION['vocapass']['comparison_audio']['vocamatch_audio_id'], $voice_file_type="COMPARISON");


        if(stristr($_SESSION['vocapass']['comparison_audio']['biometric_registration_status'],"INSUFFICIENT AUDIO")) {
            echo $_SESSION['vocapass']['comparison_audio']['biometric_registration_status'];
            silentPost($action="BiometricVerification", $status= strtoupper($_SESSION['vocapass']['comparison_audio']['biometric_registration_status']));
            exit;
        }

        //compare biometrics
        //BUSINESS_PERMANENT_UUID = '".$_SESSION['voice_authorization_api']['ACCOUNT_NUMBER']."' and 
        $query = "select vocamatch_audio_id, voiceprintid from voiceprints where CUSTOMER_BIOMETRIC_ID = '".$_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID']."' and (description = 'Registration' or description='UpdatePassword' or description='PasswordReset') and (biometric_status='APPROVED' or biometric_status='') order by voiceprintid desc ";
        logger3("query",$query);
        //$voiceprints = readTHECASHIER($query);
        $result = "DOES NOT MATCH";
        logger3("2. result",$result);
        $voiceprints = readarrayTHECASHIER($query);
        logger3("voiceprints",$voiceprints);        
        
        //BASE voiceprint
        $voiceprintids = array();
        foreach ($voiceprints as $key => $vocaprint) {
            $voiceprintids[] = $vocaprint['voiceprintid'];
        }
        //test('voiceprintids', $voiceprintids);
        // GET COMPARISON VOCAMATCH DETAILS
        $comparison_vocamatch_audio_id = $_SESSION['vocapass']['comparison_audio']['vocamatch_audio_id'];
        $tmp_sql = "SELECT * FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $comparison_vocamatch_audio_id . "';";
        //test("tmp_sql",$tmp_sql);
        $comparison_audio_details = readTHECASHIER($tmp_sql);
        //test('comparison_audio_details', $comparison_audio_details);
        $filenames = array();
        $filenames[] = $comparison_audio_details->audio_filename;
        $check_type = $_SESSION['voice_authorization_api'][authorization_template_details][template_name];
        $siv_tolerance = get_siv_tolerance();
        logger3("login: siv_tolerance",$siv_tolerance);
        $result = check_biometrics_now($check_type, $filenames, $voiceprintids, $tolerance = $siv_tolerance);
        
        $_SESSION['vocapass']['comparison_audio']['biometric_results'] = $result;
        logger3("login: _SESSION['vocapass']['comparison_audio']['biometric_results']",$_SESSION['vocapass']['comparison_audio']['biometric_results']);

        $login_status = 'rejected';
        if($result=='MATCHES') $login_status = 'approved';            
        silentPost($action="BiometricVerification", $status=  strtoupper($login_status));
        updateBiometricStatus($voiceprintid=$_SESSION['vocapass']['comparison_audio']['biometric_registration_status'], $status=strtoupper($login_status));
        
        echo "Request Received";
        
        /*
        if($login_status == 'approved'){
            echo strtoupper($login_status);
        }
        else {
            //function generate_vocapass_update_pin($MEMBER_BIOMETRIC_ID,$VOICE_AUTHORIZATION_CATEGORY,$voiceprintid)
            echo 'UPDATE:'. generate_vocapass_update_pin($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'], $VOICE_AUTHORIZATION_CATEGORY="UPDATE", $voiceprintid=$_SESSION['vocapass']['comparison_audio']['biometric_registration_status']);
        }
         
         */
        exit;

    }
    
    ################################
    #Biometric Password Update
    ################################
    
    if(stristr($_SESSION['voice_authorization_api'][authorization_template_details][template_name],"Biometric Password Update")) {
        $_SESSION['vocapass']['base_audio']['filename'] = $filename;
        $_SESSION['vocapass']['base_audio']['source'] = "RECORDED";
 

        $converted_filename = convert_audio_to_alaw($audio_filename,$path_to_audio=$target_path);
        logger3("converted_filename",$converted_filename);

        $_SESSION['vocapass']['base_audio']['vocamatch_audio_id'] = add_vocamatch_audio($audio_filename=$converted_filename,$ip,$telephone_number);
        logger3("_SESSION['vocapass']['base_audio']['vocamatch_audio_id']",$_SESSION['vocapass']['base_audio']['vocamatch_audio_id']);

        $_SESSION['vocapass']['base_audio']['biometric_registration_status'] = biometric_registration_vocamatch_RECORDED($_SESSION['vocapass']['base_audio']['vocamatch_audio_id'],$voice_file_type="BASE");
        logger3("_SESSION['vocapass']['base_audio']['biometric_registration_status']",$_SESSION['vocapass']['base_audio']['biometric_registration_status']);


        if(stristr($_SESSION['vocapass']['base_audio']['biometric_registration_status'],"INSUFFICIENT AUDIO")){
            echo $_SESSION['vocapass']['base_audio']['biometric_registration_status'];
            
            silentPost($action="BiometricPasswordUpdate", $status=strtoupper($_SESSION['vocapass']['base_audio']['biometric_registration_status']));           
            
            exit;
        }
        
        //compare biometrics
        $query = "select vocamatch_audio_id, voiceprintid from voiceprints where BUSINESS_PERMANENT_UUID = '".$_SESSION['voice_authorization_api']['ACCOUNT_NUMBER']."' and CUSTOMER_BIOMETRIC_ID = '".$_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID']."' and (description = 'Registration' or description='UpdatePassword' or description='PasswordReset') and (biometric_status='APPROVED' or biometric_status='') order by voiceprintid desc";
        //logger3("compare_biometrics_query",$query);
        //test('query', $query);        
        //$voiceprints = readTHECASHIER($query);
        $result = "DOES NOT MATCH";
        $voiceprints = readarrayTHECASHIER($query);
        
        //BASE voiceprint
        $voiceprintids = array();
        foreach ($voiceprints as $key => $vocaprint) {
            $voiceprintids[] = $vocaprint['voiceprintid'];
        }
        //test('voiceprintids', $voiceprintids);
        // GET COMPARISON VOCAMATCH DETAILS
        $comparison_vocamatch_audio_id = $_SESSION['vocapass']['base_audio']['vocamatch_audio_id'];
        
        $tmp_sql = "SELECT * FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $comparison_vocamatch_audio_id . "';";
        //test("tmp_sql",$tmp_sql);
        $comparison_audio_details = readTHECASHIER($tmp_sql);
        //test('comparison_audio_details', $comparison_audio_details);
        $filenames = array();
        $filenames[] = $comparison_audio_details->audio_filename;
        $check_type = $_SESSION['voice_authorization_api'][authorization_template_details][template_name];
        $siv_tolerance = get_siv_tolerance_for_auto_udpate();
        logger3("siv_tolerance",$siv_tolerance);
        $result = check_biometrics_now($check_type, $filenames, $voiceprintids, $tolerance = $siv_tolerance);
        
        $_SESSION['vocapass']['comparison_audio']['biometric_results'] = $result;
		logger3("_SESSION['vocapass']['comparison_audio']['biometric_results']",$_SESSION['vocapass']['comparison_audio']['biometric_results']);
		
        $login_status = 'rejected';
        if($result=='MATCHES') $login_status = 'approved';            
        silentPost($action="BiometricPasswordUpdate", $status=  strtoupper($login_status));
        updateBiometricStatus($voiceprintid=$_SESSION['vocapass']['base_audio']['biometric_registration_status'], $status=strtoupper($login_status));
        
        if($result=="INVALID"){            
            $login_status = 'INVALID';
        }                
        echo strtoupper($login_status);
        exit;
    }
    
    ################################
    #Biometric Password Reset
    ################################
    
    if(stristr($_SESSION['voice_authorization_api'][authorization_template_details][template_name],"Biometric Password Reset")) {
        $_SESSION['vocapass']['base_audio']['filename'] = $filename;
        $_SESSION['vocapass']['base_audio']['source'] = "RECORDED";
 

        $converted_filename = convert_audio_to_alaw($audio_filename,$path_to_audio=$target_path);
        logger3("converted_filename",$converted_filename);

        $_SESSION['vocapass']['base_audio']['vocamatch_audio_id'] = add_vocamatch_audio($audio_filename=$converted_filename,$ip,$telephone_number);
        logger3("_SESSION['vocapass']['base_audio']['vocamatch_audio_id']",$_SESSION['vocapass']['base_audio']['vocamatch_audio_id']);

        $_SESSION['vocapass']['base_audio']['biometric_registration_status'] = biometric_registration_vocamatch_RECORDED($_SESSION['vocapass']['base_audio']['vocamatch_audio_id'],$voice_file_type="BASE");
        logger3("_SESSION['vocapass']['base_audio']['biometric_registration_status']",$_SESSION['vocapass']['base_audio']['biometric_registration_status']);


        if(stristr($_SESSION['vocapass']['base_audio']['biometric_registration_status'],"INSUFFICIENT AUDIO")){
            echo $_SESSION['vocapass']['base_audio']['biometric_registration_status'];
            silentPost($action="BiometricPasswordReset", $status=strtoupper($_SESSION['vocapass']['base_audio']['biometric_registration_status']));           
            exit;
        }
        
        silentPost($action="BiometricPasswordReset", $status="APPROVED");
        updateBiometricStatus($voiceprintid=$_SESSION['vocapass']['base_audio']['biometric_registration_status'], $status="APPROVED");
        
        $tmp_url = appendQueryString($_SESSION['voice_authorization_api']['vocasign_account_details']['business_set_return_url_authorization_approved'],  "CUSTOMER_SESSION_ID=" . $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID']);
        if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_APPROVED_URL'])){
            $tmp_url = $_SESSION['voice_authorization_api']['CUSTOMER_APPROVED_URL'];
        }
        
        logger3("002. tmp_url",$tmp_url);
        echo 'redirect::'.$tmp_url;
        exit; 
    }

    $result = $filename;
}//uploaded

logger3("result",$result);
echo $result;
exit;




###FUNCTIONS

function get_siv_tolerance() {
    $siv_tolerance = "0.6"; 
    
    if(isset($_SESSION['voice_authorization_api']['vocasign_account_details']['security_level_auto_approve'])) {
    
        if(!empty($_SESSION['voice_authorization_api']['vocasign_account_details']['security_level_auto_approve'])) {
            
            $siv_tolerance = $_SESSION['voice_authorization_api']['vocasign_account_details']['security_level_auto_approve'];
		
		}
	}
	
    //////////////////////////////////////////////////
    ///START: check for user-agent adjustment to tolerance:
    logger3("1. get_siv_tolerance(): _POST['AUTHORIZATION_CUSTOMER_EMAILADDRESS']",$_POST['AUTHORIZATION_CUSTOMER_EMAILADDRESS']);
    logger3("1. get_siv_tolerance(): _POST['AUTHORIZATION_CUSTOMER_EMAILADDRESS']",$_GET['AUTHORIZATION_CUSTOMER_EMAILADDRESS']);
    logger3("1. get_siv_tolerance(): _SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS']",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS']);
    
    $tmp_emailaddress = $_POST['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
    
    if(empty($tmp_emailaddress)) $tmp_emailaddress = $_GET['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
    
    if(empty($tmp_emailaddress)) $tmp_emailaddress = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
    
    $tmp_sql = "SELECT memberid FROM email_addresses WHERE emailaddress = '". $tmp_emailaddress ."';";
    logger3("get_siv_tolerance(): tmp_sql",$tmp_sql);
    
    $tmp_memberid = getTHECASHIER($tmp_sql);
    logger3("get_siv_tolerance():  tmp_memberid",$tmp_memberid);
    
    $usergaent_details_results = match_usergaent_details($memberid=$tmp_memberid,$useragent_data="");
    logger3("get_siv_tolerance():  usergaent_details_results",$usergaent_details_results);
    /// END: check for user-agent adjustment to tolerance:
    //////////////////////////////////////////////////
	
    if(stristr($usergaent_details_results,"match")) {
    	
    	$siv_tolerance = $siv_tolerance - "0.1";
    
    }
    
    logger3("get_siv_tolerance(): siv_tolerance",$siv_tolerance);
    return $siv_tolerance;
}

function get_siv_tolerance_for_auto_udpate(){
    $security_level_auto_update = "0.3";
    
    if(isset($_SESSION['authorization_service']['security_level_auto_update'])) {
    
        if(!empty($_SESSION['authorization_service']['security_level_auto_update'])) {
            $security_level_auto_update = $_SESSION['authorization_service']['security_level_auto_update'];
        }
    }
    
    //////////////////////////////////////////////////
    ///START: check for user-agent adjustment to tolerance:
    $tmp_emailaddress = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
    $tmp_sql = "SELECT memberid FROM email_addresses WHERE emailaddress = '". $tmp_emailaddress ."';";
    logger3("get_siv_tolerance_for_auto_udpate(): tmp_sql",$tmp_sql);
    
    $tmp_memberid = getTHECASHIER($tmp_sql);
    logger3("get_siv_tolerance_for_auto_udpate(): tmp_memberid",$tmp_memberid);
    
    $usergaent_details_results = match_usergaent_details($memberid=$tmp_memberid,$useragent_data="");
    logger3("get_siv_tolerance_for_auto_udpate(): usergaent_details_results",$usergaent_details_results);
    /// END: check for user-agent adjustment to tolerance:
    //////////////////////////////////////////////////
    
    if(stristr($usergaent_details_results,"match")) {
    	
    	$security_level_auto_update = $security_level_auto_update - "0.1";
    
    }
   
    
    
    
    return $security_level_auto_update;
}

function updateBiometricStatus($voiceprintid, $status){    
    if(intval($voiceprintid)>0){
        $query = "UPDATE voiceprints set biometric_status= '" . $status . "' WHERE voiceprintid='" . $voiceprintid . "'";
        updateTHECASHIER($query);
    }
}
function getEmailAddress($biometric_id){
    $email_address = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
    if(empty($email_address)){
        $tmp_sql = "SELECT emailaddress FROM email_addresses WHERE biometric_id = '". $biometric_id ."' AND biometric_id!='' ORDER BY datetime_created DESC LIMIT 1";
        //logger3("tmp_sql",$tmp_sql);

        $email_address = getTHECASHIER($tmp_sql);
    }
    return $email_address;
}
function emailBiometricUpdateLink(){  
    $biometric_id = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
    
    $result = "<span style='color:red;'>An error occurred, please try again.</span>";
    $AUTHORIZATION_UPDATE_TEMPLATE = 'e8a90a48b1b75a30d58573d641531a80'; // "Biometric Password Update"
    //$tmp_sql = "SELECT * FROM biometric_registration_session WHERE ACCOUNT_NUMBER='" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "' AND CUSTOMER_SESSION_ID='" . $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'] . "' AND AUTHORIZATION_CUSTOMER_NAME='" . $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] . "' AND verified_status='YES' ORDER BY biometric_registration_session_id DESC LIMIT 1;";
  
//    $tmp_sql = "SELECT * FROM biometric_registration_session WHERE email_verification_hash='" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] . "' AND verified_status='YES' ORDER BY biometric_registration_session_id DESC LIMIT 1;";
//
//    $biometric_registration_session = object2array(readTHECASHIER($tmp_sql));
    //echo $tmp_sql;
    $to = getEmailAddress($biometric_id);
    if(!empty($to)){
        //. "&SERVICE_PASSWORD=" . $_SESSION['voice_authorization_api']['SERVICE_PASSWORD'] 
        
        $subject = "Voice Biometric Profile Update Link :: ". datetime() ." GMT";
        $link = "https://gateway.vocaPASS.com/voice_authorization.api?ACCOUNT_NUMBER=" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "&AUTHORIZATION_TEMPLATE=" . $AUTHORIZATION_UPDATE_TEMPLATE . "&CUSTOMER_SESSION_ID=" . $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'] . "&AUTHORIZATION_CUSTOMER_FIRSTNAME=" . $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'] . "&AUTHORIZATION_CUSTOMER_LASTNAME=" . $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'] . "&CUSTOMER_BIOMETRIC_ID=" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
        
        if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'])){
            $link .= "&AUTHORIZATION_CUSTOMER_EMAILADDRESS=" . $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
        }
        if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_APPROVED_URL'])){
            $link .= "&CUSTOMER_APPROVED_URL=" . $_SESSION['voice_authorization_api']['CUSTOMER_APPROVED_URL'];
        }
        
        $message = "<a href='".$link."' target='vocaPASS'>".$link."<a>";
        quick_mailer($to,$subject,$message,$alert=null);
        $result = "SUCCESS!  A profile update authorization link, has been sent to your registered email address (".disguise_emailaddress_text($to).")";
    }
    return $result;
}





function addAuthorization($action="BiometricVerification", $status='') { 
	
	logger3("addAuthorization(): action",$action);
	logger3("addAuthorization(): status",$status);
	             
    $timestamp = $tmp_timestamp = $tmp_datetime = time();
    
    $set_voice_authorization_authorizationid = "";
    $set_voice_authorization_hash = hash_me();
    $set_voice_authorization_authorization_templateid = $_SESSION['voice_authorization_api']['authorization_template_details']['hash']; //"";
    $set_voice_authorization_template_name = $_SESSION['voice_authorization_api']['authorization_template_details']['template_name']; // "";
    $set_voice_authorization_business_accountid = $_SESSION['voice_authorization_api']['business_account_details']['accountid']; // "";
    $set_voice_authorization_customer_memberid = "";
    $set_voice_authorization_customer_accountid = "";
    
    $set_voice_authorization_biometric_id = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
    //$set_voice_authorization_customer_emailaddress = getEmailAddress($set_voice_authorization_biometric_id);
    $set_voice_authorization_customer_emailaddress = $_SESSION['voice_authorization_api']['CUSTOMER_EMAIL_ADDRESS'];
    
    $set_voice_authorization_customer_name = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'] . ' ' . $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME']); // "";
    $set_voice_authorization_phone_number = 
    $_SESSION['authorization']['phone']['calling_code'] . "/". $_SESSION['authorization']['phone']['number']; // "";
    $set_voice_authorization_phone_country_iso3 = $_SESSION['authorization']['phone']['country_iso3']; // "";
    $set_voice_authorization_ip = $_SESSION['session']['geo']['ip'];
    $set_voice_authorization_ip_country_iso3 = $_SESSION['session']['geo']['iso3'];
    $set_voice_authorization_filename = $_SESSION['authorization']['voice_file'];
    $set_voice_authorization_status = $status; //"Approved";

    //test("_SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
    //test("_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']",$_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);
    //exit;

    $set_voice_authorization_billing_rate = 0;//find_voip_rate($_SESSION['authorization']['phone']['calling_code'] . $_SESSION['authorization']['phone']['number'],"",$_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);

    ///test("set_voice_authorization_billing_rate",$set_voice_authorization_billing_rate);

    $set_voice_authorization_datetime_created = $timestamp;
    ### $set_voice_authorization_ = "";
    ### $set_voice_authorization_ = "";
    ### $set_voice_authorization_ = "";

    //logger3("_SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);   
    
    $set_voice_authorization_datetime_created = $tmp_datetime;
    $set_voice_authorization_datetime_updated = $tmp_datetime;
    $tmp_query = "INSERT into voice_authorizations (
                    `authorizationid`
                    ,`hash`
                    ,`authorization_templateid`
                    ,`template_name`
                    ,`business_accountid`
                    ,`customer_memberid`
                    ,`customer_accountid`
                    ,`biometric_id`
                    ,`customer_name`
                    ,`customer_emailaddress`
                    ,`phone_number`
                    ,`phone_country_iso3`
                    ,`ip`
                    ,`ip_country_iso3`
                    , `ip_city`
                    , `ip_region`
                    , `card_first_digit`
                    , `card_last4_digit`
                    , `authorization_amount`
                    ,`filename`
                    ,`status`
                    ,`billing_rate`
                    ,`datetime_created`
                    ,`passphrase`
            ) VALUES (
                    '" . $set_voice_authorization_authorizationid . "'
                    , '" . $set_voice_authorization_hash . "'
                    , '" . $set_voice_authorization_authorization_templateid . "'
                    , '" . $set_voice_authorization_template_name . "'
                    , '" . $set_voice_authorization_business_accountid ."'
                    , '" . $set_voice_authorization_customer_memberid . "'
                    , '" . $set_voice_authorization_customer_accountid . "'
                    , '" . $set_voice_authorization_biometric_id . "'
                    , '" . $set_voice_authorization_customer_name . "'
                    , '" . $set_voice_authorization_customer_emailaddress . "'
                    , '" . $set_voice_authorization_phone_number . "'
                    , '" . $set_voice_authorization_phone_country_iso3 . "'
                    , '" . $set_voice_authorization_ip . "'
                    , '" . $set_voice_authorization_ip_country_iso3 . "'
                    , '". addslashes($_SESSION['session']['geo']['city']) ."'
                    , '". addslashes($_SESSION['session']['geo']['region']) ."'
                    , '". "" ."'
                    , '". "" ."'
                    , '". "" ."'
                    , '" . $_SESSION['vocapass']['filename'] . "'
                    , '" . $set_voice_authorization_status . "'
                    , '" . $set_voice_authorization_billing_rate . "'
                    , '" . $set_voice_authorization_datetime_created . "'
                    , ''
                    )";
    logger3("addAuthorization(): tmp_query",$tmp_query);	
    //$_SESSION['voice_authorization_api']['approved']['authorizationid'] = $authorizationid = 
    $insert_results = insertTHECASHIER($tmp_query);	
    logger3("addAuthorization(): insert_results",$insert_results);
    insertTHECASHIER($tmp_query);	
    //test("authorizationid",$authorizationid);	
    //test("_SESSION['voice_authorization_api']['approved']['authorizationid']",$_SESSION['voice_authorization_api']['approved']['authorizationid']);    
}

function silentPost($action="BiometricVerification", $status='') {
    
    $_SESSION['voice_authorization_api']['CUSTOMER_EMAIL_ADDRESS'] = getEmailAddress($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID']);
            
    addAuthorization($action, ucfirst(strtolower($status)));
    
    if($action=="BiometricVerification"){
        if(isset($_SESSION['voice_authorization_api']['ios_app_session_id'])){
            $app_session_query = "update vocapass_app_session set status='".  strtoupper($status)."' where appsessionid='" . $_SESSION['voice_authorization_api']['ios_app_session_id'] . "'";
            updateTHECASHIER($app_session_query);
        }
        
        if(stristr($status,"REJECTED")){
            $_SESSION['voice_authorization_api']['CUSTOMER_UPDATE_PIN'] = generate_vocapass_update_pin($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'], $VOICE_AUTHORIZATION_CATEGORY="UPDATE", $voiceprintid=$_SESSION['vocapass']['comparison_audio']['biometric_registration_status']);
        }
    }
    
    ############################################################
    ### (KURL) UPDATE business_set_user_status_url:
    if(isset($_SESSION['voice_authorization_api'])) {
       
       if(isset($_SESSION['voice_authorization_api']['vocasign_account_details'])) {
       
       
       
       		logger3("888. _SESSION['session']['biometric_registration_session']",$_SESSION['session']['biometric_registration_session']);
       		logger3("888. _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);

            # notify business account of new session_status:
            $tmp_url = $_SESSION['voice_authorization_api']['vocasign_account_details']['business_set_user_status_url'];
            
            
            if(empty($_SESSION['voice_authorization_api']['CUSTOMER_EMAIL_ADDRESS'])) $_SESSION['voice_authorization_api']['CUSTOMER_EMAIL_ADDRESS'] = $_SESSION['session']['biometric_registration_session']['emailaddress'];
            
            /*
            //$tmp_properties = "ACTION=".$action;
            $tmp_properties = "ACTION=". urlencode($_SESSION['voice_authorization_api']['authorization_template_details']['template_name']);
            $tmp_properties .= "&CUSTOMER_SESSION_ID=" . urlencode($_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID']);
            $tmp_properties .= "&CUSTOMER_FIRSTNAME=" . urlencode($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME']);
            $tmp_properties .= "&CUSTOMER_LASTNAME=" . urlencode($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME']);
            $tmp_properties .= "&CUSTOMER_EMAILADDRESS=" . urlencode($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS']);
            //$tmp_properties .= "&CUSTOMER_TELEPHONE_NUMBER=" . urlencode($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER']);
            $tmp_properties .= "&CUSTOMER_BIOMETRIC_ID=" . urlencode($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID']);
            $tmp_properties .= "&AUTHORIZATION_STATUS=" . urlencode($status);
            
            */
            
            if(isset($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])){
                $tmp_properties .= "VOICE_BIOMETRIC_PASSPORT_ID=" . urlencode($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID']) . "&";
            }
            if($action=="BiometricVerification" && isset($_SESSION['voice_authorization_api']['CUSTOMER_UPDATE_PIN'])){
                $tmp_properties .= "CUSTOMER_UPDATE_PIN=" . $_SESSION['voice_authorization_api']['CUSTOMER_UPDATE_PIN'] . "&";
            }
            $tmp_properties .= "AUTHORIZATION_STATUS=" . strtoupper(urlencode($status));
            
            //biometric_registration_session^AUTHORIZATION_CUSTOMER_NAME^shea writer
            //biometric_registration_session^emailaddress^shea.writer@nsdb.com_addref(
						
            //$tmp_properties = urlencode($tmp_properties);
            
            $tmp_kurl = kurl($tmp_url,$tmp_properties);
            logger3("8. tmp_url: " , $tmp_url);
            logger3("8. tmp_properties: " , $tmp_properties);
            logger3("8. tmp_kurl: " , $tmp_kurl);                      
        }
    }
}

function addEmailAddress($biometric_id, $emailaddress, $status='VERIFIED'){    
    $tmp_sql = "INSERT into email_addresses					
        (
        `emailaddressesid`
        ,`emailaddress`
        ,`biometric_id`
        ,`status`
        ,`datetime_created`
        ,`datetime_updated`
        ) VALUES (
        '$emailaddressesid'
        ,'". trim(strtolower($emailaddress)) ."'
        ,'". $biometric_id ."'
        ,'". $status ."'
        ,'". datetime() ."'
        ,'". datetime() ."'
        );
    ";
    insertTHECASHIER($tmp_sql);        
}

function appendQueryString($url, $query) {
    $pound = "";
    $poundPos = -1;

    //Is there a #?
    if ( ( $poundPos = strpos( $url, "#" ) ) !== false )
    {
        $pound = substr( $url, $poundPos );
        $url = substr( $url, 0, $poundPos );
    }

    $separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
    $url .= $separator . $query . $pound;
    logger3("appendQueryString(): url",$url);
    return $url;
}

function check_biometrics_now($check_type, $filenames, $voiceprintids, $tolerance) {
    global $logging;
    global $master_config_ibmsiv_host;
    global $master_config_testing_biometric_matching;

    # prepare session:
    logger3("### BUILD THE LOOK-UP SESSIONS...", $a);
    logger3('filenames:', $filenames);
    logger3('voiceprintids:', $voiceprintids);
    logger3("Check Type:", $check_type);
    logger3("Tolerance:", $tolerance);


    ### PREP VARS:
    $response = NULL;
    $response = array();
    $results = NULL;
    $results = array();


    ##############################################################################


    $mh = curl_multi_init();


    $possible_duplicates = NULL;
    $possible_duplicates = array();
    $pd = 0;
    $fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    logger3("filenames[$fn]: ", $filenames[$fn]);


    ##############################################################################
    # prepare requests / handles:

    $vp = 0;
    while (isset($voiceprintids[$vp])) {
        logger3("[vp]: [", $vp . "]", $a);
        logger3("voiceprintids[vp]: ", $voiceprintids[$vp]);

        # set url:
        $siv_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/score";

        #set parameters for sv:
        $parameters = "voiceprint={$voiceprintids[$vp]}&input-wave-uri=/mnt/WebServer/www/audio_recorder/recordings/" . $filenames[$fn];

        logger3("SIV URL", $siv_url . "?" . $parameters);



        # initialize:
        $ch[$master_counter] = curl_init();
        //logger3("ch[$vp]: ", $ch[$master_counter]);
        #set headers:
        curl_setopt($ch[$master_counter], CURLOPT_HEADER, 0);

        #set number of parameters
        curl_setopt($ch[$master_counter], CURLOPT_POST, 1);

        # dunno what this does:
        curl_setopt($ch[$master_counter], CURLOPT_RETURNTRANSFER, 1);

        #curl_setopt($ch, CURLOPT_VERBOSE, 1);
        # set path to server
        curl_setopt($ch[$master_counter], CURLOPT_URL, $siv_url);

        #set parameter values:
        curl_setopt($ch[$master_counter], CURLOPT_POSTFIELDS, $parameters);

        # set multi handle 
        curl_multi_add_handle($mh, $ch[$master_counter]);

        #update voiceid
        $vp++;
        $master_counter++;
    }

    #update filname
    $fn++;
    //}
    ##############################################################################
    # execute:

    $running = 1;
    while ($running > 0) {
        //logger3("running...", $running);
        curl_multi_exec($mh, $running);
    }


    ##############################################################################
    # get responses:
    logger3("### RAW (PER LOOKUP) RESULTS...", $a);

    # used to make final decsision:
    $duplicate_voiceprintids = NULL;
    $duplicate_voiceprintids = array();

    $fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    $result = "DOES NOT MATCH";
    $vp = 0;
    while (isset($voiceprintids[$vp])) {

        //logger3("[vp]: [", $vp . "]",$a);
        //logger3("voiceprintids[vp]: ", $voiceprintids[$vp]);

        $response[$vp] = curl_multi_getcontent($ch[$master_counter]);
        //logger3("response[vp]: ", $response[$vp]);       

        $tmp_response = explode("name=\"result.score\" expr=\"'", $response[$vp]);
        $tmp_response = explode("'\"/>", $tmp_response[1]);
        logger3("filename[$fn]: ", $filenames[$fn] . " vs. voiceprintid[$vp]: " . $voiceprintids[$vp] . " = score: " . $tmp_response[0]);

        if ($tmp_response[0] >= $tolerance) {
            $result="MATCHES";
        }
        else{
            //IF ALREADY FOUND A MATCHES, DONT REPLACE IT
            if($result!='MATCHES'){
                if(stristr($check_type,"Biometric Password Update")){
                    $result = "INVALID";
                }
            }
        }

        # remove handle
        curl_multi_remove_handle($mh, $ch[$master_counter]);

        # update voicefileid
        $vp++;
        $master_counter++;
    }
    # update filename
    $fn++;
    //}
    ##############################################################################
    # all done / close session:
    curl_multi_close($mh);
    
    return $result;
}

?>
