<?php

if(!defined('VIRTUALIZOR')){
	die('Hacking Attempt');
}

function log_rotation_theme(){

global $globals, $l, $log_rotate_config, $rotate_data, $theme, $done, $error;

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

$GLOBALS['breadcrumbs'] = ['dashboard', 'lms_logs', 'lms_log_rotation'];
					
echo page_header(__('Log Rotation'), 'fas fa-laptop-code ');

error_handle($error);
	
if(!empty($done)){
	show_alert(__('Logrotation configuration saved successfully'), '', 'log_rotation');
}

echo '<script type="text/javascript" charset="utf8" src="'.$theme['url'].'/js/cronstrue.min.js"></script>
<script language="javascript" type="text/javascript"><!-- // --><![CDATA[

	let selected_cron_type = "";';

	if($rotate_data['logrotate_cron_type']){
		echo 'selected_cron_type = \''.$rotate_data['logrotate_cron_type'].'\'
		$("#cron_type").val(selected_cron_type);';
	}

	echo '
	$(document).ready(function(){
		$("input:radio").change(function(event){
			
			const value = $(this).val();
			
			if(!(["monthly", "weekly", "daily", "hourly"].includes(value))) {
				return false;
			}

			$("#months, #dates, #days, #hrs, #mins").trigger("reset");		
			$("#converted_cron").text("");
			
			$(".chosen, #months, #dates, #days").select2({
				"width" : "100%"
			});

			get_cron_msg();

			selected_cron_type = value;

			if(!empty(selected_cron_type)){
				$("#cron_type").val(selected_cron_type);
			}

			$("#rotate_month, #rotate_date, #rotate_day, #rotate_hour, #rotate_time").hide();

			if(value == "monthly"){
				$("#rotate_month, #rotate_date, #rotate_time").show();
			} else if(value == "weekly"){
				$("#rotate_day, #rotate_time").show();
			} else if(value == "hourly"){
				$("#rotate_hour").show();
			} else{
				$("#rotate_time").show();
			}
		});
	});

	function get_cron_msg(){

		if($("#freqm").prop("checked") == true){

			let months = new Array();
			let dates = new Array();

			if(!empty($("#months").val())){
				if(Object.values($("#months").val()).indexOf("1-12") > -1){
					$("#months").val("").val("1-12").select2({width : "100%"})
					months = "1-12";
				}else{
					months = Object.values($("#months").val()).join(",");
				}
			}

			if(!empty($("#dates").val())){
				if(Object.values($("#dates").val()).indexOf("1-31") > -1){
					$("#dates").val("").val("1-31").select2({width : "100%"})
					dates = "1-31";
				}else{
					dates = Object.values($("#dates").val()).join(",");
				}
			}

			if(empty(months)){
				months = "*";
			}

			if(empty(dates)){
				dates = "*";
			}

			let hrs = $("#hrs").val();
			let mins = $("#min").val();
			expression = mins+" "+hrs+" "+dates+" "+months+" *";

		}
		if($("#freqw").prop("checked") == true){

			let days = "";

			if($("#days").val() != null){
				if(Object.values($("#days").val()).indexOf("1-7") > -1){
					$("#days").val("").val("1-7").select2({width : "100%"})
					days = "1-7";
				}else{
					days = Object.values($("#days").val()).join(",");
				}
			}

			if(days == ""){
				days = "*";
			}

			let hrs = $("#hrs").val();
			let mins = $("#min").val();
			expression = mins+" "+hrs+" * * "+days;
		}
		if($("#freqd").prop("checked") == true){

			let hrs = $("#hrs").val();
			let mins = $("#min").val();
			expression = mins+" "+hrs+" * * *";

		}
		if($("#freqh").prop("checked") == true){
			let hourly_freq = $("#hourly_freq").val();
			expression = "00 */"+hourly_freq+" * * *";
		}

		expression_description = convert_to_msg(expression);
		$("#converted_cron").text(expression_description);
	}
	
	function convert_to_msg(exp){
		return cronstrue.toString(exp, { throwExceptionOnParseError: false });
	}
	
	function add_cron_job(){

		let cron_val = "";
		if(!empty($("#cron_job").val())){
			cron_val = $("#cron_job").val().split(" ")
		}
		
		$("#cron_job_form").trigger("reset");
		$("#converted_cron").text("");

		$(".chosen, #months, #dates, #days").select2({
			"width" : "100%"
		});
		
		$("#rotate_date, #rotate_day, #rotate_time, #rotate_hour, #rotate_month").hide();

		$("#freqm_div").show();

		if(!empty(cron_val) && !empty(selected_cron_type)){
			if(selected_cron_type == "monthly"){
				$("#freqm").trigger("click");
				$("#months").val(cron_val[3].split(",")).select2({"width" : "100%"});
				$("#dates").val(cron_val[2].split(",")).select2({"width" : "100%"});
				$("#hrs").val(cron_val[1]);
				$("#min").val(cron_val[0]);
			}else if(selected_cron_type == "weekly"){
				$("#freqw").trigger("click");
				$("#days").val(cron_val[4].split(",")).select2({"width" : "100%"});
				$("#hrs").val(cron_val[1]);
				$("#min").val(cron_val[0]);
			}else if(selected_cron_type == "daily"){
				$("#freqd").trigger("click");
				$("#hrs").val(cron_val[1]);
				$("#min").val(cron_val[0]);
			}else if(selected_cron_type == "hourly"){
				$("#freqh").trigger("click");
				var tmp = cron_val[1].split("/");
				$("#hourly_freq").val(tmp[1]);
			}
			get_cron_msg();
		}

		$("#cronModal").modal();
		
		$("#create_cron").unbind().click(function(){
			$("#cron_job").val(expression);
			$(".cron_job").html(expression_description);
			$("#cronModal").modal("hide");
		});	
	}

	function force_log_rotate(){
		$.ajax({
			url: "'.$globals['index'].'&act=log_rotation&force_rotation=1&api=json",
			dataType : "json",
			method : "post",
			success:function(data){
				if(!empty(data["error"])){
					showalert(data["error"] ,"1");
					return false;
				}
				show_toast("'.__J('Force Log Rotation task started').'");
			}
		});
	}';

	if(!empty($rotate_data['logrotate_cron_job']) || !empty($_POST['cron_job']) ){
		echo  '
		$(document).ready(function(){
			$(".cron_job").html(convert_to_msg(\''.(!empty($_POST['cron_job']) ? $_POST['cron_job'] : $rotate_data['logrotate_cron_job']).'\'))
		})';
	}

echo '
// ]]></script>

<!--Modal started -->
<div class="modal fade" id="cronModal" tabindex="-1" aria-labelledby="cronjob" aria-hidden="true">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="cronjob">'.__('Add Cron Job').'</h5>
				<button type="button" class="close text-always-white" data-dismiss="modal">×</button>
			</div>
			<div class="modal-body">
				<span class="h5 m-0 font-italic" id="converted_cron"></span>
				<form id="cron_job_form">
					<div class="my-3">
						<div class="form-group r-pill">
							<div class="r-pill__group mb-3">
								<span class="r-pill__item" id="freqm_div">
									<input type="radio" class="custom-control-input" id="freqm" name="freq" value="monthly" '.POSTradio('freq', 'monthly').'>
									<label for="freq" class="m-0">'.__('Monthly').'</label>
								</span>
								<span class="r-pill__item">
									<input type="radio" class="custom-control-input" id="freqw" name="freq" value="weekly" '.POSTradio('freq', 'weekly').'>
									<label for="freq" class="m-0">'.__('Weekly').'</label>
								</span>
								<span class="r-pill__item">
									<input type="radio" class="custom-control-input" id="freqd" name="freq" value="daily" '.POSTradio('freq', 'daily').'>
									<label for="freq" class="m-0">'.__('Daily').'</label>
								</span>
								<span class="r-pill__item">
									<input type="radio" class="custom-control-input" id="freqh" name="freq" value="hourly" '.POSTradio('freq', 'hourly').'>
									<label for="freq" class="m-0">'.__('Hourly').'</label>
								</span>
							</div>
						</div>
					</div>
					<div class="row mx-auto w-100 my-3" id="rotate_hour" style="display:none">
						<div class="col-sm-6">
							<label class="control-label">'.__('Run the Logrotate process every').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('The hourly Logrotate frequency').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6">
							<select class="custom-select w-50" name="hourly_freq" id="hourly_freq" onchange="get_cron_msg()">';
								for($i=0;$i<24;$i++){
									echo '<option value="'.($i < 10 ? '0'.$i : $i).'" '.POSTselect('hourly_freq', $i).' >'.($i < 10 ? '0'.$i : $i).'</option>';
								}
						echo'</select><label class="p-2">'.__('Hours').'</label>
						</div>
					</div>		
					<div class="row mx-auto w-100 my-3" id="rotate_day" style="display:none;">
						<div class="col-sm-6">
							<label class="control-label">'.__('Logrotate Day').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('Logrotate Day').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6">
							<select class="custom-select" multiple="multiple" name="day" id="days" onchange="get_cron_msg()">
								<option value="0" '.POSTselect('day', "0").' >'.__('Sunday').'</option>
								<option value="1" '.POSTselect('day', "1").' >'.__('Monday').'</option>
								<option value="2" '.POSTselect('day', "2").' >'.__('Tuesday').'</option>
								<option value="3" '.POSTselect('day', "3").' >'.__('Wednesday').'</option>
								<option value="4" '.POSTselect('day', "4").' >'.__('Thursday').'</option>
								<option value="5" '.POSTselect('day', "5").' >'.__('Friday').'</option>
								<option value="6" '.POSTselect('day', "6").' >'.__('Saturday').'</option>
								<option value="0-6" >'.__('All Days').'</option>
							</select>
						</div>
					</div>
					<div class="row mx-auto w-100 my-3" id="rotate_month" style="display:none;">
						<div class="col-sm-6">
							<label class="control-label">'.__('Logrotate Month').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('Designated month on which the Logrotate will run').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6">
							<select name="months" multiple="multiple" class="custom-select" id="months" onchange="get_cron_msg()">';
							for($i=1;$i<=12;$i++){
								echo '<option value="'.$i.'" '.POSTselect('months', $i).' >'.$i.'</option>';
							}
							echo '<option value="1-12" >'.__('All Months').'</option>';
						echo '</select>
						</div>
					</div>
					<div class="row mx-auto w-100 my-3" id="rotate_date" style="display:none;">
						<div class="col-sm-6">
							<label class="control-label">'.__('Logrotate Date').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('Designated day of the month on which the Logrotate will run').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6">
							<select name="date" multiple="multiple" class="custom-select" id="dates" onchange="get_cron_msg()">';
							for($i=1;$i<32;$i++){
								echo '<option value="'.$i.'" '.POSTselect('date', $i).' >'.$i.'</option>';
							}
							echo '<option value="1-31" >'.__('All Dates').'</option>';
						echo '</select>
						</div>
					</div>
					<div class="row mx-auto w-100 my-3" id="rotate_time" style="display:none;">
						<div class="col-sm-6">
							<label class="control-label">'.__('Time').'&nbsp;<a class="info" data-placement="right" tooltip="'.__('The time at which the Logrotate will begin').'"><i class="fas text-primary fa-info-circle"></i></a></label>
						</div>
						<div class="col-sm-6">
							<select class="custom-select w-25 p-1 float-left" name="hrs" id="hrs" onchange="get_cron_msg()">';
							for($i=0;$i<24;$i++){
								echo '<option value="'.($i < 10 ? '0'.$i : $i).'" '.POSTselect('hrs', $i).' >'.($i < 10 ? '0'.$i : $i).'</option>';
							}
						echo '</select>
							<label class="side_lbl">'.__('Hours').'</label>
							<select class="custom-select w-25 p-1 float-left" name="min" id="min" onchange="get_cron_msg()">';
								for($i=0;$i<60;$i++){
									echo '<option value="'.($i < 10 ? '0'.$i : $i).'" '.POSTselect('min', $i).' >'.($i < 10 ? '0'.$i : $i).'</option>';
								}
						echo '</select><label class="side_lbl">'.__('Minutes').'</label>
						</div>
					</div>
					<input type="button" value="'.__('Add Cron Job').'" name="create_cron" class="go_btn" id="create_cron" />
				</form>
			</div>
		</div>
	</div>
</div>
<!--Modal end -->
	
<div class="bg">';

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

	<form accept-charset="'.$globals['charset'].'" id="logrotationform" name ="logrotationform" method="post" action="" class="form-horizontal">

		<div class="row mx-auto w-100 my-3 align-items-center">
			<div class="col-6">
				<label class="control-label">'.__('Rotated Logs Directory').'&nbsp;&nbsp;<a class="info" data-placement="right" tooltip="'.__('The path to the directory where rotated log files will be stored. <br/> <b>Default</b> :- Logs are rotated in the same directory the log normally resides').'"><i class="fas text-primary fa-info-circle"></i></a></label>
				<input type="text" class="form-control w-100" name="rotated_logs_directory" size="30" value="'.POSTval('rotated_logs_directory', $rotate_data['olddir']).'" />
			</div>
			<div class="col-6">
				<label class="control-label">'.__('Log Files Size').'&nbsp;&nbsp;<a class="info" data-placement="right" tooltip="'.__('If Set then the Log files will be rotated only if they grow bigger then given the size.').'"><i class="fas text-primary fa-info-circle"></i></a></label>
				<div class="input-group">
					<input type="number" class="form-control" name="file_size" id="file_size" size="30" placeholder="0" value="'.POSTval('file_size', $rotate_data['file_size']).'"/>
					<div class="input-group-append">
						<select name="file_size_unit" id="file_size_unit" class="form-select input-group-text">';
							foreach(["K", "M", "G"] as $unit){
								$selected = ($rotate_data['files_size_unit'] == $unit || $_POST['files_size_unit'] == $unit) ? 'selected="selected"' : '';
								echo'<option value="'.$unit.'" '.$selected.'>'.$unit.'B</option>';
							}
						echo'</select>
					</div>
				</div>
			</div>
			<div class="col-6 mt-2">
				<div class="row mx-auto">
					<div class="col-sm-6 p-0">
						<label class="control-label">'.__('Enable Log Rotation').'&nbsp;&nbsp;<a class="info" data-placement="right" tooltip="'.__('If Enabled then the log files will be rotated based on the given frequency.').'"><i class="fas text-primary fa-info-circle"></i></a></label>
					</div>
					<div class="col-sm-6 d-flex justify-content-end p-0">
						'.get_switch('enable_log_rotation', '', 'enable_log_rotation', array('chk_it' => 1, 'val' => $rotate_data['enabled'])).'
					</div>
				</div>
			</div>
			<div class="col-6 mt-2">
				<div class="row mx-auto">
					<div class="col-sm-6 p-0">
						<label class="control-label">'.__('Enable Compression').'&nbsp;&nbsp;<a class="info" data-placement="right" tooltip="'.__('If Checked the rotated log files will be comprassed using gzip.').'"><i class="fas text-primary fa-info-circle"></i></a></label>
					</div>
					<div class="col-sm-6 d-flex justify-content-end p-0">
						'.get_switch('enable_compression', '', 'enable_compression', array('chk_it' => 1, 'val' => $rotate_data['compression'])).'
					</div>
				</div>
			</div>
			<div class="col-6 mt-2">
				<label class="control-label">'.__('Log Rotation Frequency').'&nbsp;&nbsp;<a class="info" data-placement="right" tooltip="'.__('How often to run the log rotation.').'"><i class="fas text-primary fa-info-circle"></i></a></label>
				<span class="cursor-pointer cron_job" onclick="add_cron_job();">'.__('Click to set cron').'</span>
				<input type="hidden" class="form-control" id="cron_job" value="'.POSTval('cron_job', $rotate_data['logrotate_cron_job']).'" name="cron_job" autocomplete="off"/>
			</div>
		</div>

		<input type="hidden" id="cron_type" value="'.POSTval('cron_type', $rotate_data['logrotate_cron_type']).'" name="cron_type" autocomplete="off"/>

		<center>
			<input type="submit" name="logrotate" value="'.__('Submit').'" class="go_btn m-3">
			<input class="go_btn m-3" type="button" id="force_rotation" name="force_rotation" onclick="force_log_rotate();" title="'.__('Force Rotation').'" value="'.__('Force Rotation').'" class="btn cursor-pointer col-sm-0 p-2">
		</center>

	</form>
</div>';

softfooter();
}