<?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();

 // header('Set-Cookie: PHPSESSID= ' . session_id() . '; SameSite=strict; Secure=true; HttpOnly=true;');

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'];
    $confExtension = $_POST['conf_extension'];
    $confTag = $_POST['conf_tag'];
    $wssServer = $_POST['wss_server'];
    $webSocketAndPath = $_POST['web_sock_path'];

    /**
     *  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, extension name, conference extension, conference label and WebSocket port and server path
    $userExtenConfExt = $username . "|" . $extenForExternal . "|" . $confExtension . "|" . $confTag . "|" . $webSocketAndPath;
    $ivsep = substr(sha1((string) mt_rand()), 0, 16);
    $encryptpwdin = openssl_encrypt($userExtenConfExt, '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 user for which we want to insert the external user data
    $enabled = 1;
    $query1 = $mysqli->prepare("SELECT id, userrole, username, enabled FROM app_users WHERE (userrole = 'admin' OR userrole = 'superadmin') AND BINARY username = ? AND enabled = ?");
    $query1->bind_param("si", $username, $enabled);
    $query1->execute();
    $queryres = $query1->get_result()->fetch_assoc();
    $userID = $queryres['id'];

    // Check if the extension has already been introduced in the 'external_users' table
    $query2 = $mysqli->prepare("SELECT id, userid, exten_for_external FROM external_users WHERE exten_for_external = ?");
    $query2->bind_param("s", $extenForExternal);
    $query2->execute();
    $extqueryres = $query2->get_result()->fetch_assoc();
    $linkauthorID = $extqueryres['userid'];
    $extensionExists = $extqueryres['id'];


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

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

        $keypasssp = substr(sha1((string) 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((string) 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->prepare("SELECT id, userid, exten_for_external, exten_for_ext_pass FROM external_users WHERE userid = ? AND exten_for_external = ?");
              $queryselextpass->bind_param("is", $userID, $extenForExternal);
              $queryselextpass->execute();
              $extpassarr = $queryselextpass->get_result()->fetch_assoc();

              $extenForExternalPassEnc = $extpassarr['exten_for_ext_pass'];

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

    $date = date("Y-m-d H:i:s");

    // 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_extension = ?, conf_tag = ?, conf_access_link = ?, date_modified = ? WHERE userid = ?
                                             AND exten_for_external = ?");
	    $updatequery->bind_param("sssssis", $extenForExternalPassEnc, $confExtension, $confTag, $confAccessLinkEnc, $date, $userID, $extenForExternal);

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

        } else { $messagetosend = 'A different user 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_extension, conf_tag, conf_access_link, date_added, 
                                             date_modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
	    $insertquery->bind_param("isssssss", $userID, $extenForExternal, $extenForExternalPassEnc, $confExtension, $confTag, $confAccessLinkEnc, $date, $date);

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

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

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

?>
