<?php
/**
 *  Copyright (C) 2021  Cover Tower LLC
 *
 *  This file is part of Roundpin, which is licensed under the
 *  GNU Affero General Public License Version 3.0. The license terms
 *  are detailed in the "LICENSE.txt" file located in the root directory.
 */

session_start();

if (isset($_POST['s_ajax_call']) && ($_POST['s_ajax_call'] == $_SESSION['validate_s_access'])) {


 define('ACCESSCONST', TRUE);

 require('db-connect.php');

    $username = $_POST['username'];
    $wssServer = $_POST['wss_server'];
    $webSocketPort = $_POST['web_socket_port'];
    $serverPath = $_POST['server_path'];
    $profileName = $_POST['profile_name'];
    $sipUsername = $_POST['sip_username'];
    $sipPasswordPre = $_POST['sip_password'];
    $stunServer = $_POST['stun_server'];
    $audioOutputId = $_POST['audio_output_id'];
    $videoSrcId = $_POST['video_src_id'];
    $videoHeight = $_POST['video_height'];
    $frameRate = $_POST['frame_rate'];
    $aspectRatio = $_POST['aspect_ratio'];
    $videoOrientation = $_POST['video_orientation'];
    $audioSrcId = $_POST['audio_src_id'];
    $autoGainControl = $_POST['auto_gain_control'];
    $echoCancellation = $_POST['echo_cancellation'];
    $noiseSuppression = $_POST['noise_suppression'];
    $ringOutputId = $_POST['ring_output_id'];
    $videoConfExtension = $_POST['video_conf_extension'];
    $videoConfWindowWidth = $_POST['video_conf_window_width'];
    $profilePicture = $_POST['profile_picture'];
    $notifications = $_POST['notifications'];
    $useRoundcube = $_POST['use_roundcube'];
    $rcDomain = $_POST['rcdomain'];
    $rcBasicAuthUser = $_POST['rcbasicauthuser'];
    $rcBasicAuthPass = $_POST['rcbasicauthpass'];
    $rcUser = $_POST['rcuser'];
    $rcPassword = $_POST['rcpassword'];

    // Encrypt the SIP password, Roundcube password (if any) and Roundcube basic auth password (if any), before inserting them into the database
    if ($sipPasswordPre != '' && $sipPasswordPre != "%20%20%20%20%20%20%20") {

        $keypass = substr(sha1(mt_rand()), 0, 32);
        $keysalt = openssl_random_pseudo_bytes(12);
        $generated_key = openssl_pbkdf2($keypass, $keysalt, 40, 100, 'sha256');
        $psswdadded = bin2hex($generated_key);

        if (!is_dir('restr')) {
            mkdir('restr', 0700);
        }

        if (!is_dir('restr/'.$username.'')) {
            mkdir('restr/'.$username.'', 0700);
        }

        file_put_contents('restr/'.$username.'/pwdkey', $psswdadded);
        chmod('restr/'.$username.'/pwdkey', 0600);

        $iv = substr(sha1(mt_rand()), 0, 16);
        $encpwdin = openssl_encrypt($sipPasswordPre, 'AES-256-CBC', $psswdadded, false, $iv);
        $sipPasswordEnc = $encpwdin.':'.$iv;

    } elseif ($sipPasswordPre == "%20%20%20%20%20%20%20") { 

              $queryselsippass = $mysqli->query("SELECT username, sip_password, enabled FROM app_users WHERE BINARY username = '$username' AND enabled = 1");
              $sippassarr = $queryselsippass->fetch_assoc();
              $sipPasswordEnc = $sippassarr['sip_password']; 

    } elseif ($sipPasswordPre == '') { 
              $sipPasswordEnc = ''; 
    } else { $sipPasswordEnc = ''; }


    if ($rcBasicAuthPass != '' && $rcBasicAuthPass != "%20%20%20%20%20%20%20") {

        $keypassrcba = substr(sha1(mt_rand()), 0, 32);
        $keysaltrcba = openssl_random_pseudo_bytes(12);
        $generated_keyrcba = openssl_pbkdf2($keypassrcba, $keysaltrcba, 40, 100, 'sha256');
        $psswdaddedrcba = bin2hex($generated_keyrcba);

        if (!is_dir('restr')) {
            mkdir('restr', 0700);
        }

        if (!is_dir('restr/'.$username.'')) {
            mkdir('restr/'.$username.'', 0700);
        }

        file_put_contents('restr/'.$username.'/pwdkeyrcba', $psswdaddedrcba);
        chmod('restr/'.$username.'/pwdkeyrcba', 0600);

        $iv2 = substr(sha1(mt_rand()), 0, 16);
        $encRcBasicAuthPass = openssl_encrypt($rcBasicAuthPass, 'AES-256-CBC', $psswdaddedrcba, false, $iv2);
        $rcBasicAuthPassEnc = $encRcBasicAuthPass.':'.$iv2;

    } elseif ($rcBasicAuthPass == "%20%20%20%20%20%20%20") { 
              $queryselrcbapass = $mysqli->query("SELECT username, rcbasicauthpass, enabled FROM app_users WHERE BINARY username = '$username' AND enabled = 1");
              $rcbapassarr = $queryselrcbapass->fetch_assoc();
              $rcBasicAuthPassEnc = $rcbapassarr['rcbasicauthpass']; 
    } elseif ($rcBasicAuthPass == '') { 
              $rcBasicAuthPassEnc = ''; 
    } else { $rcBasicAuthPassEnc = ''; }


    if ($rcPassword != '' && $rcPassword != "%20%20%20%20%20%20%20") {

        $keypassrc = substr(sha1(mt_rand()), 0, 32);
        $keysaltrc = openssl_random_pseudo_bytes(12);
        $generated_keyrc = openssl_pbkdf2($keypassrc, $keysaltrc, 40, 100, 'sha256');
        $psswdaddedrc = bin2hex($generated_keyrc);

        if (!is_dir('restr')) {
            mkdir('restr', 0700);
        }

        if (!is_dir('restr/'.$username.'')) {
            mkdir('restr/'.$username.'', 0700);
        }

        file_put_contents('restr/'.$username.'/pwdkeyrc', $psswdaddedrc);
        chmod('restr/'.$username.'/pwdkeyrc', 0600);

        $iv3 = substr(sha1(mt_rand()), 0, 16);
        $encRcPassword = openssl_encrypt($rcPassword, 'AES-256-CBC', $psswdaddedrc, false, $iv3);
        $rcPasswordEnc = $encRcPassword.':'.$iv3;

    } elseif ($rcPassword == "%20%20%20%20%20%20%20") { 
              $queryselrcpass = $mysqli->query("SELECT username, rcpassword, enabled FROM app_users WHERE BINARY username = '$username' AND enabled = 1");
              $rcpassarr = $queryselrcpass->fetch_assoc();
              $rcPasswordEnc = $rcpassarr['rcpassword']; 
    } elseif ($rcPassword == '') { 
              $rcPasswordEnc = ''; 
    } else { $rcPasswordEnc = ''; }

    // Insert account data for the current user in the 'app_users' table
    $enabled = 1;
    $query1 = $mysqli->prepare("UPDATE `app_users` SET `wss_server`=?, `web_socket_port`=?, `server_path`=?, `profile_name`=?, `sip_username`=?, `sip_password`=?, `stun_server`=?,
                                `audio_output_id`=?, `video_src_id`=?, `video_height`=?, `frame_rate`=?, `aspect_ratio`=?, `video_orientation`=?, `audio_src_id`=?, `auto_gain_control`=?,
                                `echo_cancellation`=?, `noise_suppression`=?, `ring_output_id`=?, `video_conf_extension`=?, `video_conf_window_width`=?, `profile_picture`=?,
                                `notifications`=?, `use_roundcube`=?, `rcdomain`=?, `rcbasicauthuser`=?, `rcbasicauthpass`=?, `rcuser`=?, `rcpassword`=? WHERE BINARY `username`=? AND `enabled`=?");
    $query1->bind_param("sissssssssissssssssssiissssssi", $wssServer, $webSocketPort, $serverPath, $profileName, $sipUsername, $sipPasswordEnc, $stunServer, $audioOutputId,
                         $videoSrcId, $videoHeight, $frameRate, $aspectRatio, $videoOrientation, $audioSrcId, $autoGainControl, $echoCancellation, $noiseSuppression,
                         $ringOutputId, $videoConfExtension, $videoConfWindowWidth, $profilePicture, $notifications, $useRoundcube, $rcDomain, $rcBasicAuthUser, $rcBasicAuthPassEnc, 
                         $rcUser, $rcPasswordEnc, $username, $enabled);
    if ($query1->execute()) { $messagetosend = 'success'; } else { $messagetosend = 'failure'; }

    $response = array('result' => $messagetosend);
    echo json_encode($response);

} else {
    header("Location: roundpin-login.php");
}

?>