<commit_before><?
/*
	pfSense_MODULE:	ajax
*/

if(Connection_Aborted()) {
	exit;
}

require_once("config.inc");

function get_stats() {
	$stats['cpu'] = cpu_usage();
	$stats['mem'] = mem_usage();
	$stats['uptime'] = get_uptime();
	$stats['states'] = get_pfstate();
	$stats['temp'] = get_temp();
	$stats['datetime'] = update_date_time();
	$stats['interfacestatistics'] = get_interfacestats();
	$stats['interfacestatus'] = get_interfacestatus();
	$stats['gateways'] = get_gatewaystats();
	$stats['cpufreq'] = get_cpufreq();
	$stats['load_average'] = get_load_average();
	$stats = join("|", $stats);
	return $stats;
}

function get_gatewaystats() {
	$a_gateways = return_gateways_array();
	$gateways_status = array();
	$gateways_status = return_gateways_status(true);
	$data = "";
	$isfirst = true;
	foreach($a_gateways as $gname => $gw) {
		if(!$isfirst)
			$data .= ",";
		$isfirst = false;
		$data .= $gw['name'] . ",";
		if ($gateways_status[$gname]) {
			$data .= lookup_gateway_ip_by_name($gname) . ",";
			$gws = $gateways_status[$gname];
			switch(strtolower($gws['status'])) {
			case "none":
				$online = "Online";
				$bgcolor = "#90EE90";  // lightgreen
				break;
			case "down":
				$online = "Offline";
				$bgcolor = "#F08080";  // lightcoral
				break;
			case "delay":
				$online = "Latency";
				$bgcolor = "#F0E68C";  // khaki
				break;
			case "loss":
				$online = "Packetloss";
				$bgcolor = "#F0E68C";  // khaki
				break;
			default:
				$online = "Pending";
				break;
			}
		} else {
			$data .= "~,";
			$gws['delay'] = "~";
			$gws['loss'] = "~";
			$online = "Unknown";
			$bgcolor = "#ADD8E6";  // lightblue
		}
		$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
		$data .= "<table><tr><td bgcolor=\"$bgcolor\">&nbsp;$online&nbsp;</td></td></tr></table>";
	}
	return $data;
}

function get_uptime() {
	$boottime = "";
	$matches = "";
	exec("/sbin/sysctl -n kern.boottime", $boottime);
	preg_match("/sec = (\d+)/", $boottime[0], $matches);
	$boottime = $matches[1];
	$uptime = time() - $boottime;

	if(intval($boottime) == 0)
		return;
	if(intval($uptime) == 0)
		return;

	$updays = (int)($uptime / 86400);
	$uptime %= 86400;
	$uphours = (int)($uptime / 3600);
	$uptime %= 3600;
	$upmins = (int)($uptime / 60);
	$uptime %= 60;
	$upsecs = (int)($uptime);

	$uptimestr = "";
	if ($updays > 1)
		$uptimestr .= "$updays Days ";
	else if ($updays > 0)
		$uptimestr .= "1 Day ";

	if ($uphours > 1)
		$hours = "s";

	if ($upmins > 1)
		$minutes = "s";

	if ($upmins > 1)
		$seconds = "s";

	$uptimestr .= sprintf("%02d Hour$hours %02d Minute$minutes %02d Second$seconds", $uphours, $upmins, $upsecs);
	return $uptimestr;
}

/* Calculates non-idle CPU time and returns as a percentage */
function cpu_usage() {
	$duration = 1;
	$diff = array('user', 'nice', 'sys', 'intr', 'idle');
	$cpuTicks = array_combine($diff, explode(" ", `/sbin/sysctl -n kern.cp_time`));
	sleep($duration);
	$cpuTicks2 = array_combine($diff, explode(" ", `/sbin/sysctl -n kern.cp_time`));

	$totalStart = array_sum($cpuTicks);
	$totalEnd = array_sum($cpuTicks2);

	// Something wrapped ?!?!
	if ($totalEnd <= $totalStart)
		return 0;

	// Calculate total cycles used
	$totalUsed = ($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks['idle']);

	// Calculate the percentage used
	$cpuUsage = floor(100 * ($totalUsed / ($totalEnd - $totalStart)));

	return $cpuUsage;
}

function get_pfstate() {
	global $config;
	$matches = "";
	if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0)
		$maxstates="{$config['system']['maximumstates']}";
	else
		$maxstates=pfsense_default_state_size();
	$curentries = `/sbin/pfctl -si |grep current`;
	if (preg_match("/([0-9]+)/", $curentries, $matches)) {
		$curentries = $matches[1];
	}
	return $curentries . "/" . $maxstates;
}

