<?php

//////////////////////////////////////////////////////////////
//===========================================================
// vscpu_theme.php
//===========================================================
// SOFTACULOUS VIRTUALIZOR
// Version : 1.0
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Alons
// Date:       8th Mar 2010
// Time:       23:00 hrs
// Site:       https://www.virtualizor.com/ (SOFTACULOUS VIRTUALIZOR)
// ----------------------------------------------------------
// Please Read the Terms of use at https://www.virtualizor.com
// ----------------------------------------------------------
//===========================================================
// (c)Softaculous Ltd.
//===========================================================
//////////////////////////////////////////////////////////////

if(!defined('VIRTUALIZOR')){

	die('Hacking Attempt');

}

function mailtouser_theme(){

global $theme, $globals, $cluster, $users, $l, $vpsusage, $available, $vpses, $error, $done, $servergroups, $servers, $users_email;

softheader($l['<title>']);

$GLOBALS['breadcrumbs'] = array('dashboard','lm_users', 'lms_mail');

echo page_header(__('Send Mail'), 'fas fa-paper-plane', '', 0, 0, '', 'ostemplates');

error_handle($error);

if(!empty($done)){
	show_alert(__('Mail was sent successfully'));
}

echo '
<script type="text/javascript" src="'.$theme['url'].'/js/tinymce/tinymce.min.js"></script>
<style type="text/css">
	.mce-tinymce{
		min-width: 370px;
	}
	.mce-fullscreen{
		z-index:1053;
	}
	.usr{
		font-size: 16px;
		color: #444444;
		text-decoration: none;
		height: 30px;
		font-family: OpenSans,Arial, Verdana, Helvetica, sans-serif;
	}
	.cat-wrapper{
		margin: 0px auto !important;
		width:82%;
	}
	.usr label,#plus2{
		cursor:pointer;
		font-weight: normal;
	}
	.usr_small{
		margin-left:4px;
	}
	.usr_small::after{
		content:")";
	}
	.usr_small::before{
		content:"(";
	}
	.to_label{
		color: black;
		height: 5px;
		font-size:14px;
		font-weight: bold;
		margin-top: 5px;
	}
	.subject_label{
		color: black;
		height: 5px;
		font-size:14px;
		font-weight: bold;
		margin-top: 5px;
	}
	.error {
		width: 82%;
		margin: 10px auto;
	}
	.togglediv{
		padding:8px 0px 0px 8px;
	}
	
	label{
		vertical-align: super;
	  	padding-left: 8px;
	}
		
	control-label{
		padding-top: 8px !important;
	}
	
	.adj_ht_cont{
		height : 30px;
		padding : 6px;
		font-size : 12px;
		font-weight : bold;		
	}
	
	.btn.adj_ht_cont{
		height : 22.5px;
		margin : 3px;
		padding : 2px;
		padding-left : 20px;
		padding-right : 20px;		
	}
	
	#toggle_indicator{
		float: left;
		font-size: 1em;
		margin-top: 0px;
	}
	
	.hover_user div{
		padding: 5px;
		margin: 0px;
	}
	
	.hover_user:hover div{
		background-color:#c3c3c3;
	}
	.adj_ht_cont, .adj_ht{
		background-color: #f2f2f2;
	}
	
