<?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'];

    // Get the Roundcube password and Roundcube auth password for the current user from the 'app_users' table
    $querysel = $mysqli->query("SELECT username, rcdomain, rcbasicauthuser, rcbasicauthpass, rcuser, rcpassword, enabled FROM app_users WHERE BINARY username = '$username' AND enabled = 1");
    $confdatafromdb = $querysel->fetch_assoc();


    // Decrypt the Roundcube password (if any) and Roundcube basic auth password (if any), fetched from the database

    if ($confdatafromdb['rcpassword'] != '' && $confdatafromdb['rcpassword'] != null && $confdatafromdb['rcpassword'] != 'undefined') {

        $psswdaddedkeyrc = file_get_contents('restr/'.$username.'/pwdkeyrc');
        $rcpasswdinit = $confdatafromdb['rcpassword'];
        $componentrcpass = explode(':', $rcpasswdinit);

        $encpwdin = $componentrcpass[0];
        $ivkey = $componentrcpass[1];

        $rcpassworddec = openssl_decrypt($encpwdin, 'AES-256-CBC', $psswdaddedkeyrc, false, $ivkey);

        $confdatafromdb['rcpassword'] = $rcpassworddec;

    } else { $confdatafromdb['rcpassword'] = ''; }

    if ($confdatafromdb['rcbasicauthpass'] != '' && $confdatafromdb['rcbasicauthpass'] != null && $confdatafromdb['rcbasicauthpass'] != 'undefined') {

        $psswdaddedkeyrcba = file_get_contents('restr/'.$username.'/pwdkeyrcba');
        $rcbapasswdinit = $confdatafromdb['rcbasicauthpass'];
        $componentrcbapass = explode(':', $rcbapasswdinit);

        $baencpwdin = $componentrcbapass[0];
        $baivkey = $componentrcbapass[1];

        $rcbapassworddec = openssl_decrypt($baencpwdin, 'AES-256-CBC', $psswdaddedkeyrcba, false, $baivkey);

        $confdatafromdb['rcbasicauthpass'] = $rcbapassworddec;

    } else { $confdatafromdb['rcbasicauthpass'] = ''; }

    $datafromdb = $confdatafromdb;

    echo json_encode($datafromdb);

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

?>