function has_temp() {
	/* no known temp monitors available at present */

	/* should only reach here if there is no hardware monitor */
	return false;
}

function get_hwtype() {
	return;
}

function get_temp() {
	$temp_out = "";
	exec("/sbin/sysctl dev.cpu.0.temperature | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d 'C' -f 1", $dfout);
	$temp_out = trim($dfout[0]);
	if ($temp_out == "") {
		exec("/sbin/sysctl hw.acpi.thermal.tz0.temperature | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d 'C' -f 1", $dfout);
		$temp_out = trim($dfout[0]);
	}

	return $temp_out;
}

function disk_usage() {
	$dfout = "";
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d '%' -f 1", $dfout);
	$diskusage = trim($dfout[0]);

	return $diskusage;
}

function swap_usage() {
	$swap_info = exec_command("/usr/sbin/swapinfo");
	$swap_used = "";
	foreach (explode("\n", $swap_info) as $line)
		if (preg_match('/(\d+)%$/', $line, $matches)) {
			$swap_used = $matches[1];
			break;
		}

	return $swap_used;
}

function mem_usage() {
	$memory = "";
	exec("/sbin/sysctl -n vm.stats.vm.v_page_count vm.stats.vm.v_inactive_count " .
		"vm.stats.vm.v_cache_count vm.stats.vm.v_free_count", $memory);

	$totalMem = $memory[0];
	$availMem = $memory[1] + $memory[2] + $memory[3];
	$usedMem = $totalMem - $availMem;
	$memUsage = round(($usedMem * 100) / $totalMem, 0);

	return $memUsage;
}

function update_date_time() {
	$datetime = date("D M j G:i:s T Y");
	return $datetime;
}
<commit_msg>Use exec directly instead of exec_command<commit_after><?
/*
	pfSense_MODULE:	ajax
*/

if(Connection_Aborted()) {
	exit;
}

require_once("config.inc");

function get_stats() {
	$stats['cpu'] = cpu_usage();
	$stats['mem'] = mem_usage();
	$stats['uptime'] = get_uptime();
	$stats['states'] = get_pfstate();
	$stats['temp'] = get_temp();
	$stats['datetime'] = update_date_time();
	$stats['interfacestatistics'] = get_interfacestats();
	$stats['interfacestatus'] = get_interfacestatus();
	$stats['gateways'] = get_gatewaystats();
	$stats['cpufreq'] = get_cpufreq();
	$stats['load_average'] = get_load_average();
	$stats = join("|", $stats);
	return $stats;
}

function get_gatewaystats() {
	$a_gateways = return_gateways_array();
	$gateways_status = array();
	$gateways_status = return_gateways_status(true);
	$data = "";
	$isfirst = true;
	foreach($a_gateways as $gname => $gw) {
		if(!$isfirst)
			$data .= ",";
		$isfirst = false;
		$data .= $gw['name'] . ",";
		if ($gateways_status[$gname]) {
			$data .= lookup_gateway_ip_by_name($gname) . ",";
			$gws = $gateways_status[$gname];
			switch(strtolower($gws['status'])) {
			case "none":
				$online = "Online";
				$bgcolor = "#90EE90";  // lightgreen
				break;
			case "down":
				$online = "Offline";
				$bgcolor = "#F08080";  // lightcoral
				break;
			case "delay":
				$online = "Latency";
				$bgcolor = "#F0E68C";  // khaki
				break;
			case "loss":
				$online = "Packetloss";
				$bgcolor = "#F0E68C";  // khaki
				break;
			default:
				$online = "Pending";
				break;
			}
		} else {
			$data .= "~,";
			$gws['delay'] = "~";
			$gws['loss'] = "~";
			$online = "Unknown";
			$bgcolor = "#ADD8E6";  // lightblue
		}
		$data .= ($online == "Pending") ? "{$online},{$online}," : "{$gws['delay']},{$gws['loss']},";
		$data .= "<table><tr><td bgcolor=\"$bgcolor\">&nbsp;$online&nbsp;</td></td></tr></table>";
	}
	return $data;
}

