<?php

function plugin_phpsysinfo_variables()
{
    $variables = array(
        'Plugin Name'       => array(
            'type'        => 'hidden',
            'description' => '',
            'value'       => 'Server Info',
        ),
        'Viewable by Support Managers'   => array(
            'type'        => 'yesno',
            'description' => '',
            'value'       => false,
        ),
        'Viewable by Support Staff members'   => array(
            'type'        => 'yesno',
            'description' => '',
            'value'       => false,
        ),
        'Viewable by Billing Staff members'   => array(
            'type'        => 'yesno',
            'description' => '',
            'value'       => false,
        ),
        'Viewable by Customers'   => array(
            'type'        => 'yesno',
            'description' => '',
            'value'       => false,
        ),
    );

    return $variables;
}

function plugin_phpsysinfo_view()
{

    global $gSettingsArray, $tpl;

    if (isset($_GET['pluginaction'])) {
        switch ($_GET['pluginaction']) {
            case 'showserver':
                _plugin_phpsysinfo_showServer();
                break;
        }
    }

    _plugin_phpsysinfo_showServerDropDown();

    $tpl->parse('output', 'serverstats_template');
    return $tpl->fetch('output');
}

function plugin_phpsysinfo_getDashboardData($statsurl) {
    $xml = _plugin_phpsysinfo_getXML($statsurl);
    return array(
        'loadAverages'      => _plugin_phpsysinfo_getLoadAverages($xml),
        'uptime'            => _plugin_phpsysinfo_getUptime($xml),
        'memoryUsedPercent' => _plugin_phpsysinfo_getMemUsedPercent($xml),
        'memoryCached'      => _plugin_phpsysinfo_getCachedPercent($xml),
        'mounts'            => _plugin_phpsysinfo_getMounts($xml),
    );
}

function _plugin_phpsysinfo_showServerDropDown(){
    global $gSettingsArray, $tpl;

    // Get list of servers
    if ($GLOBALS['user']->isAdmin()) {
        $sql = "SELECT s.id, s.name FROM server s WHERE statsurl != '' ORDER BY s.name";
        $result = $GLOBALS['db']->query($sql);
    } else {
        $sql = "SELECT DISTINCT(s.id), s.name FROM server s, domains d "
              ."WHERE d.serverid = s.id AND s.statsurl != '' AND s.statsviewable = 1 AND d.CustomerID = ? ORDER BY s.name";
        $result = $GLOBALS['db']->query($sql, $GLOBALS['user']->getId());
    }

    $tpl->define(array('serverstats_template' => '../../plugins/addons/phpsysinfo/phpsysinfo.tpl'));
    $tpl->define_dynamic('serverstats', 'serverstats_template');

    $tpl->setKey(array(
        'SYSINFO_FUSE'          => $GLOBALS['user']->isAdmin()? cADMIN : cCLIENTS,
        'SYSINFO_ACTION'        => $GLOBALS['user']->isAdmin()? cADMIN_ADDONS : cCLIENTS_SHOWADDONS_CUSTOMER,
        'SYSINFO_POPUPHELP1'    => returnPopupString(lang('To add a server, set the \'Status URL\' field in the server\'s configuration screen').'.'),
    ));

    $tpl->setKey(array(
        'LANUAGE_SELECTSERVER' => Lang('Select Server')
    ));

    while (list($serverid, $servername) = $result->fetch())
    {

        if(isset($_GET['serverid']) && $_GET['serverid'] == $serverid) {
            $selected = "SELECTED";
        }else{
            $selected = "";
        }

        $tpl->setKey(array('SYSINFO_SELECTED' => $selected));
        $tpl->setKey(array(
            'SYSINFO_SERVER' => $serverid,
            'SYSINFO_SERVERNAME'   => $servername,
        ));
        $tpl->subst('trash', '.servers');
    }
}

