<?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.
 *
 *  This is a modified version of the original file "index.html",
 *  first modified in 2020. The copyright notice for the original
 *  content follows:

/*
  Cyber Mega Phone 2K
  Copyright (C) 2017 Digium, Inc.

  This program is free software, distributed under the terms of the
  MIT License. See the LICENSE file at the top of the source tree.
*/

$retrievedstringinit = $_GET['param'];
$retrievedstring = hex2bin($retrievedstringinit);

if ($retrievedstring != '') {

    session_start();

    define('ACCESSCONST', TRUE);

    require('../db-connect.php');

    // Extract the secret from the configuration file
    $configfilestring = file_get_contents('../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('../roundpin-config.php');

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

    // Decrypt the extension used for external access to conference and the username of the user who created the link
    $componentuserext = explode(':', $retrievedstring);

    $encpwdinusext = $componentuserext[0];
    $ivkey = $componentuserext[1];

    $userExtDec = openssl_decrypt($encpwdinusext, 'AES-256-CBC', $secretfin, false, $ivkey);

    $userExtDecComp = explode("|", $userExtDec);
    $userName = $userExtDecComp[0];
    $extForExtern = $userExtDecComp[1];

    $retrievedSipUsername = $extForExtern;

    // Get the relevant information for the superadmin who created the external access link
    $query1 = $mysqli->query("SELECT id, userrole, username, wss_server, stun_server, video_conf_extension, enabled FROM app_users WHERE userrole = 'superadmin' AND BINARY username = '$userName' AND enabled = 1");
    $queryres = $query1->fetch_array();
    $userID = $queryres[0];
    $retrievedWssServer = $queryres[3];
    $retrievedStunServer = $queryres[4];
    $retrievedVideoConfExt = $queryres[5];

    // Get the SIP password from the 'external_users' table
    $query2 = $mysqli->query("SELECT id, userid, exten_for_external, exten_for_ext_pass FROM external_users WHERE userid = '$userID' AND exten_for_external = '$extForExtern'");
    $extqueryres = $query2->fetch_array();
    $extensionPass = $extqueryres[3];

    // Decrypt the SIP password
    $componentpkey = explode(':', $extensionPass);
    $psswdaddedkey = file_get_contents('../restr/'.$userName.'/externalext/'.$extForExtern);

    $encpwdinsip = $componentpkey[0];
    $ivkeysip = $componentpkey[1];

    $retrievedSipPassword = openssl_decrypt($encpwdinsip, 'AES-256-CBC', $psswdaddedkey, false, $ivkeysip);

?>

<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8" />
    <title>Roundpin Video Conference</title>
    <link rel="stylesheet" type="text/css" href="css/conference-phone.min.css">

    <link rel="stylesheet" type="text/css" href="../fonts/font-awesome-4.7.0/css/font-awesome.min.css"/>

    <link rel="stylesheet" type="text/css" href="../css/jeegoo-1.0.0.min.css"/>

    <link rel="shortcut icon" type="image/svg" href="../images/favicon.svg" />
    <script type="text/javascript" src="js/sdp-interop-sl-1.4.0.min.js"></script>
    <script type="text/javascript" src="js/jssip-3.7.0.min.js"></script>
    <script type="text/javascript" src="js/utils.min.js"></script>
    <script type="text/javascript" src="../js/jquery-3.3.1.min.js"></script>

    <script type="text/javascript" src="js/conference-phone.min.js"></script>

    <script type="text/javascript" src="../js/jquery.jeegoopopup.1.0.0.min.js"></script>

<script type="text/javascript">

let phone;
let numPressed = null;

let sip_username = "<?php print_r($retrievedSipUsername); ?>";
let sip_password = "<?php print_r($retrievedSipPassword); ?>";
let wss_server = "<?php print_r($retrievedWssServer); ?>";
let stun_server = "<?php print_r($retrievedStunServer); ?>";
let videoConfExtension = "<?php print_r($retrievedVideoConfExt); ?>";

window.onload = function() {

        var mvcount = 0;
	document.getElementById("connect").value = "Connect";
	document.getElementById("connect").disabled = false;
	document.getElementById("call").value = "Call";
	document.getElementById("call").disabled = true;
        document.getElementById("call").style.display = 'none';
        document.getElementById("fullscreen").style.display = 'none';

	function findMediaView(parent, stream) {
		let nodes = parent.childNodes;

		for (let i = 0; i < nodes.length; ++i) {
			if (nodes[i].id == stream.id) {
				return nodes[i];
			}
		}
		return null;
	}

        function dtmfMenuShow() {

                $.jeegoopopup.close();

	        var leftPos = event.pageX - 90;
	        var topPos = event.pageY + 28;

		if ($(window).width() < 680) {
		    leftPos = event.pageX - 50;
		}

	        var html = "<div id=\"sendPinDialPad\">";
	        html += "<div><input type=\"text\" id=\"dialText\" class=\"dialTextInput\"></div>";
	        html += "<table cellspacing=10 cellpadding=0 style=\"margin-left:auto; margin-right: auto\">";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('1');new Audio('../sounds/dtmf.mp3').play();\"><div>1</div><span>&nbsp;</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('2');new Audio('../sounds/dtmf.mp3').play();\"><div>2</div><span>ABC</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('3');new Audio('../sounds/dtmf.mp3').play();\"><div>3</div><span>DEF</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('4');new Audio('../sounds/dtmf.mp3').play();\"><div>4</div><span>GHI</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('5');new Audio('../sounds/dtmf.mp3').play();\"><div>5</div><span>JKL</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('6');new Audio('../sounds/dtmf.mp3').play();\"><div>6</div><span>MNO</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('7');new Audio('../sounds/dtmf.mp3').play();\"><div>7</div><span>PQRS</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('8');new Audio('../sounds/dtmf.mp3').play();\"><div>8</div><span>TUV</span></button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('9');new Audio('../sounds/dtmf.mp3').play();\"><div>9</div><span>WXYZ</span></button></td></tr>";
	        html += "<tr><td><button class=dtmfButtons onclick=\"phone.dtmfSend('*');new Audio('../sounds/dtmf.mp3').play();\">*</button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('0');new Audio('../sounds/dtmf.mp3').play();\">0</button></td>";
	        html += "<td><button class=dtmfButtons onclick=\"phone.dtmfSend('#');new Audio('../sounds/dtmf.mp3').play();\">#</button></td></tr>";
	        html += "</table>";
	        html += "</div>";

	        $.jeegoopopup.open({
			html: html,
			width: "auto",
			height: "auto",
			left: leftPos,
			top: topPos,
			scrolling: 'no',
			skinClass: 'jg_popup_basic',
			overlay: true,
			opacity: 0,
			draggable: true,
			resizable: false,
			fadeIn: 0
	        });

	        $("#jg_popup_overlay").click(function() { $.jeegoopopup.close(); });
	        $(window).on('keydown', function(event) { if (event.key == "Escape") { $.jeegoopopup.close(); } });
        }

	function createMediaControls(video) {

		let controls = document.createElement("div");
		controls.className = "media-controls";

                if (video.srcObject.local == true) {
		        let sendPin = document.createElement("button");
                        sendPin.className = "mediaControlBtn";
                        sendPin.id = "sendPinBtn";
		        sendPin.innerHTML = '<i class="fa fa-keyboard-o" aria-hidden="true" title="Show Keypad"></i>';
                        sendPin.onclick = function() { dtmfMenuShow(); }

		        controls.appendChild(sendPin);
                }

		let audioTracks = video.srcObject.getAudioTracks();
		if (audioTracks.length > 0) {
                        let muteAudio = document.createElement("button");
                        muteAudio.className = "mediaControlBtn";
                        muteAudio.innerHTML = '<i class="fa fa-microphone-slash" aria-hidden="true" title="Mute Audio"></i>';
			muteAudio.setAttribute("state", "Unmute");
			muteAudio.onclick = function() {
				let state = this.getAttribute("state");
                                if (state == "Mute") {
                                    this.setAttribute("state", "Unmute");
                                    this.innerHTML = '<i class="fa fa-microphone-slash" aria-hidden="true" title="Mute Audio"></i>';
                                } else if (state == "Unmute") {
                                    this.setAttribute("state", "Mute");
                                    this.innerHTML = '<i class="fa fa-microphone" aria-hidden="true" title="Unmute Audio"></i>';
                                }

				mute(video.srcObject, {audio: this.getAttribute("state") == "Mute"});
			};
			controls.appendChild(muteAudio);
		}

		let videoTracks = video.srcObject.getVideoTracks();
		if (videoTracks.length > 0) {
                        let muteVideo = document.createElement("button");
                        muteVideo.className = "mediaControlBtn";
                        muteVideo.innerHTML = '<i class="fa fa-ban" aria-hidden="true" title="Mute Video"></i>';
			muteVideo.setAttribute("state", "Unmute");
			muteVideo.onclick = function() {
				let state = this.getAttribute("state");
                                if (state == "Mute") {
                                    this.setAttribute("state", "Unmute");
                                    this.innerHTML = '<i class="fa fa-ban" aria-hidden="true" title="Mute Video"></i>';
                                } else if (state == "Unmute") {
                                    this.setAttribute("state", "Mute");
                                    this.innerHTML = '<i class="fa fa-video-camera" aria-hidden="true" title="Unmute Video"></i>';
                                }

				mute(video.srcObject, {video: this.getAttribute("state") == "Mute"});
			};
			controls.appendChild(muteVideo);

                        if (video.srcObject.local == true) {
                                let ScreenShare = document.createElement("button");
                                ScreenShare.className = "mediaControlBtn";
                                ScreenShare.innerHTML = '<i class="fa fa-desktop" aria-hidden="true" title="Share Screen"></i>';
				ScreenShare.onclick = function() {
					phone.ShareScreen();
				};

				controls.appendChild(ScreenShare);

                                let VideoShare = document.createElement("button");
                                VideoShare.className = "mediaControlBtn";
                                VideoShare.innerHTML = '<i class="fa fa-video-camera" aria-hidden="true" title="Share Camera"></i>';
				VideoShare.onclick = function() {
					phone.ShareVideo();
				};

				controls.appendChild(VideoShare);
                        }

                        let fullScreen = document.createElement("button");
                        fullScreen.className = "mediaControlBtn";
                        fullScreen.innerHTML = '<i class="fa fa-expand" aria-hidden="true" title="Full Screen"></i>';
			fullScreen.onclick = function() {
			    this.fullScreen.request();					
			};

			fullScreen.fullScreen = new FullScreen(video);
			controls.appendChild(fullScreen);
		}
		return controls;
	}

	function createMediaView(stream) {

		var mediaView = document.createElement("div");
		mediaView.className = "media-view";
		mediaView.id = "new-media-view"+stream.id;
                mediaView.style.width = localStorage.getItem("VidConfWindowWidth")+"%";

		var videoView = document.createElement("div");
                videoView.className = "video-view";
                videoView.id = "video-view"+stream.id;

		var video = document.createElement("video");
                video.className = "videoElem";
                video.id = "locVideo"+stream.id;
		video.autoplay = true;

		video.srcObject = stream;
		video.onloadedmetadata = function() {
		      let tracks = stream.getVideoTracks();

		      for (let i = 0; i < tracks.length; ++i) {
			   tracks[i].enabled = true;
		      }
		};

		if (stream.local == false) {
			function checkForVideo() {
				if (video.videoWidth < 10 || video.videoHeight < 10) {
                                    mediaView.style.display = 'none';
				    return;
				}
                                mediaView.style.display = 'inline';
			}
                        checkForVideo();
			setInterval(checkForVideo, 1000);
		}

		// Video elements connected to local streams will by default
		// echo both the video and the audio back to ourselves. Since
		// we don't want to hear ourselves we mute it, which mutes only
		// the audio portion.

		if (stream.local == true) {
			video.muted = true;
		} else if (mvcount == 0) {
                        // We hide our own remote video track
                        mvcount = 1;
                        document.getElementById(mediaView.id).style.display = 'none';
                }

		videoView.appendChild(video);
		mediaView.appendChild(videoView);
		mediaView.appendChild(createMediaControls(video));

		return mediaView;
	}

	function removeMediaView(parent, stream) {
		let node = findMediaView(parent, stream);
		if (node) {
			parent.removeChild(node);
		}
	}

	function getValue(id) {
		let obj = document.getElementById(id);
		return obj.value ? obj.value : obj.placeholder;
	}

        document.getElementById("connect").addEventListener("click", function() {
		if (document.getElementById("connect").value == "Disconnect") {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = true;
			document.getElementById("connect").value = "Disconnecting";
			document.getElementById("connect").disabled = true;

			phone.disconnect();
			return;
		}

                phone = new ConferencePhone(sip_username, sip_username, sip_password, wss_server, stun_server, true);

                sip_password = '';

		phone.handle("connected", function () {

			if (document.getElementById("connect").value != "Disconnect") {
				document.getElementById("connect").value = "Registering";
			} else {
				document.getElementById("connect").value = "Disconnect";
				document.getElementById("connect").disabled = false;
				document.getElementById("call").disabled = false;
			}
		});

		phone.handle("disconnected", function () {
			document.getElementById("connect").value = "Connect";
			document.getElementById("connect").disabled = false;
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = true;
		});

		phone.handle("registered", function () {
			document.getElementById("connect").value = "Disconnect";
			document.getElementById("connect").disabled = false;
			document.getElementById("call").disabled = false;
		});

		phone.handle("registrationFailed", function () {
			phone.disconnect();
		});

		phone.handle("incoming", function (reason) {
			document.getElementById("call").value = "Answer";
		});

		phone.handle("failed", function (reason) {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = false;
		});

		phone.handle("ended", function (reason) {
			document.getElementById("call").value = "Call";
			document.getElementById("call").disabled = document.getElementById("connect").value == "Connect";
		});

		phone.handle("streamAdded", function (stream) {
			document.getElementById("media-views").appendChild(createMediaView(stream));
			document.getElementById("call").value = "Hangup";
			document.getElementById("call").disabled = false;
                        document.getElementById("call").style.display = 'inline';
                        document.getElementById("fullscreen").style.display = 'inline';
                        document.getElementById("fullscreen").innerHTML = '<i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen';
		});

		phone.handle("streamRemoved", function (stream) {
			removeMediaView(document.getElementById("media-views"), stream);
		});

		phone.connect();

		document.getElementById("connect").disabled = true;
		document.getElementById("connect").value = "Connecting";
	});

        document.getElementById("connect").click();

        let constraints = { video: true, audio: true };
        navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
            phone.call(videoConfExtension);
        }).catch(function(err) { });

        let node = document.getElementById("call");

        if (node.value == "Answer") {
	    node.disabled = true;
	    node.value = "Hangup";
	}

        document.getElementById("call").addEventListener("click", function() {
            if (node.value == "Hangup") {
	        phone.terminate();
                document.getElementById("call").remove();
                window.close();
                document.getElementsByTagName("body")[0].innerHTML = '<h4 style="text-align:center;color:#595959;">You have closed the video conference call ! If you want to enter the conference again, just press the button from below:</h4><button class="enterConfExt" onclick="window.location.reload()">Enter Conference Again</button><h4 style="text-align:center;color:#595959;">Otherwise, you can close this browser tab.</h4>';
            }
        });

	$("#showConnectionBttns").click(function() {
	  if ($("#connection").is(':visible')) {
	      $("#connection").hide();
	      $("#showConnectionBttns").html('<i class="fa fa-caret-down" aria-hidden="true"></i>');
	  } else { 
	      $("#connection").show();
	      $("#showConnectionBttns").html('<i class="fa fa-caret-up" aria-hidden="true"></i>');
	  }
	});

	document.addEventListener("fullscreenchange", onFullScreenChange, false);
	document.addEventListener("webkitfullscreenchange", onFullScreenChange, false);
	document.addEventListener("mozfullscreenchange", onFullScreenChange, false);

	function onFullScreenChange() {
	   if (document.mozFullScreenElement != null || document.webkitFullscreenElement != null || document.fullscreenElement != null) {
	       document.getElementById("fullscreen").innerHTML = '<i class="fa fa-compress" aria-hidden="true"></i><b>&nbsp; Exit Fullscreen';
	       document.getElementById("fullscreen").style.width = "148px";
	   } else { 
	       document.getElementById("fullscreen").innerHTML = '<i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen';
	       document.getElementById("fullscreen").style.width = "117px";
	   }
	}

}; // window.onload

