<?php
	if(isset($_POST['name']) && isset($_POST['host']))
	{
		$port = 80;
		if(!empty($_POST['port'])) $port = $_POST['port'];
		addServer($_POST['name'], $_POST['host'], $port);
		header('Location: index.php');
	}
	else if(isset($_GET['del']))
	{
		$index = (int) $_GET['del'];
		if($index >= 0) deleteServer($index);
	}
?>
<!DOCTYPE html>
<html class="no-js">
    <head>
        <meta name="robots" content="noindex">
        <meta charset="utf-8">
        <title>Server Status Port</title>
        <link href="css/bootstrap.css" rel="stylesheet">
        <link href="css/bootstrap-theme.css" rel="stylesheet">
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
		<link rel="shortcut icon" type="image/x-icon" href="./favicon.png" />
    </head>

    <body class="light-mode" onload="startTime()">

     <style type="text/css">
            body {
                padding-top: 60px;
            }
            .pie_progress {
                width: 150px;
                margin: 10px auto;
            }
            @media all and (max-width: 968px) {
                .pie_progress {
                    width: 80%;
                    max-width: 810px;
                }
            }
            .title {
                height: 50px;
            }
			.Time{
			color: black;
			}
            .Time2{
            color: yellow;
            }

        </style>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="gauge/css/asPieProgress.css">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">

<center>


<div class="container content">

	<div class="page-title light-mode">
	<h2>Monitoring Serv. </h2>
	<!--	<div id="heure" class="Time2"></div> -->
	<img src="favicon.png" alt="Monitoring image" class="logo-image">
	<button id="theme-toggle" >Dark theme</button>
	</div>

	     <div class="col-xs-4 col-sm-4 col-lg-4" id="cpuDiv">
                <div class="pie_progress_cpu" role="progressbar" data-goal="33">
                    <div class="pie_progress__number">0%</div>
                    <div class="pie_progress__label">CPU</div>
                </div>
                <h1>Cpu</h1>
                <div class='title'></div>
            		 <pre><?php echo  `lsb_release -s -d`; ?><br></pre>
            </div>
            <div class="col-xs-4 col-sm-4 col-lg-4" id="memDiv">
                <div class="pie_progress_mem" role="progressbar" data-goal="33">
                    <div class="pie_progress__number">0%</div>
                    <div class="pie_progress__label">Memory</div>
                </div>
                <h1>Memory</h1>

                <div class='title'></div>
                <pre><?php echo `date`;?> <strong><span id="heure" class="Time"></span></strong></pre>

            </div>
            <div class="col-xs-4 col-sm-4 col-lg-4" id="diskDiv">
                <div class="pie_progress_disk" role="progressbar" data-goal="33">
                    <div class="pie_progress__number">0%</div>
                    <div class="pie_progress__label">Disk</div>
                </div>
                <h1>Disk</h1>
                <div class='title'></div> 

				<!-- Check SSL block -->
                <pre>Validity SSL echosystem.fr
                <strong><?php $file='SSL.txt'; $contenu=file_get_contents($file); echo "$contenu"; ?></strong></pre>
				<br>

            </div>
			<br>
    		<h3>Server Status Port</h3>
    		<table class="table table-bordered">
				<tr>
					<th class="text-center">Name</th>
					<th class="text-center">Domain</th>
					<th class="text-center">IP</th>
					<th class="text-center">Port</th>
					<th class="text-center">Status</th>
					<th class="text-center deleteMode" style="width:75px">Delete</th>
				</tr>
                <?php parser(); ?>
			</table>
			<input id="editMode" type="button" value="Edit Entry" checked="checked" class="btn btn-default pull-right_ btnedit" /><br><br>
			<form class="form-inline" role="form" action="index.php" method="post">
				<div class="form-group">Name service<br>
					<input type="text" class="form-control" id="name" name="name" placeholder="Name"> 
				</div>
				<div class="form-group">Host / Domain <br>
					<input type="text" class="form-control" onkeyup="javascript:checkForm(this)" id="host" name="host" placeholder="Domain / IP">
				</div>
				<div class="form-group">Port <br>
					<input type="text" size="5" class="form-control" id="port" name="port" placeholder="Port">
				</div>
				<button type="submit" class="btn btn-default" id="add-button" style="margin-top: 18px;">Add</button>
			</form>
			<br><br>
			<footer>
				<p><center>
				<pre style="width:292px;">By <a href="https://echosystem.fr/erreur32" style="color: unset;">πŸ…΄πŸ†πŸ†πŸ…΄πŸ†„πŸ†32</a> <a href="https://echosystem.fr/" style="color: unset;">
				<img style="display: block; margin-left: auto; margin-right: auto;" src="https://echosystem.fr/home/favicon.png" alt="" width="32" height="32"> πŸ†“πŸ…΄πŸ…²πŸ…·πŸ…ΎοΈπŸ†‚πŸ†ˆπŸ†‚πŸ†ƒπŸ…΄πŸ…Ό </a>
				</pre></center></p>Page Hosted on  <?php $hostname = gethostname(); echo $hostname ?>
    		</footer>
    	</div>

    	<script src="js/jquery.js" type="text/javascript"></script>
        <script src="js/app.js" type="text/javascript"></script>
        <script src="js/bootstrap.min.js" type="text/javascript"></script>
  <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
        <script type="text/javascript" src="gauge/jquery-asPieProgress.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                // Example with grater loading time - loads longer
                $('.pie_progress_cpu, .pie_progress_mem, .pie_progress_disk').asPieProgress({});
                getCpu();
                getMem();
                getDisk();
            });

            function getCpu() {
                $.ajax({
                    url: 'cpu.json.php',
                    success: function (response) {
                        update('cpu', response);
                        setTimeout(function () {
                            getCpu();
                        }, 1000);
                    }
                });
            }

            function getMem() {
                $.ajax({
                    url: 'memory.json.php',
                    success: function (response) {
                        update('mem', response);

                        setTimeout(function () {
                            getMem();
                        }, 1000);
                    }
                });
            }

            function getDisk() {
                $.ajax({
                    url: 'disk.json.php',
                    success: function (response) {
                        update('disk', response);
                        setTimeout(function () {
                            getDisk();
                        }, 1000);
                    }
                });
            }

            function update(name, response) {
                $('.pie_progress_' + name).asPieProgress('go', response.percent);
                $("#" + name + "Div div.title").text(response.title);
//                $("#" + name + "Div pre").text(response.output.join('\n'));
            }
        </script>

    <script>
        function afficherHeure() {
            var date = new Date();
            var heures = date.getHours();
            var minutes = date.getMinutes();
            var secondes = date.getSeconds();

            document.getElementById('heure').innerHTML = heures + ":" + minutes + ":" + secondes;

            // Actualise l'heure chaque seconde
            setTimeout(afficherHeure, 1000);
        }

        // Appelle la fonction pour la première fois
        afficherHeure();
    </script>


 <script src="darktheme.js"></script>