function _plugin_phpsysinfo_showServer(){
    global $gSettingsArray, $tpl;

    if ($GLOBALS['user']->isAdmin()) {
        $sql = "SELECT s.statsurl, s.name FROM server s WHERE s.id=?";
        $result = $GLOBALS['db']->query($sql,$_GET['serverid']);
    } else {
        $sql = "SELECT s.statsurl, s.name FROM server s, domains d "
              ."WHERE d.serverid=s.id AND s.statsviewable=1 AND s.id=? AND d.CustomerID=?";
        $result = $GLOBALS['db']->query($sql,$_GET['serverid'], $GLOBALS['user']->getId());
    }
    list($statsurl, $servername) = $result->fetch();


    $tpl->define(array('serverstatspage_template' => '../../plugins/addons/phpsysinfo/phpsysinfo_serverinfo.tpl'));
    $tpl->define_dynamic('serverstatspage', 'serverstatspage_template');

    $xml = _plugin_phpsysinfo_getXML($statsurl);

    _plugin_phpsysinfo_SetVitals($xml);
    _plugin_phpsysinfo_SetHardware($xml);
    _plugin_phpsysinfo_NetworkUsage($xml);
    _plugin_phpsysinfo_MemoryUsage($xml);
    _plugin_phpsysinfo_FileSystem($xml);

    $tpl->parse('inneroutput', 'serverstatspage_template');

    $tpl->setKey(array(
        'SYSINFO_SERVERSTATS' => $tpl->fetch('inneroutput')
    ));

}

function _plugin_phpsysinfo_getXML($statsurl) {
    $xmldata = curlRequest($statsurl, false, false, true, true);

    //need to validate XML before we do anything so that we do not
    //get unexpected errors when using this xmlize function
    $xml = xmlize($xmldata,1);

    return $xml;
}

function _plugin_phpsysinfo_MemoryUsage($xml){
    global $tpl;

    //Getting Physical Memory
    //we get these in kilobytes so we convert to byte before passing to this function
    $memfree = _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Free"][0]["#"])*1024,"");
    $memtotal = _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Total"][0]["#"])*1024,"");

    //Get Kernal + Application
    //we get these in kilobytes so we convert to byte before passing to this function
    $kernused = _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["App"][0]["#"])*1024,"");
    $kernpercent = $xml["phpsysinfo"]["#"]["Memory"][0]["#"]["AppPercent"][0]["#"];

    //Get Buffers
    //we get these in kilobytes so we convert to byte before passing to this function
    $buffused = _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Buffers"][0]["#"])*1024,"");
    $buffpercent = $xml["phpsysinfo"]["#"]["Memory"][0]["#"]["BuffersPercent"][0]["#"];

    //Get Cached
    //we get these in kilobytes so we convert to byte before passing to this function
    $cachedused = _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Cached"][0]["#"])*1024,"");

    //Set Vitals
    $tpl->setKey(array(
        'SYSINFO_MEMFREE'       => $memfree,
        'SYSINFO_MEMUSED'       => _plugin_phpsysinfo_getMemUsed($xml),
        'SYSINFO_MEMTOTAL'      => $memtotal,
        'SYSINFO_MEMPERCENT'    => bar(_plugin_phpsysinfo_getMemUsedPercent($xml),100),
        'SYSINFO_KERNUSED'      => $kernused,
        'SYSINFO_KERNPERCENT'   => bar($kernpercent,100),
        'SYSINFO_BUFFUSED'      => $buffused,
        'SYSINFO_BUFFPERCENT'   => bar($buffpercent,100),
        'SYSINFO_CACHUSED'      => $cachedused,
        'SYSINFO_CACHPERCENT'   => bar(_plugin_phpsysinfo_getCachedPercent($xml),100),
    ));
}

