<?php
/**
 *  Copyright (C) 2021  Double Bastion 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'];
    $extenForExternal = $_POST['exten_for_external'];
    $extenForExternalPass = $_POST['exten_for_ext_pass'];
    $wssServer = $_POST['wss_server'];

    /**
     *  Encrypt the user and the extension used for external access
     */

    // Extract the secret from the configuration file
    $configfilestring = file_get_contents(dirname(__FILE__) . '/roundpin-config.php');

    if (preg_match_all('[include|include_once|require|require_once]', $configfilestring) != 0) {

        if (strpos($configfilestring, "'") !== false) {
            $continit = explode("'", $configfilestring);
            $configfilepath = $continit[1];
        } elseif (strpos($configfilestring, "\"") !== false) {
            $continit = explode("\"", $configfilestring);
            $configfilepath = $continit[1];
          }

        $configfilelines = file($configfilepath);

        if (count($configfilelines) != 0) {

           foreach ($configfilelines as $keyfile => $valuefile) {

              if (strpos($valuefile, "\$secret") !== false) {
                  $secret_init = explode("'", $valuefile);
                  $secretfin = $secret_init[1];
              }
           }
        }

    } else {

        $configfilelines = file(dirname(__FILE__) . '/roundpin-config.php');

        if (count($configfilelines) != 0) {
           foreach ($configfilelines as $keyfile => $valuefile) {
              if (strpos($valuefile, "\$secret") !== false) {
                  $secretinit = explode("'", $valuefile);
                  $secretfin = $secretinit[1];
              }
           }
        }
      }

    // Encrypt the username and extension name
    $userAndExt = $username . "|" . $extenForExternal;
    $ivsep = substr(sha1(mt_rand()), 0, 16);
    $encryptpwdin = openssl_encrypt($userAndExt, 'AES-256-CBC', $secretfin, false, $ivsep);
    $finUserExtEncinit = $encryptpwdin.':'.$ivsep;
    $finUserExtEnc = bin2hex($finUserExtEncinit);

    // Build the external access link
    $confAccessLinkEnc = "https://".$wssServer."/videoconference/external.php?param=".$finUserExtEnc;

    // Get the id of the superadmin for which we want to insert the external user data
    $query1 = $mysqli->query("SELECT id, userrole, username, enabled FROM app_users WHERE userrole = 'superadmin' AND BINARY username = '$username' AND enabled = 1");
    $queryres = $query1->fetch_array();
    $userID = $queryres[0];

    // Check if the extension has already been introduced in the 'external_users' table
    $query2 = $mysqli->query("SELECT id, userid, exten_for_external FROM external_users WHERE exten_for_external = '$extenForExternal'");
    $extqueryres = $query2->fetch_array();
    $linkauthorID = $extqueryres[1];
    $extensionExists = $extqueryres[0];


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

        // Encrypt the SIP password for the extension used for external access

        $keypasssp = substr(sha1(mt_rand()), 0, 32);
        $keysaltsp = openssl_random_pseudo_bytes(24);
        $keyLengthsp = 80;
        $iterationssp = 100;
        $generated_keysp = openssl_pbkdf2($keypasssp, $keysaltsp, $keyLengthsp, $iterationssp, 'sha256');
        $psswdaddedsp = bin2hex($generated_keysp);

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

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

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

        file_put_contents('restr/'.$username.'/externalext/'.$extenForExternal, $psswdaddedsp);
        chmod('restr/'.$username.'/externalext/'.$extenForExternal, 0600);

        $ivsp = substr(sha1(mt_rand()), 0, 16);
        $encpwdinsp = openssl_encrypt($extenForExternalPass, 'AES-256-CBC', $psswdaddedsp, false, $ivsp);
        $extenForExternalPassEnc = $encpwdinsp.':'.$ivsp;

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

              $queryselextpass = $mysqli->query("SELECT id, userid, exten_for_external, exten_for_ext_pass FROM external_users WHERE userid = '$userID' AND 
                                                 exten_for_external = '$extenForExternal'");
              $extpassarr = $queryselextpass->fetch_assoc();

              $extenForExternalPassEnc = $extpassarr['exten_for_ext_pass']; 

    } elseif ($extenForExternalPass == '') { 
              $extenForExternalPassEnc = ''; 
    } else { $extenForExternalPassEnc = ''; }


    // Update or insert the data in the 'external_users' table
    if ($extensionExists != '') {

        if ($linkauthorID == $userID) {
	    $updatequery = $mysqli->prepare("UPDATE external_users SET exten_for_ext_pass=?, conf_access_link=? WHERE userid=? AND exten_for_external=?");
	    $updatequery->bind_param("ssis", $extenForExternalPassEnc, $confAccessLinkEnc, $userID, $extenForExternal);

	    if ($updatequery->execute()) { $messagetosend = 'The data has been successfully saved to the database !'; } else { $messagetosend = 'Error while updating data!'; }

        } else { $messagetosend = 'A different Superadmin has already created a link for this extension. Please choose a different extension!'; }

    } else {
	    $insertquery = $mysqli->prepare("INSERT INTO external_users (userid, exten_for_external, exten_for_ext_pass, conf_access_link) VALUES (?, ?, ?, ?)");
	    $insertquery->bind_param("isss", $userID, $extenForExternal, $extenForExternalPassEnc, $confAccessLinkEnc);

	    if ($insertquery->execute()) { $messagetosend = 'The data has been successfully saved to the database !'; } else { $messagetosend = 'Error while inserting data into the database!'; }
      }

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

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

?>