<?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['destSipUser']) &&
    $_GET['destSipUser'] != '' && isset($_GET['sentFlNm']) && $_GET['sentFlNm'] != '') {

    define('ACCESSCONST', TRUE);

    require('db-connect.php');

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

    $destSipUser = $_GET['destSipUser'];
    $sentFileName = $_GET['sentFlNm'];

    $fileToDownload = '../textchat/' . $destSipUser . '/uploads/' . $sentFileName;

    // 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, $destSipUser);
    $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");
}

?>
