<?php

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

include_once(dirname(__FILE__).'/Measurement.php');

class SystemMeasurement extends Measurement
{
  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
    {
      return FALSE;
    }
    restore_error_handler();
  }

  function Ping($Host = 'nix.cz')
  {
    $Row = array();
    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()
  {
    $CpuStateFileName = '/tmp/LastCpuUsage';
    $LastCpuUsage = unserialize(file_get_contents($CpuStateFileName));
    //$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;
    }
    file_put_contents($CpuStateFileName, serialize($CpuUsage));
    return 100 - round($CpuUsagePercent['Idle'], 2);
  }

  function GetNetworkState()
  {
    $NetworkStateFile = '/tmp/LastNetworkState';
    $LastNetworkState = unserialize(file_get_contents($NetworkStateFile));
    $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;
    }
    file_put_contents($NetworkStateFile, serialize($NetworkState));
    return $NetworkState;
  }

  function NetworkSpeedDownload($Interface)
  {
    $NetworkState = $this->GetNetworkState();
    return $NetworkState['Interface']['DownAverage'];
  }

  function NetworkSpeedUpload($Interface)
  {
    $NetworkState = $this->GetNetworkState();
    return $NetworkState['Interface']['UpAverage'];
  }

  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];
  }
}