function get_uptime() {
	$boottime = "";
	$matches = "";
	exec("/sbin/sysctl -n kern.boottime", $boottime);
	preg_match("/sec = (\d+)/", $boottime[0], $matches);
	$boottime = $matches[1];
	$uptime = time() - $boottime;

	if(intval($boottime) == 0)
		return;
	if(intval($uptime) == 0)
		return;

	$updays = (int)($uptime / 86400);
	$uptime %= 86400;
	$uphours = (int)($uptime / 3600);
	$uptime %= 3600;
	$upmins = (int)($uptime / 60);
	$uptime %= 60;
	$upsecs = (int)($uptime);

	$uptimestr = "";
	if ($updays > 1)
		$uptimestr .= "$updays Days ";
	else if ($updays > 0)
		$uptimestr .= "1 Day ";

	if ($uphours > 1)
		$hours = "s";

	if ($upmins > 1)
		$minutes = "s";

	if ($upmins > 1)
		$seconds = "s";

	$uptimestr .= sprintf("%02d Hour$hours %02d Minute$minutes %02d Second$seconds", $uphours, $upmins, $upsecs);
	return $uptimestr;
}

/* Calculates non-idle CPU time and returns as a percentage */
function cpu_usage() {
	$duration = 1;
	$diff = array('user', 'nice', 'sys', 'intr', 'idle');
	$cpuTicks = array_combine($diff, explode(" ", `/sbin/sysctl -n kern.cp_time`));
	sleep($duration);
	$cpuTicks2 = array_combine($diff, explode(" ", `/sbin/sysctl -n kern.cp_time`));

	$totalStart = array_sum($cpuTicks);
	$totalEnd = array_sum($cpuTicks2);

	// Something wrapped ?!?!
	if ($totalEnd <= $totalStart)
		return 0;

	// Calculate total cycles used
	$totalUsed = ($totalEnd - $totalStart) - ($cpuTicks2['idle'] - $cpuTicks['idle']);

	// Calculate the percentage used
	$cpuUsage = floor(100 * ($totalUsed / ($totalEnd - $totalStart)));

	return $cpuUsage;
}

function get_pfstate() {
	global $config;
	$matches = "";
	if (isset($config['system']['maximumstates']) and $config['system']['maximumstates'] > 0)
		$maxstates="{$config['system']['maximumstates']}";
	else
		$maxstates=pfsense_default_state_size();
	$curentries = `/sbin/pfctl -si |grep current`;
	if (preg_match("/([0-9]+)/", $curentries, $matches)) {
		$curentries = $matches[1];
	}
	return $curentries . "/" . $maxstates;
}

function has_temp() {
	/* no known temp monitors available at present */

	/* should only reach here if there is no hardware monitor */
	return false;
}

function get_hwtype() {
	return;
}

function get_temp() {
	$temp_out = "";
	exec("/sbin/sysctl dev.cpu.0.temperature | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d 'C' -f 1", $dfout);
	$temp_out = trim($dfout[0]);
	if ($temp_out == "") {
		exec("/sbin/sysctl hw.acpi.thermal.tz0.temperature | /usr/bin/awk '{ print $2 }' | /usr/bin/cut -d 'C' -f 1", $dfout);
		$temp_out = trim($dfout[0]);
	}

	return $temp_out;
}

function disk_usage() {
	$dfout = "";
	exec("/bin/df -h | /usr/bin/grep -w '/' | /usr/bin/awk '{ print $5 }' | /usr/bin/cut -d '%' -f 1", $dfout);
	$diskusage = trim($dfout[0]);

	return $diskusage;
}

function swap_usage() {
	exec("/usr/sbin/swapinfo", $swap_info);
	$swap_used = "";
	foreach ($swap_info as $line)
		if (preg_match('/(\d+)%$/', $line, $matches)) {
			$swap_used = $matches[1];
			break;
		}

	return $swap_used;
}

function mem_usage() {
	$memory = "";
	exec("/sbin/sysctl -n vm.stats.vm.v_page_count vm.stats.vm.v_inactive_count " .
		"vm.stats.vm.v_cache_count vm.stats.vm.v_free_count", $memory);

	$totalMem = $memory[0];
	$availMem = $memory[1] + $memory[2] + $memory[3];
	$usedMem = $totalMem - $availMem;
	$memUsage = round(($usedMem * 100) / $totalMem, 0);

	return $memUsage;
}

function update_date_time() {
	$datetime = date("D M j G:i:s T Y");
	return $datetime;
}

{'fraction_non_alphanumeric': 0.21975354742345032, 'fraction_numerical': 0.016243465272591486, 'mean_word_length': 4.036671368124119, 'pattern_counts': {'":': 8, '<': 21, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4428065', 'n_tokens_mistral': 4635, 'n_tokens_neox': 4274, 'n_words': 846}