</body>
</html>

<?php

function getStatus($ip, $port)
{
	$socket = @fsockopen($ip, $port, $errorNo, $errorStr, 2);
	if (!$socket) return false;
	else return true;
}

function addServer($name, $host, $port)
{
	// TODO : rewrite the opening part correctly (better errors management)
	$i = 0;
	$filename = 'servers.xml';

	$servers = file_get_contents("servers.xml");
	if (trim($servers) == '')
	{
		exit();
	}
	else
	{
		$servers = simplexml_load_file("servers.xml");
		foreach ($servers as $server) $i++;
	}

	$servers = simplexml_load_file($filename);
	$server = $servers->addChild('server');

	$server->addAttribute('id', (string) $i);
	if(strlen($name) == 0) $name = $host;
	$server->addChild('name', (string)$name);
	$server->addChild('host', (string)$host);
	$server->addChild('port', (string)$port);
	$servers->asXML($filename);
}

function parser()
{
	//TODO : Fix errors when no valid XML content inside file.
	$file = "servers.xml";
	if(file_exists($file))
	{
		$servers = file_get_contents("servers.xml");
		if (trim($servers) == '') //File exists but empty
		{	
			$content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><servers></servers>";
			file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
		}
		else
		{
			$servers = simplexml_load_file("servers.xml");
			foreach ($servers as $server)
			{
				echo "<tr>";
				echo "<td>".$server->name."</td>";
				if(filter_var($server->host, FILTER_VALIDATE_IP))
				{
					echo "<td class=\"text-center\">N/A</td><td class=\"text-center\">".$server->host."</td>";	
				}
				else
				{
					echo "<td class=\"text-center\">".$server->host."</td><td class=\"text-center\">".gethostbyname($server->host)."</td>";
				}

				echo "<td class=\"text-center\">".$server->port."</td>";

				if (getStatus((string)$server->host, (string)$server->port))
				{
					echo "<td class=\"text-center\"><span class=\"label label-success\">Online</span></td>";
				}
				else 
				{
					echo "<td class=\"text-center\"><span class=\"label label-danger\">Offline</span></td>";
				}
				echo "<td class=\"text-center deleteMode\"><a href=\"index.php?del=".$server->attributes()."\" style=\"text-decoration:none\"><b style=\"color:red;\">X</b></a></td>";
				echo "</tr>";
			}
		}
	}
	else
	{
		// TODO : detect creation errors (ex : permissions)
		$content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><servers></servers>";
		file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
	}
}

function deleteServer($index)
{
	$file = "servers.xml";

	$serverFile = new DOMDocument;
	$serverFile->formatOutput = true;
	$serverFile->load($file);
	$servers = $serverFile->documentElement;
	$list = $servers->getElementsByTagName('server');
	$nodeToRemove = null;

	foreach ($list as $server)
	{
		$attrValue = $server->getAttribute('id');
		if ((int)$attrValue == $index) $nodeToRemove = $server;
	}

	if ($nodeToRemove != null) $servers->removeChild($nodeToRemove);

	$serverFile->save($file);
	header('Location: index.php');
}