</style>
<script>
	var users = '.json_encode($users).';
	var users_email = '.json_encode($users_email).';
	var sel_usrs = [];
	var sel_usrs_cnt = 0;
	
	function toggle_div(id){
		if ($("#"+id).is(":hidden")){
			$("#toggle_indicator").html("<span class=\"h4 m-0 pl-2\"> + </span>");
			$("#"+id).slideDown("slow");
		}else{
			$("#toggle_indicator").html("<span class=\"h4 m-0 pl-2\"> - </span>");
			$("#"+id).slideUp("slow");
		}
	}
	
	function get_users(){

		var userType = $("select[name=\'userType[]\']").val();
		var select_servers = $("select[name=\'serid[]\']").val();

		// If no userType/select_servers provided default will be all users
		if(select_servers == null) {
			select_servers = ["-1"];
		}

		if(userType == null) {
			userType = ["-1"];
		}

		var servers = [];
		var groupIds = [];
		var userList = "";
		var usrfilter = [];
		var usrfilter_temp = [];

		// Extract serids and sgids
		for(sid in select_servers){
			let sid_data = select_servers[sid];
			if(sid_data.match(/_group/) != null){
				groupIds.push(sid_data.replace(/_group/, ""));
			} else {
				servers.push(sid_data);
			}
		}

		const servers_set = new Set(servers);
		const groupIds_set = new Set(groupIds);

		// Filter the ids according to given data
		for(var userId in users){

			let include_user =  false;

			if((groupIds.length > 0) && (userType.includes(users[userId][\'type\']) || userType.includes("-1")) && (users[userId]["sgid_list"] != undefined && users[userId]["sgid_list"].some(sgid => groupIds_set.has(sgid)))){
				include_user =  true;
				
			} else if ((users[userId]["serid_list"] != undefined && users[userId]["serid_list"].some(serid => servers_set.has(serid))) && (userType.includes(users[userId][\'type\']) || userType.includes("-1"))) {
			 	include_user =  true;

			} else if(servers.includes("-1") && (userType.includes("-1") || userType.includes(users[userId][\'type\']))){ 
				include_user =  true;

			} else if(servers.includes("-2") && (users[userId]["serid_list"] == undefined) && (userType.includes("-1") || userType.includes(users[userId][\'type\']))){
				include_user =  true;
			}

			if(include_user) {
				usrfilter_temp[userId] = 1;
			}
		}
		
		// Sort Users in ascending order of email
		for(var x in usrfilter_temp){
			if(usrfilter_temp[x]){
				usrfilter.push(x);
			}
		}
		
		usrfilter.sort(function(a, b){
			if(users_email[a] && users_email[b]){
				return users_email[a].localeCompare(users_email[b]);
			}
			return -1;			
		});
		
		email_count = 0;

		userList = \'<div class="col-sm-3 usr"><div class="custom-control custom-checkbox"><input type="checkbox" class="custom-control-input" id="all_users" name="users[]" value="-1"><label class="custom-control-label" for="all_users">&nbsp;'.__J('All Users').'</label></div></div>\';

		for(var x in usrfilter){
			userList += \'<div class="col-sm-3 usr"><div class="custom-control custom-checkbox"><input type="checkbox" class="ios custom-control-input" id="users_\'+x+\'" name="users[]" value="\'+usrfilter[x]+\'"><label class="custom-control-label" for="users_\'+x+\'">&nbsp;\'+users_email[usrfilter[x]]+\'</label></div></div>\';
			email_count++;			
		}
		
		$("#users_count").html(email_count);

		$("#user-list").html(userList);
		
		if($("#user-list").html() == ""){
			if($("#user-list").css("display") == "block"){
				toggle_div(\'user-list\');
				toggle_div(\'user-list-options\');
			}
			return;
		}

		if($("#user-list").css("display") == "none"){
			toggle_div(\'user-list\');
			toggle_div(\'user-list-options\');
		}
	}
	
	function process_users_slist(action, uid){
		
		if(action == "add"){
			$("#select_all").prop("checked", false);
			chk = $("#user-list input:checked");

			if(chk.length < 1){
				showalert("'.__J('No Users Selected').'" ,"1");
				return false;
			}

			for(var i = 0; i < chk.length; i++){
				var va = chk[i].value;
				sel_usrs[va] = 1;
				if((va == "-1") || (sel_usrs["-1"] == 1)){
					sel_usrs = {"-1" : 1};
					users_email["-1"] = "'.__J('All Users').'";
					break; 
				};
			}
		}else if(action == "remove"){
			if(uid){
				delete sel_usrs[uid];
			}else{
				sel_usrs = [];
				sel_usrs_cnt = 0;
			}
		}
		
		var sel_usr_str = "";
		var sel_usrs_cnt1 = 0;
		
		for(var k in sel_usrs){
			sel_usr_str += "<div class=\"col-sm-3 p-0 hover_user\" id="+k+"><div class=\"row w-100\"><div class=\"col-10 p-0\" >"+users_email[k]+"</div><div class=\"col-2 text-right pr-3 py-0 cursor-pointer\" onclick=\"process_users_slist(\'remove\', "+k+")\" >X</div></div></div>";
			sel_usrs_cnt1++;
		}

		sel_usrs_cnt1 = (sel_usrs["-1"] == 1) ? $("#user-list").children().length - 1 : sel_usrs_cnt1;

		if((sel_usrs_cnt1 == 0) && (action == "add")){
			sel_usrs = [];
			sel_usr_str = "";
			showalert("'.__J('No Users Found').'" ,"1");
		} else if(sel_usrs_cnt == sel_usrs_cnt1){
			showalert("'.__J('User(s) already added!').'" ,"1");
		}else{
			sel_usrs_cnt = sel_usrs_cnt1;
		}
		
		$("#to_div").html(sel_usr_str);
		$("#usr_selected_count").html(sel_usrs_cnt1);
		$("#hidden_users").val(Object.keys(sel_usrs).toString());
		get_users();
	}

	function clear_fields(){
		sel_usrs = [];
		sel_usrs_cnt = 0;
		$("#to_div").html("");
		$("#usr_selected_count").html(0);
		$("#hidden_users").val("");
	}
	
	function plus_onmouseover(id){
		$("#"+id).attr("src", "'.$theme['images'].'admin/plus_hover.gif");
	}

	function plus_onmouseout(id){
		$("#"+id).attr("src", "'.$theme['images'].'admin/plus.gif");
	}

	tinymce.init({
		selector:"textarea",
		plugins: [
			"advlist autolink lists link image charmap print preview hr anchor pagebreak",
			"searchreplace wordcount visualblocks visualchars code fullscreen",
			"insertdatetime nonbreaking save table contextmenu directionality",
			"emoticons template paste textcolor"
		],
		toolbar1: "insertfile undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent blockquote| link image",
		toolbar2: "preview media | forecolor backcolor emoticons | formatselect fontselect fontsizeselect "
	});
	
	function validate_form(){
		
		if($("#mail [name=users]").val().trim() == ""){
			showalert("'.__J('No user selected').'" ,"1");
			return false;
		}
		
		if($("#mail [name=subject]").val().trim() == ""){
			showalert("'.__J('Please enter Subject').'" ,"1");
			return false;
		}
		
		return true;
	}
	
	$(document).ready(function(){
		get_users();
	});
	
</script>
<form id="mail"  accept-charset="'.$globals['charset'].'" action="" method="post" name="mail" class="form-horizontal" onsubmit="return validate_form();">
<div class="card p-2 mx-3">
	<div class="adj_ht row mx-auto w-100 my-3 border d-flex align-items-center">
		<div class="col-2 adj_ht_cont text-center">
			<label class="control-label" for="serid">'.__('Server').'</label>
		</div>
		<div class="col-10 p-0">';

			$POSTserid = (array_key_exists('serid', $_POST) && !empty($_POST['serid'])) ? $_POST['serid'] : [];

			echo '
			<select id="serid" class="form-control" name="serid[]" size="8" onchange="clear_fields();get_users();" multiple="multiple">

				<option value="-1" '.((empty($POSTserid) || in_array(-1, $POSTserid)) ? 'selected="selected"' : '').'>'.__('All Servers').'</option>
				<option value="-2" '.(in_array(-2, $POSTserid) ? 'selected="selected"' : '').'>'.__('No Server').'</option>';
				
				foreach ($servergroups as $k => $v){
					echo '<option class="fhead" value="'.$k.'_group" '.(in_array($k.'_group', $POSTserid) ? 'selected="selected"' : '').'>[Group]&nbsp;'.$v['sg_name'].'</option>';
					
					foreach ($servers as $m => $n){
						if($n['sgid'] == $k){
							echo '<option value="'.$n['serid'].'" '.(in_array((string)$n['serid'], $POSTserid) ? 'selected="selected"' : '').'>&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;'.$n['server_name'].'</option>';
						}
					}
				}
		echo '</select>
		</div>
	</div>
	<div class="adj_ht row mx-auto w-100 my-3 border d-flex align-items-center">
		<div class="col-2 adj_ht_cont text-center"><label class="control-label" for="userType" >'.__('Type').'</label></div>
		<div class="col-10 p-0">';

			$POSTuserid = (array_key_exists('userType', $_POST) && !empty($_POST['userType'])) ? $_POST['userType'] : [];

			echo '<select class="form-control w-100" name="userType[]" id="userType" onchange="clear_fields();get_users();" multiple="multiple">
				<option value="-1" '.((empty($POSTserid) || in_array(-1, $POSTserid)) ? 'selected="selected"' : '').'>'.__('all').'</option>';
				
				foreach(['User', 'Admin', 'Cloud'] as $key => $type){
					echo '<option value="'.$key.'" '.(in_array($key, $POSTuserid) ? 'selected="selected"' : '') .'>'.__($type).'</option>';
				}

			echo '
			</select>
		</div>
	</div>
	<div class="row mx-auto w-100 mt-3 adj_ht border">
		<div id="toggle_indicator" class="col-xs-4 text-left d-flex align-items-center cursor-pointer" onclick="toggle_div(\'user-list\');toggle_div(\'user-list-options\');"><span class="h4 m-0 pl-2"> - </span></div>
		<div class="col-xs-4 text-center adj_ht_cont" >'.__('User List').'&nbsp;&nbsp;(<span id="users_count"></span>)</div>
	</div>
	<div id="user-list" class="row mx-auto w-100 mh-50 pt-2 overflow-auto" class="togglediv row w-100"></div>
	<div class="row mx-auto w-100 my-3 adj_ht p-1" id="user-list-options">
		<div class="col-xs-6 text-center adj_ht_cont d-flex align-items-center">
			'.get_checkbox('select_all', __('Select All'), 'select_all', array('chk_it' => 0), '', 'select_all').'
		</div>
		<div class="col-xs-6 text-center adj_ht">
			<button type="button" class="btn py-1" onclick="process_users_slist(\'add\')" >'.__('Add').'</button>
		</div>
	</div>
	

	<input type="hidden" name="users" id="hidden_users"/>
	<div>
		<div class="row mx-auto w-100 my-3 adj_ht">
			<div class="col-2 text-center adj_ht_cont">
				<label class="to_label m-0 p-0">'.__('To').'</label>
			</div>
			<div class="col-10 overflow-auto border" name="to">
				<div id="to_div" class="row mx-auto w-100 m-0" ></div>
			</div>
			<div class="row mx-auto w-100 mt-5 mb-1 adj_ht">
				<div class="col-xs-6 text-center adj_ht_cont" >'.__('Users Selected').': <span id="usr_selected_count">0</span></div>
				<div class="col-xs-6 text-center" >
					<button type="button" class="btn py-1" onclick="process_users_slist(\'remove\'); return false;" >'.__('Remove All').'</button>
				</div>
			</div>
		</div>

		<div class="notice" align="left"><span><b> '.__('Note').' : </b> &nbsp; '.__('You can use the following Variables (One Variable at a time) :<br>
<strong>{{hostname}}</strong> : Hostnames of the User VPS(s) on that Server/Server Group<br>
<strong>{{ip}}</strong> : IPs of the User VPS(s) on that Server/Server Group<br>
<strong>{{hostname_ip}}</strong> : Hostname (IP) of the User VPS(s) on that Server/Server Group<br>').'</span></div>
		
		<div class="row mx-auto w-100 my-3 adj_ht border">
			<div class="col-sm-2 adj_ht_cont" >
				<label for="subject">'.__('Subject').'</label>
			</div>
			<div class="col-sm-10 m-0 p-0">
				<input type="text" id="subject" class="form-control" name="subject" maxlength="180"/>
			</div>
		</div>
	</div>
	
	<textarea rows="20" name="mailbox"></textarea>
	
</br>
</br>
<center><input type="submit" name="submit" value="'.__('Submit').'" class="go_btn mt-3"/></center><br>
</form>

</div>
</div>
';
softfooter();

}

?>