window.onbeforeunload = function() {
       phone.terminate();
}; 

window.onunload = function() {
       if (phone) {
	   phone.disconnect();
       }
}; // window.onunload

</script>
</head>
<body>
	<div id="connection">
               <div id="VideoConferenceLogo"><img src="../images/small-logo.svg" /></div>
	       <input type="button" id="connect" class="connect" value="Connect" style="display:none;" />
               <button id="call" class="call"><i class="fa fa-phone" aria-hidden="true"></i><b>&nbsp; Hangup</b></button>
               <button id="fullscreen" class="fullscreen" onclick="toggleFullScreen(document.body)"><i class="fa fa-expand" aria-hidden="true"></i><b>&nbsp; Fullscreen</b></button>
	</div>
        <div id="showConnectionBttns"><i class="fa fa-caret-down" aria-hidden="true"></i></div>
       <div id="media-views" class="media-views"></div>

<script type="text/javascript">

FullScreen.prototype.request = function() {
	if (this.is()) {
		return;
	}

	if (this._obj.requestFullscreen) {
		this._obj.requestFullscreen();
	} else if (this._obj.mozRequestFullScreen) {
		this._obj.mozRequestFullScreen();
	} else if (this._obj.webkitRequestFullScreen) {
		this._obj.webkitRequestFullScreen();
	} else if (this._obj.msRequestFullscreen) {
		this._obj.msRequestFullscreen();
	}

	this.setData(true);
};

function toggleFullScreen(elem) {

    if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) ||
       (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
        if (elem.requestFullScreen) {
            elem.requestFullScreen();
        } else if (elem.mozRequestFullScreen) {
            elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullScreen) {
            elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
        } else if (elem.msRequestFullscreen) {
            elem.msRequestFullscreen();
        }

    } else {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

</script>
</body>
</html>

<?php

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

?>
