<?php

//////////////////////////////////////////////////////////////
//===========================================================
// passthrough_theme.php
//===========================================================
// SOFTACULOUS VIRTUALIZOR
// Version : 1.0
// Inspired by the DESIRE to be the BEST OF ALL
// ----------------------------------------------------------
// Started by: Sumeet Boga
// Ended by: Pawan Battu
// Date:       1th jan 2022
// 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 passthrough_theme(){

	global $theme, $servers, $globals, $kernel, $users, $l, $error, $done, $passthroughs, $not_deleted;

	softheader($l['<title>']);
						
	$buttons = array(
		0 => array(
			'name' => __('Add device'),
			'act'  => 'addpassthrough'
		)
	);

	$GLOBALS['breadcrumbs'] = array('dashboard', 'lm_passthrough', 'lms_passthrough');
	
	echo page_header(__('Passthrough Devices'), 'fab fa-usb', '', 1, 0, $buttons);
	
	error_handle($error);

	echo '<script language="javascript" type="text/javascript"><!-- // --><![CDATA[

	//execute function
	exec = (finalData) => {
		$("#progress_bar").show();
		$.ajax({
			type: "POST",
			url: "'.$globals['index'].'act=passthrough&api=json",
			data : finalData,
			dataType : "json",
			success: function(data){
				$("#progress_bar").hide();
				//console.log(data);
				if("passthrough_vpses" in data){
					$("#dev_id").val("");
					let options = "";
					for(opt in data["passthrough_vpses"]){
						
						options += "<option value="+data["passthrough_vpses"][opt]["vpsid"]+">"+data["passthrough_vpses"][opt]["vpsid"]+" - "+data["passthrough_vpses"][opt]["hostname"]+"</otion>";
						$("#vpsid").html(options);
					}
					$("#attach_device").modal("show");
					$("#dev_id").val(data["device_id"]);
				}
				if("done" in data){
					setTimeout(function(){showalert("'.__J('The action was completed sucessfully').'");
					$("#alert-modal").on("hidden.bs.modal", function (e) {
						location.reload(true);
					});} ,200);
				}
				if("error" in data){
					var errstr = "'.__J('The following errors were found').'"+"<br>";
					for(x in data["error"]){
						//console.log(data["error"][x]);
						errstr += "<br>"+data["error"][x];
					}
					setTimeout(function(){showalert(errstr,"1");} ,200);
				}

				if("fatal_error_text" in data){
					setTimeout(function(){showalert(data["fatal_error_text"],"1");} ,200);
				}
			},
			error: function(data) {
				$("#progress_bar").hide();
				return false;
			}
		});
	}
	
	perform_operation = (pid , ele, vpsid = 0) =>{
		// List of ids to delete
		var usr_list = new Array();
		var operation_types = {deactivate: "deactivate", activate: "activate", delete: "delete", attach: "attach", detach: "detach"};
		let passthrough_type = operation_type = warn = 0;
		if(pid === 0){
			
			if($(ele).parent().prev().find("select").val() == 0){
				showalert("'.__J('No action selected !').'" ,"1");
				return false;
			}
			
			// Multi select action
			var action = $(ele).parent().prev().find("select").val();
			operation_type = operation_types[action];

			$(".ios:checked").each(function() {
				usr_list.push($(this).val());
				passthrough_type = (Array.isArray($(this).val().match(/(pci)+/)) ? "pci" : "usb"); 
			});
			
		}else{

			passthrough_type = (Array.isArray(pid.match(/(pci)+/)) ? "pci" : "usb"); 
			if((ele.getAttribute("data-attach")) == 1){
				action = "detach";
				//console.log(vpsid);
				if(vpsid == 0){
					showalert("'.__J('No VPS Found').'" ,"1");
					return false;
				}
			}else if((ele.getAttribute("data-attach")) == 0){
				action = "attach";
			}else{
				action = "delete"
			}

			usr_list.push(pid);
			operation_type = operation_types[action];
			

			var act_val = "'.__J('Delete').'";
			
			if(usr_list.length < 1){
				showalert("'.__J('Nothing selected !').'" ,"1");
				return false;
			}
		}
		
		if(usr_list.length < 1){
			showalert("'.__J('Nothing selected !').'" ,"1");
			return false;
		}
		//console.log(operation_type);
		if(operation_type.match(/^activate$/i)){
			warn = (passthrough_type.match(/usb/i)) ? "'.__J('activate').'" : "'.__J('Activating the PCI device will in turn activate all its peer IOMMU group PCI devices in the database.').'" ;
			warn = (pid === 0 ) ? "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item(s)').'" : "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item').'"
		}else if(operation_type.match(/^deactivate$/i)){
			warn = (passthrough_type.match(/usb/i)) ? "'.__J('deactivate').'" : "'.__J('Deactivating the PCI device will in turn deactivate all its peer IOMMU group PCI devices in the database.').'" ;
			warn = (pid === 0 ) ? "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item(s)').'" : "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item').'"
		}else if(operation_type.match(/^attach$/i)){
			warn = (passthrough_type.match(/usb/i)) ? "'.__J('attach').'" : "'.__J('attach').'" ;
			warn = (pid === 0 ) ? "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item(s)').'" : "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item').'"
		}else if(operation_type.match(/^detach$/i)){
			warn = (passthrough_type.match(/usb/i)) ? "'.__J('detach').'" : "'.__J('detach').'" ;
			warn = (pid === 0 ) ? "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item(s)').'" : "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item').'"
		}else if(operation_type.match(/^delete$/i)){
			warn = (passthrough_type.match(/^usb$/i)) ? "'.__J('Delete').'" : "'.__J('Deleting the PCI device will in turn delete all its peer IOMMU group PCI devices in the database.').'" ;
			warn = (pid === 0 ) ? "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item(s)').'" : "'.__J('Are you sure, you want to ').'" + warn + "'.__J(' the selected item').'"
		}

		showalert(warn ,"3" ,function(confirm){
			if(confirm == false){
				return false;
			}else{
				let finalData = new Object();
				finalData[operation_type] = usr_list.join(",");
				if(action.match(/^detach$/i)){
					finalData["passthrough_vpsid"] = vpsid;
				}
				exec(finalData);
			}
		});
		
		return false;
	};

	attach_passthrough = () => {
		let dev_id = $("#dev_id").val();
		let vpsid = $("#vpsid").val();

		if(dev_id && vpsid){
			//console.log(dev_id+" "+vpsid);
			let warn = "'.__J('Are you sure, you want to ').'" + "'.__J('Passthrough Device').'" + "'.__J(' the selected item').'";
			let finalData = new Object();

			showalert(warn ,"3" ,function(confirm){
				if(confirm == false){
					return false;
				}else{
					let finalData = new Object();
					finalData["passthrough_dev"] = dev_id;
					finalData["passthrough_vpsid"] = vpsid;
					$("#attach_device").modal("hide");
					exec(finalData);
				}
			});
		}else{
			setTimeout(function(){showalert("error","1");} ,200);
		}
	}

	// ]]></script>
	<div class="card mx-3 p-2">
	<div id="showsearch" style="display:'.(optREQ('search') || (!empty($passthroughs) && !empty($globals['showsearch'])) ? "" : "none").';">
		<form accept-charset="'.$globals['charset'].'" name="passthrough" method="GET" action="" class="form-horizontal">
			<input type="hidden" name="act" value="passthrough">
			<div class="form-group_head">
				<div class="row mx-auto w-100">
					<div class="col-sm-3"></div>
					<div class="col-sm-3">
						<label>'.__('ID').'</label>
						<input type="text" class="form-control" name="pid" id="pid" size="15" value="'.REQval('pid','').'" />
					</div>
					<div class="col-sm-3">
						<label>'.__('Search device').'</label>&nbsp;<i class="fas text-primary fa-info-circle" tooltip="'.__('You can do a Wildcard search using *<br>e.g. abc* will match emails starting with abc').'"></i>
						<input type="text" class="form-control" name="pname" id="pname" size="30" value="'.REQval('pname', '').'"/> &nbsp;
					</div>
				</div>
				<div class="row mx-auto w-100 my-2">
					<div class="col-sm-12 sm_space text-center"><input type="submit" class="go_btn mt-2" name="search" value="'.__('Save Settings').'"/></div>
				</div>
			</div>
		</form>
	</div>';

	if($done){
		show_alert(empty($not_deleted) ? __('Passthrough device(s) deleted successfully') : __('Following device ids are assigned to the VPS(s), hence not deleted: '.implode(',', $not_deleted)));
	}
	
	if(empty($passthroughs) && empty($error)){
		optREQ('search') ? show_alert(__('No results were found for your search query'), "2") : "";
		echo '<div class="notice"><b>NOTE : </b>&nbsp; '.(optREQ('search') ? __('No results were found for your search query') : __('There are no passthrough Devices. <a href="index.php?act=addpassthrough">Add a device now</a>')).'</div>';
	}elseif(!empty($passthroughs)){
		echo'<div class="row mx-auto w-100 mt-3">
			<div class="col-sm-8 col-lg-8 col-md-6 d-flex align-items-center mb-3 p-0">';
				page_links($globals['num_res'], $globals['cur_page'], $globals['reslen']);
			echo'
			</div>
			<div class="col-sm-4 col-lg-4 col-md-6 text-right mb-3">
				<div class="bottom-menu float-right w-100">
					<div class="row my-auto">
						<div class="p-0">
							<label>'.__('With Selected').'</label>
						</div>
						<div class="col p-0">
							<select name="user_task_select" id="user_task_select" class="custom-select">
								<option value="0">---</option>
								<option value="delete">'.__('Delete').'</option>
								<option value="activate">'.__('Activate').'</option>
								<option value="deactivate">'.__('Deactivate').'</option>
							</select>
						</div>
						<div class="pl-2">
							<input type="submit" id ="user_submit" class="go_btn" name="user_submit" value="'.__('Go').'" onclick="perform_operation(0, this); return false;">
						</div>
					</div>
				</div>
			</div>
		</div>
		<form accept-charset="'.$globals['charset'].'" name="multi_passthroughs" id="multi_passthroughs" method="post" action="">
		<div class="w-100 mx-auto sticky">
		<table align="center" cellpadding="8" cellspacing="1" border="0" width="95%" class="table table-hover tablesorter common-table" class="form-horizontal">
		<tr class="table_heading">
			<th class="z-index-1 min_width">
				'.get_checkbox('select_all', '', 'select_all', array('chk_it' => 0), '', 'select_all').'
			</th>
			<th class="min_width">'.__('ID').'</th>
			<th class="min_width">'.__('Type').'</th>	
			<th width="250">'.__('Name').'</th>	
			<th width="90">Assigned To</th>
			<th class="min_width" align="center">Server</th>
			<th>'.__('Description').'</th>
			<th class="min_width">'.__('Status').'</th>
			<th align="right" colspan="3" class="min_width text-right pr-3">'.__('Manage').'</th>
		</tr>';

		$i = 1;
		
		foreach($passthroughs as $k => $v){	

			if(!empty($v['status'])){  	 	 
				$status_img = '<h5 class="p-0 m-0"><a class="badge badge-success">'.__('Active').'</a></h5>';
			}else{  	 	 
				$status_img = '<h5 class="p-0 m-0"><a class="badge badge-danger">'.__('Inactive').'</a></h5>';
			}
			echo '<tr>
				<td width="2" valign="middle" align="center">
					'.get_checkbox('passthrough_list[]', '', '', array('chk_it' => 0), $v['type'].$k).'
				</td>
				<td align="center">'.$v['pid'].'</td>
				<td align="center">'.strtoupper($v['type']).'</td>
				<td>'.$v['name'].(preg_match('/pci/', $v['type']) ? '&nbsp;<i class="fas text-primary fa-info-circle" tooltip="IOMMU group : '.(is_null($v['iommu_grp_num']) ? 'NULL': $v['iommu_grp_num']).'"></i></a>' : '').'</td>
				<td>'.(empty($v['vpsid'])? 'None' : "(#{$v['vpsid']}) {$v['hostname']}").'</td>
				<td width="150">'.$servers[$v['serid']]['server_name'].'</td>';
			
				if(empty($v['description'])){
					echo '<td>'.$v['dev_fullname'].'</td>';
				}else{
					$desc = _unserialize($v['description']);
					$rom = (!empty($desc['gpu_rom_file']) ? (('<br>'.__('VGA Bios Rom File').' : '.$desc['gpu_rom_file'])) : '');
				
					echo '<td>'.(!empty($desc['description']) ? ((!empty($desc['description']) ? $desc['description'] : $v['dev_fullname'])).$rom :  (__('Description').' : '.$v['dev_fullname']).$rom).'</td>';	
				}
				
				echo'
				<td align="center">'.$status_img.'</td>
				<td width="24" align="center">
					<div class="badge_container">
						<a class="badge badge-manage" href="'.$globals['ind'].'act=editpassthrough&pid='.$k.'" title="'.__('Edit device').'"><i class="fas fa-pencil-alt"></i></a>
						<a class="badge badge-trash" href="javascript:void(0);" onclick="return perform_operation(\''.$v['type'].$k.'\', this);"  title="'.__('Delete device').'"><i class="fas fa-trash"></i></a>
					';
				if($v['type'] == 'usb'){
					if(!empty($v['vpsid'])){
						echo '<a class="badge badge-manage" href="javascript:void(0);" onclick="return perform_operation(\''.$v['type'].$k.'\', this, \''.$v['vpsid'].'\');" data-attach=1 title="'.__('detach').'"><i class="fas fa-unlink"></i></a>';
					}else{
						echo '<a class="badge badge-trash" href="javascript:void(0);" onclick="return perform_operation(\''.$v['type'].$k.'\', this, \''.$v['vpsid'].'\');" data-attach=0 title="'.__('attach').'"><i class="fas fa-link"></i></a>';
					}
				}
				
				echo'
					</div>
				</td>
			</tr>';
			
			$i++;
		}

		echo '</table></div>';
		echo'<div class="row mx-auto w-100 mt-3">
			<div class="col-sm-8 col-lg-8 col-md-6 mb-3 p-0">';
				page_links($globals['num_res'], $globals['cur_page'], $globals['reslen']);
			echo'
			</div>
			<div class="col-sm-4 col-lg-4 col-md-6 text-right mb-3">
				<div class="bottom-menu float-right w-100">
					<div class="row my-auto">
						<div class="p-0">
							<label>'.__('With Selected').'</label>
						</div>
						<div class="col p-0">
							<select name="user_task_select" id="user_task_select" class="custom-select">
								<option value="0">---</option>
								<option value="delete">'.__('Delete').'</option>
								<option value="activate">'.__('Activate').'</option>
								<option value="deactivate">'.__('Deactivate').'</option>
							</select>
						</div>
						<div class="pl-2">
							<input type="submit" id ="user_submit" class="go_btn" name="user_submit" value="'.__('Go').'" onclick="perform_operation(0, this); return false;">
						</div>
					</div>
				</div>
			</div>
		</div>

		</form>

		<div id="progress_bar" style="display:none;">
			<br />
			<center>
				<font id="progress_txt" size="4" color="#222222">'.__('Please wait, Action in Progress.').'</font>
			</center>
			<div class="my-2" align="center">
				<div class="progress w-50">
					<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100">
					</div>
				</div>
			</div>
			<center>
				'.__('You will be notified once the Action is Completed.').'
			</center>
		</div>

		<!--attach modal start-->
		<div class="modal fade" id="attach_device">
			<div class="modal-dialog modal-lg">
				<div class="modal-content">
					<div class="modal-header d-flex align-items-center">
						<span class="modal-title"><label class="control-label">' . __('Passthrough Device') . '</label></span>
						<button type="button" class="close text-white" data-dismiss="modal">&times;</button>
					</div>
					<div class="modal-body" id="attach_device_body">
						<form id="attach_deviceform" action="" method="post">
							<div id="form-container">
								<div class="row mx-auto w-100 my-3">
									<div class="col-sm-4">
										<label class="control-label">' . __('VPS') . '&nbsp;<a class="info" data-placement="right" tooltip="' . __('Choose vps') . '"><i class="fas text-primary fa-info-circle"></i></a></label>
									</div>
									<div class="col-sm-6" id="td_vpsid">
										<select name="vpsid" id="vpsid" class="custom-select virt-select">
										</select>
									</div>
									<input value="" id="dev_id" type="hidden">	
								</div>
							</div>
							<br /><br />
							<center>	
								<input class="go_btn" value="' . __('Passthrough Device') . '" type="button" onclick="return attach_passthrough(this)"/>
							</center>
						</form>
					</div>
				</div>
			</div>
		</div>
		<!--attach modal End-->
		<br />
		<div class="text-center my-4"><a href="'.$globals['ind'].'act=addpassthrough" title="'.__('Add device').'" class="go_btn">'.__('Add device').'</a></div><br>
	';						   
	}// End of else
	
	echo '</div>';

	softfooter();

}