<?php

//////////////////////////////////////////////////////////////
//===========================================================
// letsencrypt_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 letsencrypt_theme(){
    
global $theme, $globals, $cluster, $l, $crt_details, $site_domain, $crt_buts, $crt_config_options, $crt_select_opts, $done, $error, $actid, $flag_task, $servers;

// If flag_task flag is set, then send back actid of the task
if($flag_task){
	echo 'actid = '.$actid;
	$flag_task = 0;
	return;
}

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

$GLOBALS['breadcrumbs'] = ['dashboard', 'lm_ssl', 'lms_installssl'];
										
echo page_header(__('Install SSL'), 'fab fa-expeditedssl', $globals['docs'].'letsencrypt/', 0, 0, '');

echo '<div class="card p-2 mx-3">';

error_handle($error);
echo '<div id="ajax_err"></div>';

// Is it offline ?
$hypervisor_status = $cluster->statewise($globals['server']);
if($hypervisor_status == 0 || $hypervisor_status == 2){
	show_alert($globals['hypervisor_status'][$hypervisor_status] ,"1");
	echo '<div class="e_notice"><b>NOTE : </b>&nbsp; '.$globals['hypervisor_status'][$hypervisor_status].'</div>';
	
}else{
	
	echo '<script>
		function load_form(frm){
			if(frm === undefined){
				return false;
			}
			$.each(frm, function(k, v){
				switch(v.type){
					case "text":
						$("#"+k).val(v.value);
						break;
					case "select":
						$("#"+v.value).prop("selected", true);
						break;
					case "checkbox":
						$("#"+k).prop("checked", v.value);
						break;
					default:
						break;
				}
			});
		}
			
		function show_form(){
		
			$("#processing").css("display", "block");
			
			';
			$config_contents = '<div class="card p-3 m-2">';
			$letsencrypt_lang['ssl_type'] = 'SSL Type';
			$letsencrypt_lang['ssl_type_exp'] = 'select ssl type for the certificate';				
			$letsencrypt_lang['primary_domain'] = 'Primary Domain';
			$letsencrypt_lang['primary_domain_exp'] = 'Primary Domain name for the certificate';
			$letsencrypt_lang['contact_email'] = 'Contact Email';
			$letsencrypt_lang['contact_email_exp'] = 'Email address which will be used by SSL certificate provider to contact domains owner';
			$letsencrypt_lang['key_size'] = 'Key Size';
			$letsencrypt_lang['key_size_exp'] = 'Domains certificate private keys length';
			$letsencrypt_lang['renew_days'] = 'Renew Days';
			$letsencrypt_lang['renew_days_exp'] = 'Minimum days before expiration to automatically renew certificate (must be less than or equal to 80)';
			$letsencrypt_lang['staging'] = 'Staging';
			$letsencrypt_lang['staging_exp'] = 'Use SSL certificate provider\'s Staging (Testing) server to obtain the certificate';
			$letsencrypt_lang['enable_force'] = 'Force';
			$letsencrypt_lang['enable_force_exp'] = 'Force processing certificate';

			foreach($crt_config_options['crt_save_cfg_frm']['inputs'] as $k => $v){
				
				$config_contents .= '<div class="row mx-auto w-100 my-3"> \
				<div class="'.($v['type'] == 'checkbox' ? 'col-5' : 'col-sm-5').'"> \
					<label class="control-label">'.$letsencrypt_lang[$k].'&nbsp;<a class="info" data-placement="right" tooltip="'.preg_quote($letsencrypt_lang[$k.'_exp'], "'").'"><i class="fas text-primary fa-info-circle"></i></a></label> \
				</div>';
				
				switch($v['type']){
					
					case 'text':
						$config_contents .= '<div class="col-sm-7"><input type="text" id="'.$k.'" name="'.$k.'" class="form-control" value="'.$v['value'].'"/></div>';
						break;
						
					case 'select':
						$config_contents .='<div class="col-sm-7" ><select id="'.$k.'" name="'.$k.'" class="custom-select">';
						if(isset($crt_select_opts[$k])){
							foreach($crt_select_opts[$k] as $vv){
								$config_contents .= '<option id="'.$vv.'" name="'.$vv.'" value="'.$vv.'" '.($v['value'] == $vv ? 'selected="selected"' : '').'>'.$vv.'</option>';
							}
						}
						$config_contents .= '</select></div>';
						break;
						
					case 'checkbox':
						$config_contents .= '<div class="col-7"> \
							<div class="custom-control custom-checkbox"> \
								<input type="checkbox" class="ios custom-control-input" id="'.$k.'" name="'.$k.'" '.($v['value'] == true ? 'checked="checked"' : '').'> \
								<label class="custom-control-label" for="'.$k.'"></label> \
							</div> \
						</div>';
						break;
						
					default:
						break;
				}
				
				$config_contents .= '</div>';
			}
			$config_contents .= '<div class="form-group"><div class="col-xs-12 text-center" ><button type="submit" id="save_cfg_id" class="go_btn" onclick="process_req(\\\'save_cfg\\\');" >'.__J('Start Installation').'</button></div><div class="col-xs-12"><div class="text-center" id="processing_form" style="display: none;"><img src="themes/default/images/ajax_remove.gif" /></div></div></div></div>';
			
			echo 'var content = \'<form id="crt_save_cfg_frm" name="crt_save_cfg_frm" class="form-horizontal" role="form" action="" method="POST" onsubmit="return false;">'.$config_contents.'</form>\';
					
			$.ajax({
				url: "'.$globals['index'].'act=installssl&api=json",
				data: "",
				dataType : "json",
				type: "post",
				success: function(response){
					load_form(response.crt_config_options.crt_save_cfg_frm.inputs);
					$("#conf_modal").modal({keyboard: true});
					$("#conf_modal").modal({show:true});
					$("#processing").css("display", "none");
					
				}
			});
			
			$("#conf_modal_body").html(content);
			show_tooltip();
		}
	</script>
	
	<div class="modal fade" role="dialog" id="conf_modal">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header text-center" id="conf_modal_head">
					
					<span class="fhead text-always-white">'.__('SSL Configuration').'</span>
					<button class="close text-always-white" data-dismiss="modal">&times;</button>
				</div>
				<div class="modal-body" id="conf_modal_body" ></div>
			</div>
		</div>
	</div>
	<div class="modal fade" role="dialog" id="logs_modal">
		<div class="modal-dialog modal-lg">
			<div class="modal-content">
				<div class="modal-header text-center" id="logs_modal_head">
					<button class="close" data-dismiss="modal">&times;</button>
					<span class="fhead">'.__('Logs').'</span>
				</div>
				<div class="modal-body" id="logs_modal_body" ></div>
			</div>
		</div>
	</div>';
	echo '<div class="text-center">';
		if(!empty($site_domain) && count($site_domain) == 1){
			echo '<span id="site_domain" class="domain_header">'.implode('', $site_domain).'</span><br />';
		}else{
			echo '<span id="site_domain" class="domain_header">'.$site_domain[0].'</span><br />';
			$tmp_site_domain = $site_domain;
			array_shift($tmp_site_domain);
			echo '<span id="sec_site_domain" class="sec_domain_header">'.implode(',', $tmp_site_domain).'</span><br /><br />';
		}
	echo '
	</div>
	<div class="row w-100 mx-auto">
		<div class="col-sm-12 text-center">
			<div class="btn-group" id="btn-grp1">';
			foreach($crt_buts as $k => $v){
				echo '<button type="button" class="btn" id="'.$k.'_id" onclick="'.($k == 'get_crt' ? 'show_form()' : 'process_req(\''.$k.'\')').'" >'.$v.'</button>';    
			}
			echo '
			</div>
		</div>
	</div>
	<div class="row mx-atuo w-100 my-2" id="processing" style="display: none;" align="center">
		<div class="progress w-25">
			<div class="progress-bar bg-primary progress-bar-striped progress-bar-animated w-100">
			</div>
		</div>
	</div>
	
	<div id="progress_onload"></div><br />
	<div class="w-100 mx-auto sticky">
	<table class="table table-hover" id="crt_details_tbl">
		<tr id="crt_details_tbl_hd">
			<th colspan=2>'.__('SSL Certificate Details').'</th>
		</tr>
		<tr>
			<td class="blue_td" style="width:14%;">'.__('Server').'</td>
			<td><span>'.$servers[$globals['server']]['server_name'].'</span></td>
		</tr>';

		$crt_details_lang['crt_domain'] = 'Domain';
		$crt_details_lang['crt_san'] = 'SAN';
		$crt_details_lang['crt_issuer'] = 'Issued By';
		$crt_details_lang['crt_serialno'] = 'Serial No.';
		$crt_details_lang['crt_valid_from_time'] = 'Valid From';
		$crt_details_lang['crt_valid_to_time'] = 'Valid Till';
		$crt_details_lang['crt_installed'] = 'Installed';
		$crt_details_lang['next_renew'] = 'Next Renew Date';

		foreach($crt_details as $k => $v){
			echo '
			<tr>
				<td class="blue_td">'.$crt_details_lang[$k].'</td>
				<td id= "'.$k.'" class="text-left">'.$v.'</td>
			</tr>';
		}
	echo '</table></div>';
}

