<?php

// Funkce pro získání stavových informací o systému

function ErrorHandler($errno,$errmsg,$filename,$linenum,$vars)
{
}

function CheckPortStatus($Ip, $Port, $Timeout = 0.5)
{
  set_error_handler('ErrorHandler');
  //error_reporting(0);
  if($Fp1 = fsockopen($Ip, $Port, $ERROR_NO, $ERROR_STR, (float)$Timeout))
  {
    fclose($Fp1);
    return(TRUE);
  } else
  {
    //echo($ERROR_NO.','.$ERROR_STR);
    return(FALSE);
  }
  restore_error_handler();
}

function Ping($Host = 'nix.cz')
{
  exec('ping '.$Host.' -c 1 -W 1|grep time=', $Row);
  // W - timeout in seconds
  // c - ping count
  $Parts = explode(' ', $Row[0]);
  if(count($Parts) > 6)
  {
    $Time = $Parts[7];
    $TimeParts = explode('=', $Time);
    return($TimeParts[1]);
  } else return(0);
}

function MemoryUsage()
{
  $Output = array();
  exec('free -b', $Output);
  $Row = $Output[2];
  while(strpos($Row, '  ') !== false) $Row = str_replace('  ', ' ', $Row);
  $RowParts = explode(' ', $Row);
  $Row = $Output[3];
  while(strpos($Row, '  ') !== false) $Row = str_replace('  ', ' ', $Row);
  $RowParts2 = explode(' ', $Row);
  return($RowParts[2] + $RowParts2[2]);
}

function CpuUsage()
{
  global $LastCpuUsage;
  //$cpuIDLEprev, $cpuSYSTprev, $cpuUSERprev;

  // get processor usage seconds for pct stats ###
  $File = fopen('/proc/stat', 'r');
  $Row = fgets($File);
  fclose($File);
  $Parts = explode(' ', $Row);
  $CpuUsage['User'] = $Parts[2] + $Parts[3];
  $CpuUsage['System'] = $Parts[4];
  $CpuUsage['Idle'] = $Parts[5];
  $CpuUsageDiff['User'] = ($CpuUsage['User'] - $LastCpuUsage['User']);
  $CpuUsageDiff['System'] = ($CpuUsage['System'] - $LastCpuUsage['System']);
  $CpuUsageDiff['Idle'] = ($CpuUsage['Idle'] - $LastCpuUsage['Idle']);
  $CpuUsageDiffTotal = (($CpuUsageDiff['User'] + $CpuUsageDiff['System']) + $CpuUsageDiff['Idle']);
  if ($CpuUsageDiffTotal > 0)
  {
    $CpuUsagePercent['User'] = ($CpuUsageDiff['User'] / $CpuUsageDiffTotal) * 100;
    $CpuUsagePercent['System'] = ($CpuUsageDiff['System'] / $CpuUsageDiffTotal) * 100;
    $CpuUsagePercent['Idle'] = ($CpuUsageDiff['Idle'] / $CpuUsageDiffTotal * 100);
  } else
  {
    $CpuUsagePercent['User'] = 0;
    $CpuUsagePercent['System'] = 0;
    $CpuUsagePercent['Idle'] = 0;
  }
  $LastCpuUsage = $CpuUsage;
  return(100 - round($CpuUsagePercent['Idle'], 2));
}

function GetNetworkState()
{
  global $LastNetworkState;

  if(!isset($LastNetworkState)) $LastNetworkState = array();
  $NetworkState = array('Time' => time());
  $Output = array();
  exec('cat /proc/net/dev', $Output);
  array_shift($Output); // Skip header
  array_shift($Output); // Skip header
  foreach($Output as $Item)
  {
    while(strpos($Item, '  ') !== false) $Item = str_replace('  ', ' ', $Item);  // Rrmove multiple spaces
    $Item = explode(':', $Item);
    $Interface = trim($Item[0]);
    $Item = explode(' ', trim($Item[1]));
    $NetworkState[$Interface] = array('Down' => $Item[0], 'Up' => $Item[8]);
    if(array_key_exists($Interface, $LastNetworkState))
    {
      $Period = time() - $LastNetworkState['Time'];
      $NetworkState[$Interface]['DownAverage'] = round(($NetworkState[$Interface]['Down'] - $LastNetworkState[$Interface]['Down']) / $Period);
      $NetworkState[$Interface]['UpAverage'] = round(($NetworkState[$Interface]['Up'] - $LastNetworkState[$Interface]['Up']) / $Period);
    } else
    {
      $NetworkState[$Interface]['DownAverage'] = 0;
      $NetworkState[$Interface]['UpAverage'] = 0;
    }
    if($NetworkState[$Interface]['DownAverage'] < 0) $NetworkState[$Interface]['DownAverage'] = 0;
    if($NetworkState[$Interface]['UpAverage'] < 0) $NetworkState[$Interface]['UpAverage'] = 0;
  }
  $LastNetworkState = $NetworkState;
  return($NetworkState);
}

function NetworkServiceConnectionCount($Port)
{
  $HostIP = gethostbyname(trim(`hostname`));
  $Output = array();
  exec('cat /proc/net/nf_conntrack|grep "dst='.$HostIP.' "|grep "dport='.$Port.' "|grep "ASSURED"', $Output);
  return(count($Output));
}

function DiskUtilization($Device)
{
  $Output = array();
  exec('iostat -d '.$Device.' -x -m 2 2', $Output);   // 2 second measure delay
  $Row = $Output[6];
  while(strpos($Row, '  ') !== false) $Row = str_replace('  ', ' ', $Row);
  $Parts = explode(' ', $Row);
  $Value = str_replace(',', '.', $Parts[11]);
  return($Value);
}

function DiskFree($Path)
{
  return(disk_free_space($Path));
}

function ProcessorTemperature($Sensor)
{
  $Output = array();
  exec('/usr/bin/sensors', $Output);
  foreach($Output as $Line)
  {
    if(substr($Line, 0, strlen($Sensor)) == $Sensor)
    {
      $Line = substr($Line, strpos($Line, '+') + 1);
      $Line = substr($Line, 0, strpos($Line, '°'));
      return($Line);
    }
  }
  return(0);
}

function SystemUptime()
{
  $File = fopen('/proc/uptime', 'r');
  $Uptime = fgets($File);
  fclose($File);
  $UptimeParts = explode(' ', $Uptime);
  return($UptimeParts[0]);
}
