#!/usr/bin/php
<?php
//
// Logging Subsystem
// Copyright (c) 2017-2018 Nagios Enterprises, LLC. All rights reserved.
//
define('SUBSYSTEM', 1);
require_once(dirname(__FILE__) . '/../html/includes/base.inc.php');

subsys_get_options($default_time = 60);
open_log_file_handles();
log_subsys();
close_log_file_handles();

function log_subsys() {

	global $max_time;

	$start_time = time();
	$total_logs_processed = 0;

	echo "LOG SUBSYS STARTED\n";
	echo "MAX TIME: $max_time\n";
	echo "START TIME: $start_time\n";

	while ((time() - $start_time) <= $max_time) {

		$total_logs_processed += ($logs_processed = process_logs());

		if ($logs_processed == 0)
			sleep(1);
	}

	echo "END TIME: " . time() . "\n";

	set_sysstat_data('log_subsys', SUBSYS_OK);
}


function process_logs() {

	global $db;

	global $write_log;
	global $write_debug;
	global $debug_in_db;

	$logs = $db->exec_query('SELECT * FROM log WHERE processed = 0 ORDER BY log_time ASC LIMIT 30');

	if ($logs === false)
		subsys_exit('PROCESS_LOGS ERROR UNABLE TO SELECT LOGS');

	$delete_ids = array();
	$process_ids = array();

	foreach ($logs as $log) {

		extract($log);
		$delete = false;

		// if it's a debug/trace message
		if ($level & LOG_LEVEL_DEBUG) {

			if (!$debug_in_db)
				$delete = true;

			if ($write_debug)
				write_to_log_file($log);
		}

		// if it isn't a debug/trace message
		else {

			if ($write_log)
				write_to_log_file($log);
		}

		if ($delete)
			$delete_ids[] = $log_id;
		else
			$process_ids[] = $log_id;
	}

	$deleted = 0;
	$processed = 0;

	if (count($delete_ids) > 0) {
		$sql = 'DELETE FROM log WHERE log_id IN (' . implode(',', $delete_ids) . ')';
		echo "DELETED SQL: {$sql}\n";
		$deleted = $db->exec_query($sql);
	}

	if (count($process_ids) > 0) {
		$sql = 'UPDATE log SET processed = 1 WHERE log_id IN (' . implode(',', $process_ids) . ')';
		echo "PROCESSED SQL: {$sql}\n";
		$processed = $db->exec_query($sql);
	}

	$logs_processed = $deleted + $processed;

	if ($logs_processed != count($logs))
		echo "ERROR: PROCESS_LOGS LOGS_PROCESSED DOESN'T MATCH LOGS SELECT COUNT\n";

	return $logs_processed;
}

function write_to_log_file($log_data) {

	if (!is_array($log_data))
		return false;

	extract($log_data);

	$file_handle = false;

	// which file are we writing to?
	if ($level & LOG_LEVEL_DEBUG) {
		global $debug_handle;
		$file_handle = $debug_handle;
	} else {
		global $log_handle;
		$file_handle = $log_handle;
	}

	$time = "[{$log_time}]";

	$type = strtoupper(log_type_to_human_readable($type));
	$type = "[{$type}]";

	$level = strtoupper(log_level_to_human_readable($level));
	$level = "[{$level}]";

	$user = '';
	if ($user_id != 0)
		$user = ' [' . get_username($user_id) . ']';

	$server = '';
	if ($server_id != 0)
		$server = ' [' . get_server_attr('name', $server_id) . ']';

	$log_string = "{$time} {$type} {$level}{$user}{$server}: {$message}\n";

	@fwrite($file_handle, $log_string);
	@fflush($file_handle);
}
