<?php
/**
 *  Copyright (C) 2022, 2024  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($_GET['sipusername']) && $_GET['sipusername'] != '' && isset($_GET['encextenpass']) && $_GET['encextenpass'] != '' && isset($_GET['conferenceext']) && 
    $_GET['conferenceext'] != '' && isset($_GET['recSipUser']) && $_GET['recSipUser'] != '' && isset($_GET['recFlNm']) && $_GET['recFlNm'] != '') {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

    $vconfExtension = $_GET['sipusername'];
    $extenPassEnc = rawurldecode($_GET['encextenpass']);
    $videoConfExt = $_GET['conferenceext'];

    $recSipUser = $_GET['recSipUser'];
    $recFileName = $_GET['recFlNm'];

    $fileToDownload = '../textchat/' . $recSipUser . '/uploads/' . $recFileName;

    // Check if the received external user extension, the corresponding encrypted password and the extension of the conference, match the data in the 'external_users' table
    $query = $mysqli->prepare("SELECT id, exten_for_external, exten_for_ext_pass, conf_extension FROM external_users WHERE exten_for_external = ? AND exten_for_ext_pass = ? AND conf_extension = ?");
    $query->bind_param("sss", $vconfExtension, $extenPassEnc, $videoConfExt);
    $query->execute();
    $extqueryres = $query->get_result()->fetch_array();

    if (!$extqueryres) {

        http_response_code(400);
        exit();

    } else {

	    // Process the download
	    if (is_file($fileToDownload)) {
		    header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="' . basename($fileToDownload) . '"');
		    header('Expires: 0');
		    header('Cache-Control: no-cache, must-revalidate');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($fileToDownload));
		    flush();
		    readfile($fileToDownload);
		    exit();
	    } else {
		    http_response_code(404);
		    exit();
	    }

    }

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

?>