echo '</div></div>
	<script>
		var regexp = /^actid/;
		var actid = null;
		var progress = 0;
		var progress_update = "";
		var timer = null;
		var sel_act = "";
		
		$(document).ready(function(){
			progress_onload();';
			if(empty($site_domain)){
				echo '
					$("#site_domain").removeClass("domain_header");
					$("#site_domain").html("<b>'.__J('No Domain configured. Please configure before installing certificate.').'</b>");
					$("#site_domain").addClass("no_domain");
				';
			}
		echo '	
		});
		var cancel_renew_flag = 0;
		function process_req(sel){
			
			var dos = ["get_crt", "renew_crt", "save_cfg", "show_logs"]; 
			$("#progress-cont").hide();
			
			if(dos.indexOf(sel) < 0){
				showalert("'.__J('Invalid option selected').'" ,"1");
				return;
			}
			
			// Disable buttons till certificat is being install
			for(x in dos){
				$("#"+dos[x]+"_id").attr("disabled", "disabled");
			}
			
			$("#processing").css("display", "block");
			var data = "";
			if(sel == "save_cfg"){
				$("#processing_form").css("display", "block");
				data = "opt=save_cfg&"+$("#crt_save_cfg_frm").serialize();
				exec(data,sel,dos);
			}else if(sel == "show_logs"){
				data = "opt="+sel;
				exec(data,sel,dos);
			}else{
				progress = 0;
				data = "opt="+sel;
				sel_act = sel;

				if(sel != "get_crt"){
					showalert("'.__J('Are you sure you want to process this request?').'" ,"3" ,function(confirm){
						if(confirm == false){
							if(empty(cancel_renew_flag)){
								cancel_renew_flag = 0;
								$("#processing").css("display", "none");
							}
							
							for(x in dos){
								//alert(dos[x]);
								$("#"+dos[x]+"_id").removeAttr("disabled");
							}
							return false;
						}else{
							cancel_renew_flag = 1;
							exec(data,sel,dos);
						}
					});
				}else{
					exec(data,sel,dos);
				}
			}
		}
		
		function exec(data,sel,dos){
			$.ajax({
				url: "'.$globals['index'].'act=installssl"+((sel == "save_cfg" || sel == "show_logs") ? "&api=json" : "&jsnohf=1")'.(!empty($_REQUEST['debug']) ? '+"&debug=died"' : '').',
				data: data,
				type: "post",
				success: function(response){
					gettaskscount();
					$("#processing").css("display", "none");
					$("#processing_form").css("display", "none");
					if(sel == "get_crt" || sel == "renew_crt"){
						$("#progress-cont").show();
						if(regexp.exec(response) != null){
							eval(response);
							setTimeout("get_progress(\'letsencrypt\')", 1000);
						}else{
							
							var error_box = $(response).find("#error_box"); 
							$("#ajax_err").html(error_box);
							$("#progress-cont").hide();
						}
					}else{
						response = JSON.parse(response);
						if(response.done){
							gettaskscount();
							
							if(sel == "save_cfg"){
								
								for(var x in response.crt_details){
									$("#"+x).html(response.crt_details[x]);
								}
								
								load_form(response.crt_config_options.crt_save_cfg_frm.inputs);
								$("#conf_modal").modal("hide");
								var primary_domain = $("#primary_domain").val().split(",");
								
								if(primary_domain.length == 1){
									
									// Only primary domain
									$("#site_domain").html(primary_domain);
									$("#site_domain").removeClass("no_domain");
									$("#site_domain").addClass("domain_header");
									
									// No secondary domain so hide that
									$("#sec_site_domain").hide();
								}else{
									
									// For primary domain
									$("#site_domain").html(primary_domain[0]);
									$("#site_domain").removeClass("no_domain");
									$("#site_domain").addClass("domain_header");
									
									// For secondary domain
									primary_domain.shift();
									$("#sec_site_domain").html(primary_domain.join(","));
									$("#sec_site_domain").removeClass("no_domain");
									$("#sec_site_domain").addClass("sec_domain_header");
								}
								process_req("get_crt");
								
							}else if(sel == "show_logs"){
								$("#logs_modal_body").html("<pre class=\"command  mh-100\" >"+response.logs+"</pre>");
								$("#logs_modal").modal({keyboard: true});
								$("#logs_modal").modal({show:true});
								$("#logs_modal").on("hidden.bs.modal", function () {
									for(x in dos){
										$("#"+dos[x]+"_id").removeAttr("disabled");
									}
								});
							}
						}else if(response.error){
							var err = "";
							for(var x in response.error){
								err += response.error[x]+"\n"; 
							}
							showalert(err ,"1");
							for(x in dos){
								$("#"+dos[x]+"_id").removeAttr("disabled");
							}
						}
					}
					
				}
			});
			if(sel == "get_crt" || sel == "renew_crt"){
				$("#error_box").remove();
				$("#pbar").html("'.__J('Initializing').' ( 0% )");			
			}
			$("#progressbar").progressbar({value: 0});
		}
		
		function donecert(){
		
			if(sel_act == "get_crt"){
				showalert("'.__J('Processed $0 Certificate request successfully', array(__J('Get'))).'");
			}else if(sel_act == "renew_crt"){
				showalert("'.__J('Processed $0 Certificate request successfully', array(__J('Renew'))).'");
			}
			$("#progress-cont").hide();';
			
			echo '
			$.ajax({
				url: "'.$globals['index'].'act=installssl&api=json"'.(!empty($_REQUEST['debug']) ? '+"&debug=died"' : '').',
				type: "post",
				success: function(response){
					response = JSON.parse(response);
					if(response.crt_details){
						for(var x in response.crt_details){
							$("#"+x).html(response.crt_details[x]);
						}
					}
				}
			});';
			
			// If the request was for master server then reload the page.
			if($globals['server'] == 0){
				echo 'location.reload(true);';
			}
			
		echo '}

		$(window).resize(function(){
		   if($(window).width() < 750){
			   $("#btn-grp1 button").removeClass("btn-lg");
			   $("#btn-grp1 button").addClass("btn-sm");
		   }else{
			   $("#btn-grp1 button").removeClass("btn-sm");
			   $("#btn-grp1 button").addClass("btn-lg");
		   }
		   
		});
	</script>
'; 
softfooter();

}

?>