function _plugin_phpsysinfo_getMemUsed(&$xml) {
    return _plugin_phpsysinfo_ConvertByte(floatval($xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Used"][0]["#"])*1024,"");
}

function _plugin_phpsysinfo_getMemUsedPercent(&$xml) {
    return $xml["phpsysinfo"]["#"]["Memory"][0]["#"]["Percent"][0]["#"];
}

function _plugin_phpsysinfo_getCachedPercent(&$xml) {
    return $xml["phpsysinfo"]["#"]["Memory"][0]["#"]["CachedPercent"][0]["#"];
}

function _plugin_phpsysinfo_FileSystem($xml){
    global $tpl;

    $mounts = _plugin_phpsysinfo_getMounts($xml);

    for($i = 0; $i < sizeof($mounts); $i++) {

        $mount = $mounts[$i];

        $mounttype  = $mount["#"]["Type"][0]["#"];
        $mountpart = $mount["#"]["Device"][0]["#"]["Name"][0]["#"];

        //we get these in kilobytes so we convert to byte before passing to this function
        $mountfree = _plugin_phpsysinfo_ConvertByte(floatval($mount["#"]["Free"][0]["#"])*1024,"0.00 KB");
        $mountused = _plugin_phpsysinfo_ConvertByte(floatval($mount["#"]["Used"][0]["#"])*1024,"0.00 KB");
        $mountsize = _plugin_phpsysinfo_ConvertByte(floatval($mount["#"]["Size"][0]["#"])*1024,"0.00 KB");

        $tpl->setKey(array(
            'SYSINFO_MOUNTPOINT'        => _plugin_phpsysinfo_getMountPoint($mount),
            'SYSINFO_MOUNTTYPE'         => $mounttype,
            'SYSINFO_MOUNTPARTITION'    => $mountpart,
            'SYSINFO_MOUNTPERCENT'      => bar(_plugin_phpsysinfo_getMountPercent($mount),100),
            'SYSINFO_MOUNTFREE'         => $mountfree,
            'SYSINFO_MOUNTUSED'         => $mountused,
            'SYSINFO_MOUNTSIZE'         => $mountsize
        ));

        $tpl->subst('trash2', '.mounts');
    }
}

function _plugin_phpsysinfo_getMounts(&$xml) {
    return $xml["phpsysinfo"]["#"]["FileSystem"][0]["#"]["Mount"];
}

function _plugin_phpsysinfo_getMountPoint($mount) {
    return $mount["#"]["MountPoint"][0]["#"];
}

function _plugin_phpsysinfo_getMountPercent($mount) {
    return $mount["#"]["Percent"][0]["#"];
}

function _plugin_phpsysinfo_NetworkUsage($xml){
    global $tpl;

    $netdevices = $xml["phpsysinfo"]["#"]["Network"][0]["#"]["NetDevice"];

    for($i = 0; $i < sizeof($netdevices); $i++) {

        $netdevice = $netdevices[$i];

        $name   = $netdevice["#"]["Name"][0]["#"];
        $rxbytes    = _plugin_phpsysinfo_ConvertByte($netdevice["#"]["RxBytes"][0]["#"],"0.00 KB");
        $txbytes    = _plugin_phpsysinfo_ConvertByte($netdevice["#"]["TxBytes"][0]["#"],"0.00 KB");
        $errors     = $netdevice["#"]["Errors"][0]["#"];
        $drops  = $netdevice["#"]["Drops"][0]["#"];

        $tpl->setKey(array(
            'SYSINFO_DEVICENAME' => $name,
            'SYSINFO_DEVICERECEIVED'   => $rxbytes,
            'SYSINFO_DEVICESENT' => $txbytes,
            'SYSINFO_DEVICEERR'   => $errors,
            'SYSINFO_DEVICEDROP'   => $drops,
        ));

        $tpl->subst('trash', '.netdevices');
    }


}

function _plugin_phpsysinfo_SetHardware($xml){
    global $tpl;

    //Getting Server Information
    $processors = $xml["phpsysinfo"]["#"]["Hardware"][0]["#"]["CPU"][0]["#"]["Number"][0]["#"];
    $cpumodel = $xml["phpsysinfo"]["#"]["Hardware"][0]["#"]["CPU"][0]["#"]["Model"][0]["#"];
    $cpuspeed = round(floatval($xml["phpsysinfo"]["#"]["Hardware"][0]["#"]["CPU"][0]["#"]["Cpuspeed"][0]["#"])/1000,2);
    $cpucache = $xml["phpsysinfo"]["#"]["Hardware"][0]["#"]["CPU"][0]["#"]["Cache"][0]["#"];


    if($cpuspeed > 0.00) $cpuspeed = $cpuspeed." GHz";


    //Set Vitals
    $tpl->setKey(array(
        'SYSINFO_PROCESSORS' => $processors,
        'SYSINFO_CPUMODEL' => $cpumodel,
        'SYSINFO_CPUSPEED' => $cpuspeed,
        'SYSINFO_CPUCACHESIZE' => $cpucache,
    ));

}

function _plugin_phpsysinfo_SetVitals($xml){
    global $tpl;

    //Getting Vitals
    $hostname = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["Hostname"][0]["#"];
    $ipaddress = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["IPAddr"][0]["#"];
    $per_cpuload = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["LoadAvg"][0]["#"];
    $distroname = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["Distro"][0]["#"];
    $kernalver = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["Kernel"][0]["#"];
    $currentusers = $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["Users"][0]["#"];

    if ($per_cpuload > 0.00){
        $per_cpuload = bar($per_cpuload,50);
    }else{
        $per_cpuload = "";
    }

    //Set Vitals
    $tpl->setKey(array(
        'SYSINFO_HOSTNAME'      => $hostname,
        'SYSINFO_LISTENINGIP'   => $ipaddress,
        'SYSINFO_UPTIME'        => _plugin_phpsysinfo_getUptime($xml),
        'SYSINFO_LOADAVERAGE'   => _plugin_phpsysinfo_getLoadAverages($xml),
        'SYSINFO_CPULOAD'       => $per_cpuload,
        'SYSINFO_DISTRONAME'    => $distroname,
        'SYSINFO_KERNALVER'     => $kernalver,
        'SYSINFO_CURRENTUSERS'  => $currentusers,
    ));

}

function _plugin_phpsysinfo_getLoadAverages(&$xml) {
    return $xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["LoadAvg"][0]["#"];
}

function _plugin_phpsysinfo_getUptime(&$xml) {
    return _plugin_phpsysinfo_parseUptime($xml["phpsysinfo"]["#"]["Vitals"][0]["#"]["Uptime"][0]["#"]);
}

//Make Human Readable
function _plugin_phpsysinfo_ConvertByte($bytes,$emptyStr){

    /*
    1 KiloByte == 1024 bytes
    1 MegaByte == 1024 KiloByte
    1 GigaByte == 1024 MegaByte
    */

     $amount = $bytes / 1024;
     $symbol = "KB";

     if ($amount > 1024){
        $symbol = "MB";
        $amount = $amount / 1024;
     }

     if ($amount > 1024){
        $symbol = "GB";
        $amount = $amount / 1024;
     }

    $returnStr = ($amount == 0) ? $emptyStr : round($amount,2)." ".$symbol;
    return $returnStr;
}

function _plugin_phpsysinfo_parseUptime($tuptime) {
     $uptimeString = "";
     $secs = floor($tuptime) % 60;
     $mins = floor($tuptime / 60) % 60;
     $hours = floor($tuptime / 3600) % 24;
     $days = floor($tuptime / 86400);

     if ($days > 0) {
       $uptimeString .= $days;
       $uptimeString .= ($days == 1) ? " day " : " days ";
     }

     if ($hours > 0) {
       $uptimeString .= $hours;
       $uptimeString .= ($hours == 1) ? " hour " : " hours ";
     }

     if ($mins > 0) {
       $uptimeString .= $mins;
       $uptimeString .= ($mins == 1) ? " minute " : " minutes ";
     }

     $uptimeString .= $secs;
     $uptimeString .= ($secs == 1) ? " second " : " seconds ";

     return $uptimeString;
}

function bar($value, $width) {
    $prefix = "blue";
    if ($value > 100) $value = 100;
    if ($value < 0) $value = 0;
    $left = 100 - $value;
    if ($left <= 10) $prefix = "red";
    $strHTML = "<!-- progress bar -->";
    $strHTML .= "<table width=\"$width%\">";
    $strHTML .= "<tr><td width=\"100%\">";
    $strHTML .= "<table width=\"100%\" height=\"14\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\" background=plugins/addons/phpsysinfo/images/$prefix-back.gif>";
    $strHTML .= "<tr>";
    $strHTML .= "<td width=\"3\" align=\"left\"><img src=plugins/addons/phpsysinfo/images/$prefix-start.gif></td>";
    if ($value != "0") $strHTML .= "<td width=\"$value%\" background=plugins/addons/phpsysinfo/images/$prefix-active.gif><img src=plugins/addons/phpsysinfo/images/zero.gif width=\"1\" height=\"1\"></td>";
    if ($value != "100" && $value != "0") $strHTML .= "<td width=\"4\"><img src=plugins/addons/phpsysinfo/images/$prefix-divider.gif></td>";
    if ($value != "100") $strHTML .= "<td width=\"$left%\"><img src=plugins/addons/phpsysinfo/images/zero.gif width=\"1\" height=\"1\"></td>";
    if ($value != "100" && $value != "0") $strHTML .= "<td width=\"3\" align=\"right\"><img src=plugins/addons/phpsysinfo/images/$prefix-end.gif></td>";
    if ($value == "0" || $value == "100") $strHTML .= "<td width=\"2\" align=\"right\"><img src=plugins/addons/phpsysinfo/images/$prefix-zeroend.gif></td>";
    $strHTML .= "</tr>";
    $strHTML .= "</table>";
    $strHTML .= "</td><td width=\"1\" class=\"text\">$value%</td></tr>";
    $strHTML .= "</table>";
    $strHTML .= "<!-- //progress bar -->";

    return $strHTML;
}
?>
