private function parseSysLog() { /* * For parsing the syslog looking for sensord entries * POTENTIALLY BUGGY -- only tested on debian/ubuntu flavored syslogs * Also slow as balls as it parses the entire syslog instead of * using something like tail */ $file = '/var/log/syslog'; if (!is_file($file) || !is_readable($file)) { return array(); } $devices = array(); foreach (LinfoCommon::getLines($file) as $line) { if (preg_match('/\\w+\\s*\\d+ \\d{2}:\\d{2}:\\d{2} \\w+ sensord:\\s*(.+):\\s*(.+)/i', trim($line), $match) == 1) { // Replace current record of dev with updated temp $devices[$match[1]] = $match[2]; } } $return = array(); foreach ($devices as $dev => $stat) { $return[] = array('path' => 'N/A', 'name' => $dev, 'temp' => $stat, 'unit' => ''); } return $return; }
private function _call() { $this->_res = array(); foreach ($this->_servers as $name => $path) { $lines = LinfoCommon::getLines($path); if (count($lines) == 0) { continue; } $info = self::readgamestat($lines); $this->_res[] = array('name' => $name, 'info' => $info); } }
private function _call() { // Time this $t = new LinfoTimerStart('CUPS extension'); // Deal with calling it try { $result = $this->_CallExt->exec('lpstat', '-p -o -l'); } catch (CallExtException $e) { // messed up somehow $this->_LinfoError->add('CUPS Extension', $e->getMessage()); $this->_res = false; // Don't bother going any further return false; } // Split it into lines $lines = explode("\n", $result); // Hold temporarily values here $printers = array(); $queue = array(); $begin_queue_list = false; // Go through it line by line for ($i = 0, $num = count($lines); $i < $num; $i++) { // So regexes don't break on endlines $lines[$i] = trim($lines[$i]); // If there are no entries, don't waste time and end here if ($lines[$i] == 'no entries') { break; } elseif (preg_match('/^printer (.+) is idle\\. (.+)$/', $lines[$i], $printers_match) == 1) { $printers[] = array('name' => str_replace('_', ' ', $printers_match[1]), 'status' => $printers_match[2]); } elseif (preg_match('/^(.+)+ is (ready|ready and printing|not ready)$/', $lines[$i], $printers_match) == 1) { $printers[] = array('name' => str_replace('_', ' ', $printers_match[1]), 'status' => $printers_match[2]); } elseif (preg_match('/^Rank\\s+Owner\\s+Job\\s+File\\(s\\)\\s+Total Size$/', $lines[$i])) { $begin_queue_list = true; } elseif ($begin_queue_list && preg_match('/^([a-z0-9]+)\\s+(\\S+)\\s+(\\d+)\\s+(.+)\\s+(\\d+) bytes$/', $lines[$i], $queue_match)) { $queue[] = array('rank' => $queue_match[1], 'owner' => $queue_match[2], 'job' => $queue_match[3], 'files' => $queue_match[4], 'size' => LinfoCommon::byteConvert($queue_match[5])); } } // Save result lset $this->_res = array('printers' => $printers, 'queue' => $queue); // Apparent success return true; }
public function draw() { // Gain access to translations $lang = $this->linfo->getLang(); // And info $this->linfo->scan(); $info = $this->linfo->getInfo(); // Say we're called more than once. Kill previous remnants if (count($this->_windows) > 0) { $this->_kill_windows(); } // Get dimensions and give lovely header text $fullscreen = ncurses_newwin(0, 0, 0, 0); ncurses_wrefresh($fullscreen); ncurses_getmaxyx($fullscreen, $x, $y); ncurses_mvwaddstr($fullscreen, 0, 0, 'Generated by ' . $this->linfo->getAppName() . ' (' . $this->linfo->getVersion() . ') on ' . date('m/d/Y @ h:i:s A (T)')); ncurses_wrefresh($fullscreen); $this->_max_dims = array($x, $y); // Some important windows $core_wins = array(array('name' => $lang['core'], 'content' => array(array($lang['os'], $info['OS']), array_key_exists('Distro', $info) ? array($lang['distro'], $info['Distro']['name'] . ($info['Distro']['version'] ? ' ' . $info['Distro']['version'] : '')) : false, array($lang['kernel'], $info['Kernel']), array_key_exists('Model', $info) && !empty($info['Model']) ? array($lang['model'], $info['Model']) : false, array($lang['uptime'], str_ireplace(array(' ', 'days', 'minutes', 'hours', 'seconds'), array('', 'd', 'm', 'h', 's'), reset(explode(';', $info['UpTime'])))), array($lang['hostname'], $info['HostName']), array_key_exists('CPUArchitecture', $info) ? array($lang['cpu_arch'], $info['CPUArchitecture']) : false, array($lang['load'], implode(' ', (array) $info['Load'])))), array('name' => $lang['memory'], 'content' => array(array($lang['size'], LinfoCommon::byteConvert($info['RAM']['total'])), array($lang['used'], LinfoCommon::byteConvert($info['RAM']['total'] - $info['RAM']['free'])), array($lang['free'], LinfoCommon::byteConvert($info['RAM']['free']))))); // Show them $h = 1; foreach ($core_wins as $win) { list($width, $height) = $this->_window_with_lines($win['name'], $win['content'], $h, 0); $h += $height + 1; } // Makeshift event loop while (true) { // Die on input $getch = ncurses_getch(); if ($getch > 0 && $getch == 113) { $this->__destruct(); echo "\nEnding at your request.\n"; exit(0); } // Stop temporariy ncurses_napms(1000); // Call ourselves $this->draw(); } }
public function ensureFQDN($hostname) { $parts = explode('.', $hostname); $num_parts = count($parts); // Already FQDN, like a boss.. if ($num_parts >= 2) { return $hostname; } // Don't bother trying to expand on .local if ($num_parts > 0 && $parts[$num_parts - 1] == '.local') { return $hostname; } // This relies on reading /etc/hosts. if (!($contents = LinfoCommon::getContents('/etc/hosts', false))) { return $hostname; } preg_match_all('/^[^\\s#]+\\s+(.+)/m', $contents, $matches, PREG_SET_ORDER); // Lets see if we can do some magic with /etc/hosts.. foreach ($matches as $match) { if (!preg_match_all('/(\\S+)/', $match[1], $hosts, PREG_SET_ORDER)) { continue; } foreach ($hosts as $host) { // I don't want to expand on localhost as it's pointlesss if (strpos('localhost', $host[1]) !== false) { continue; } $entry_parts = explode('.', $host[1]); if (count($entry_parts) > 1 && $entry_parts[0] == $hostname) { return $host[1]; } } } // Couldn't make it better :/ return $hostname; }
public function getUpTime() { $booted = $this->kstat['unix:0:system_misc:boot_time']; return array('text' => LinfoCommon::secondsConvert(time() - $booted), 'bootedTimestamp' => $booted); }
/** * Return result * * @access public * @return false on failure|array of the torrents */ public function result() { // Don't bother if it didn't go well if ($this->_res === false) { return false; } // it did; continue // Store rows here $rows = array(); // Start showing connections $rows[] = array('type' => 'header', 'columns' => array('Torrent', array(1, 'Done', '10%'), 'State', 'Have', 'Uploaded', 'Time Left', 'Ratio', 'Up', 'Down')); // No torrents? if (count($this->_torrents) == 0) { $rows[] = array('type' => 'none', 'columns' => array(array(9, 'None found'))); } else { // Store a total amount of certain torrents here: $status_tally = array(); // As well as uploaded/downloaded $status_tally['Downloaded'] = 0; $status_tally['Uploaded'] = 0; $status_tally['Ratio'] = ''; // Go through each torrent foreach ($this->_torrents as $torrent) { // Status count tally $status_tally[$torrent['state']] = !array_key_exists($torrent['state'], $status_tally) ? 1 : $status_tally[$torrent['state']] + 1; // Make some sense of the have so we can get it into bytes, which we can then have fun with $have_bytes = false; if ($torrent['have'] != 'None') { $have_parts = explode(' ', $torrent['have'], 2); if (is_numeric($have_parts[0]) && $have_parts[0] > 0) { switch ($have_parts[1]) { case 'TiB': $have_bytes = (double) $have_parts[0] * 1099511627776; break; case 'GiB': $have_bytes = (double) $have_parts[0] * 1073741824; break; case 'MiB': $have_bytes = (double) $have_parts[0] * 1048576; break; case 'KiB': $have_bytes = (double) $have_parts[0] * 1024; break; } } } // Try getting amount uploaded, based upon ratio and exact amount downloaded above $uploaded_bytes = false; if (is_numeric($have_bytes) && $have_bytes > 0 && is_numeric($torrent['ratio']) && $torrent['ratio'] > 0) { $uploaded_bytes = $torrent['ratio'] * $have_bytes; } // Save amount uploaded/downloaded tally if (is_numeric($have_bytes) && $have_bytes > 0 && is_numeric($uploaded_bytes) && $uploaded_bytes > 0) { $status_tally['Downloaded'] += $have_bytes; $status_tally['Uploaded'] += $uploaded_bytes; } // Save result $rows[] = array('type' => 'values', 'columns' => array(wordwrap(htmlspecialchars($torrent['torrent']), 50, ' ', true), '<div class="bar_chart"> <div class="bar_inner" style="width: ' . (int) $torrent['done'] . '%;"> <div class="bar_text"> ' . ($torrent['done'] ? $torrent['done'] . '%' : '0%') . ' </div> </div> </div> ', $torrent['state'], $have_bytes !== false ? LinfoCommon::byteConvert($have_bytes) : $torrent['have'], $uploaded_bytes !== false ? LinfoCommon::byteConvert($uploaded_bytes) : 'None', $torrent['eta'], $torrent['ratio'], LinfoCommon::byteConvert($torrent['up']) . '/s', LinfoCommon::byteConvert($torrent['down']) . '/s')); } // Finish the size totals $status_tally['Ratio'] = $status_tally['Downloaded'] > 0 && $status_tally['Uploaded'] > 0 ? round($status_tally['Uploaded'] / $status_tally['Downloaded'], 2) : 'N/A'; $status_tally['Downloaded'] = $status_tally['Downloaded'] > 0 ? LinfoCommon::byteConvert($status_tally['Downloaded']) : 'None'; $status_tally['Uploaded'] = $status_tally['Uploaded'] > 0 ? LinfoCommon::byteConvert($status_tally['Uploaded']) : 'None'; // Create a row for the tally of statuses if (count($status_tally) > 0) { // Store list of k: v'ish values here $tally_contents = array(); // Populate that foreach ($status_tally as $state => $tally) { $tally_contents[] = "{$state}: {$tally}"; } // Save this final row $rows[] = array('type' => 'values', 'columns' => array(array(9, implode(', ', $tally_contents)))); } } // Handle stats which might not exist if (is_array($this->_stats) && array_key_exists('downloaded-bytes', $this->_stats) && array_key_exists('uploaded-bytes', $this->_stats) && array_key_exists('seconds-active', $this->_stats)) { $extra_vals = array('title' => 'Transmission Stats', 'values' => array(array('Total Downloaded', LinfoCommon::byteConvert($this->_stats['downloaded-bytes'])), array('Total Uploaded', LinfoCommon::byteConvert($this->_stats['uploaded-bytes'])), $this->_stats['uploaded-bytes'] > 0 && $this->_stats['downloaded-bytes'] > 0 ? array('Total Ratio', round($this->_stats['uploaded-bytes'] / $this->_stats['downloaded-bytes'], 3)) : false, array('Duration', LinfoCommon::secondsConvert($this->_stats['seconds-active'])))); } else { $extra_vals = false; } // Give it off return array('root_title' => 'Transmission Torrents', 'rows' => $rows, 'extra_type' => 'k->v', 'extra_vals' => $extra_vals); }
public static function tearDownAfterClass() { self::$output = null; LinfoCommon::unconfig(); }
public static function unconfig() { self::$settings = array(); self::$lang = array(); }
public function result() { if (!$this->res) { return false; } $rows[] = array('type' => 'header', 'columns' => array('Torrent/hash' . ($this->hideName ? ' (names hidden)' : ''), 'Size', 'Progress', 'Status', 'Seeds', 'Peers', 'Downloaded', 'Uploaded', 'Ratio', 'Speeds')); foreach ($this->torrents as $name => $info) { $rows[] = array('type' => 'values', 'columns' => array(($this->hideName ? '' : $info['TORRENT_NAME'] . '<br />') . '<span style="font-size: 80%; font-family: monaco, monospace, courier;">' . $info['TORRENT_HASH'] . '</span>', LinfoCommon::byteConvert($info['TORRENT_SIZE']), LinfoOutput::generateBarChart($info['TORRENT_PROGRESS'] / 10), $info['TORRENT_STATUS_MESSAGE'], $info['TORRENT_SEEDS_CONNECTED'] . '/' . $info['TORRENT_SEEDS_SWARM'], $info['TORRENT_SEEDS_CONNECTED'] . '/' . $info['TORRENT_PEERS_SWARM'], LinfoCommon::byteConvert($info['TORRENT_DOWNLOADED']), LinfoCommon::byteConvert($info['TORRENT_UPLOADED']), $info['TORRENT_RATIO'] > 0 ? round($info['TORRENT_RATIO'] / 1000, 2) ?: '0.0' : '0.0', LinfoCommon::byteConvert($info['TORRENT_DOWNSPEED']) . '/s ↓ ' . LinfoCommon::byteConvert($info['TORRENT_UPSPEED']) . '/s ↑ ')); } // Give it off return array('root_title' => 'µTorrent <span style="font-size: 80%;">(' . LinfoCommon::byteConvert($this->stats['downloaded']) . ' ↓ ' . LinfoCommon::byteConvert($this->stats['uploaded']) . ' ↑ ' . round($this->stats['uploaded'] / $this->stats['downloaded'], 2) . ' ratio)</span>', 'rows' => $rows); }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Extract boot part of it if (preg_match('/^\\{ sec \\= (\\d+).+$/', $this->sysctl['kern.boottime'], $m) == 0) { return ''; } // Get it textual, as in days/minutes/hours/etc return LinfoCommon::secondsConvert(time() - $m[1]) . '; booted ' . date($this->settings['dates'], $m[1]); }
private function _call() { // Time this $t = new LinfoTimerStart('apcaccess Extension'); // Deal with calling it try { $result = $this->_CallExt->exec('apcaccess'); } catch (CallExtException $e) { // messed up somehow $this->_LinfoError->add('apcaccess Extension', $e->getMessage()); $this->_res = false; // Don't bother going any further return false; } // Store them here $this->_res = array(); // Get name if (preg_match('/^UPSNAME\\s+:\\s+(.+)$/m', $result, $m)) { $this->_res['name'] = $m[1]; } // Get model if (preg_match('/^MODEL\\s+:\\s+(.+)$/m', $result, $m)) { $this->_res['model'] = $m[1]; } // Get battery voltage if (preg_match('/^BATTV\\s+:\\s+(\\d+\\.\\d+)/m', $result, $m)) { $this->_res['volts'] = $m[1]; } // Get charge percentage, and get it cool if (preg_match('/^BCHARGE\\s+:\\s+(\\d+(?:\\.\\d+)?)/m', $result, $m)) { $charge = (int) $m[1]; $this->_res['charge'] = ' <div class="bar_chart"> <div class="bar_inner" style="width: ' . (int) $charge . '%;"> <div class="bar_text"> ' . ($charge ? $charge . '%' : '?') . ' </div> </div> </div> '; } // Get time remaning if (preg_match('/^TIMELEFT\\s+:\\s+([\\d\\.]+)/m', $result, $m)) { $this->_res['time_left'] = LinfoCommon::secondsConvert($m[1] * 60); } // Get status if (preg_match('/^STATUS\\s+:\\s+([A-Z]+)/m', $result, $m)) { $this->_res['status'] = $m[1] == 'ONBATT' ? 'On Battery' : ucfirst(strtolower($m[1])); } // Load percentage looking cool if (preg_match('/^LOADPCT\\s+:\\s+(\\d+\\.\\d+)/m', $result, $m)) { $load = (int) $m[1]; $this->_res['load'] = ' <div class="bar_chart"> <div class="bar_inner" style="width: ' . (int) $load . '%;"> <div class="bar_text"> ' . ($load ? $load . '%' : '?') . ' </div> </div> </div> '; } // Attempt getting wattage if (isset($load) && preg_match('/^NOMPOWER\\s+:\\s+(\\d+)/m', $result, $m)) { $watts = (int) $m['1']; $this->_res['watts_used'] = $load * round($watts / 100); } else { $this->_res['watts_used'] = false; } // Apparent success return true; }
public function getUpTime() { $booted = $this->kstat['unix:0:system_misc:boot_time']; return LinfoCommon::secondsConvert(time() - $booted) . '; booted ' . date($this->settings['dates'], $booted); }
protected function loadLanguage() { // Running unit tests? if (defined('LINFO_TESTING')) { $this->lang = LinfoCommon::getVarFromFile(LINFO_TESTDIR . '/test_lang.php', 'lang'); if (!is_array($this->lang)) { throw new LinfoFatalException('Failed getting test-specific language'); } return; } // Load translation, defaulting to english of keys are missing (assuming // we're not using english anyway and the english translation indeed exists) if (is_file(LINFO_LOCAL_PATH . 'lang/en.php') && $this->settings['language'] != 'en') { $this->lang = array_merge(LinfoCommon::getVarFromFile(LINFO_LOCAL_PATH . 'lang/en.php', 'lang'), LinfoCommon::getVarFromFile(LINFO_LOCAL_PATH . 'lang/' . $this->settings['language'] . '.php', 'lang')); } else { $this->lang = LinfoCommon::getVarFromFile(LINFO_LOCAL_PATH . 'lang/' . $this->settings['language'] . '.php', 'lang'); } }
/** * @test */ public function getLines() { $lines = array("lineone\n", "linetwo\n", "line3\n"); $file = LINFO_TESTDIR . '/files/lines.txt'; $this->assertEquals($lines, LinfoCommon::getLines($file)); }
/** * Deal with it * * @access private */ private function _call() { // Time this $t = new LinfoTimerStart('dhcpd3 leases extension'); // We couldn't find leases file? if ($this->_leases_file === false) { $this->_LinfoError->add('dhcpd3 leases extension', 'couldn\'t find leases file'); $this->_res = false; return false; } // Get contents $contents = LinfoCommon::getContents($this->_leases_file, false); // Couldn't? if ($contents === false) { $this->_LinfoError->add('dhcpd3 leases extension', 'Error getting contents of leases file'); $this->_res = false; return false; } // All dates in the file are in UTC format. Attempt finding out local time zone to convert UTC to local. // This prevents confusing the hell out of people. $do_date_conversion = false; $local_timezone = false; // Make sure we have what we need. Stuff this requires doesn't exist on certain php installations if (function_exists('date_default_timezone_get') && class_exists('DateTime') && class_exists('DateTimeZone')) { // I only want this called once, hence value stored here. It also might fail $local_timezone = @date_default_timezone_get(); // Make sure it didn't fail if ($local_timezone !== false && is_string($local_timezone)) { $do_date_conversion = true; } // Say we'll allow conversion later on } // Get it into lines $lines = explode("\n", $contents); // Store temp entries here $curr = false; // Parse each line, while ignoring certain useless'ish values // I'd do a single preg_match_all() using multiline regex, but the values in each lease block are inconsistent. :-/ for ($i = 0, $num_lines = count($lines); $i < $num_lines; $i++) { // Kill padding whitespace $lines[$i] = trim($lines[$i]); // Last line in entry if ($lines[$i] == '}') { // Have we a current entry to save? if (is_array($curr)) { $this->_leases[] = $curr; } // Make it empty for next time $curr = false; } elseif (preg_match('/^lease (\\d+\\.\\d+\\.\\d+\\.\\d+) \\{$/', $lines[$i], $m)) { $curr = array('ip' => $m[1]); } elseif ($curr && preg_match('/^starts \\d+ (\\d+\\/\\d+\\/\\d+ \\d+:\\d+:\\d+);$/', $lines[$i], $m)) { // Get it in unix time stamp for prettier formatting later and easier tz offset conversion $curr['lease_start'] = strtotime($m[1]); // Handle offset conversion if ($do_date_conversion) { // This handy class helps out with timezone offsets. Pass it original date, not unix timestamp $d = new DateTime($m[1], new DateTimeZone($local_timezone)); $offset = $d->getOffset(); // If ofset looks good, deal with it if (is_numeric($offset) && $offset != 0) { $curr['lease_start'] += $offset; } } } elseif ($curr && preg_match('/^ends \\d+ (\\d+\\/\\d+\\/\\d+ \\d+:\\d+:\\d+);$/', $lines[$i], $m)) { // Get it in unix time stamp for prettier formatting later and easier tz offset conversion $curr['lease_end'] = strtotime($m[1]); // Handle offset conversion if ($do_date_conversion) { // This handy class helps out with timezone offsets. Pass it original date, not unix timestamp $d = new DateTime($m[1], new DateTimeZone($local_timezone)); $offset = $d->getOffset(); // If ofset looks good, deal with it if (is_numeric($offset) && $offset != 0) { $curr['lease_end'] += $offset; } } // Is this old? // The file seems to contain all leases since the dhcpd server was started for the first time if (time() > $curr['lease_end']) { // Kill current entry and ignore any following parts of this lease $curr = false; // Jump out right now continue; } } elseif (!$this->_hide_mac && $curr && preg_match('/^hardware ethernet (\\w+:\\w+:\\w+:\\w+:\\w+:\\w+);$/', $lines[$i], $m)) { $curr['mac'] = $m[1]; } elseif ($curr && preg_match('/^client\\-hostname "([^"]+)";$/', $lines[$i], $m)) { $curr['hostname'] = $m[1]; } } }
private function parseSysLogData() { $file = '/var/log/syslog'; if (!is_file($file) || !is_readable($file)) { return array(); } $devices = array(); foreach (LinfoCommon::getLines($file) as $line) { if (preg_match('/\\w+\\s*\\d+ \\d{2}:\\d{2}:\\d{2} \\w+ hddtemp\\[\\d+\\]: (.+): (.+): (\\d+) ([CF])/i', trim($line), $match) == 1) { // Replace current record of dev with updated temp $devices[$match[1]] = array($match[2], $match[3], $match[4]); } } $return = array(); foreach ($devices as $dev => $stat) { $return[] = array('path' => $dev, 'name' => $stat[0], 'temp' => $stat[1], 'unit' => strtoupper($stat[2])); } return $return; }
protected function loadDmesg() { $this->dmesg = LinfoCommon::getContents('/var/run/dmesg.boot'); }
public function xmlOut() { $lang = $this->linfo->getLang(); $settings = $this->linfo->getSettings(); $info = $this->linfo->getInfo(); try { // Start it up $xml = new SimpleXMLElement('<?xml version="1.0"?><linfo></linfo>'); // Deal with core stuff $core_elem = $xml->addChild('core'); $core = array(); if (!empty($settings['show']['os'])) { $core[] = array('os', $info['OS']); } if (!empty($settings['show']['distro']) && isset($info['Distro']) && is_array($info['Distro'])) { $core[] = array($lang['distro'], $info['Distro']['name'] . ($info['Distro']['version'] ? ' - ' . $info['Distro']['version'] : '')); } if (!empty($settings['show']['kernel'])) { $core[] = array('kernel', $info['Kernel']); } if (!isset($settings['show']['ip']) || !empty($settings['show']['ip'])) { $core[] = array('accessed_ip', isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : 'Unknown'); } if (!empty($settings['show']['uptime'])) { $core[] = array('uptime', $info['UpTime']); } if (!empty($settings['show']['hostname'])) { $core[] = array('hostname', $info['HostName']); } if (!empty($settings['show']['cpu'])) { $cpus = ''; foreach ((array) $info['CPU'] as $cpu) { $cpus .= (array_key_exists('Vendor', $cpu) && empty($cpu['Vendor']) ? $cpu['Vendor'] . ' - ' : '') . $cpu['Model'] . (array_key_exists('MHz', $cpu) ? $cpu['MHz'] < 1000 ? ' (' . $cpu['MHz'] . ' MHz)' : ' (' . round($cpu['MHz'] / 1000, 3) . ' GHz)' : '') . '<br />'; } $core[] = array('CPU', $cpus); } if (!empty($settings['show']['model']) && array_key_exists('Model', $info) && !empty($info['Model'])) { $core[] = array($lang['model'], $info['Model']); } if (!empty($settings['show']['load'])) { $core[] = array('load', implode(' ', (array) $info['Load'])); } if (!empty($settings['show']['process_stats']) && $info['processStats']['exists']) { $proc_stats = array(); if (array_key_exists('totals', $info['processStats']) && is_array($info['processStats']['totals'])) { foreach ($info['processStats']['totals'] as $k => $v) { $proc_stats[] = $k . ': ' . number_format($v); } } $proc_stats[] = 'total: ' . number_format($info['processStats']['proc_total']); $core[] = array('processes', implode('; ', $proc_stats)); if ($info['processStats']['threads'] !== false) { $core[] = array('threads', number_format($info['processStats']['threads'])); } } for ($i = 0, $core_num = count($core); $i < $core_num; $i++) { $core_elem->addChild($core[$i][0], $core[$i][1]); } // RAM if (!empty($settings['show']['ram'])) { $mem = $xml->addChild('memory'); $core_mem = $mem->addChild($info['RAM']['type']); $core_mem->addChild('free', $info['RAM']['free']); $core_mem->addChild('total', $info['RAM']['total']); $core_mem->addChild('used', $info['RAM']['total'] - $info['RAM']['free']); if (isset($info['RAM']['swapFree']) || isset($info['RAM']['swapTotal'])) { $swap = $mem->addChild('swap'); $swap_core = $swap->addChild('core'); $swap_core->addChild('free', $info['RAM']['swapFree']); $swap_core->addChild('total', $info['RAM']['swapTotal']); $swap_core->addChild('used', $info['RAM']['swapTotal'] - $info['RAM']['swapFree']); if (is_array($info['RAM']['swapInfo']) && count($info['RAM']['swapInfo']) > 0) { $swap_devices = $swap->addChild('devices'); foreach ($info['RAM']['swapInfo'] as $swap_dev) { $swap_dev_elem = $swap_devices->addChild('device'); $swap_dev_elem->addAttribute('device', $swap_dev['device']); $swap_dev_elem->addAttribute('type', $swap_dev['type']); $swap_dev_elem->addAttribute('size', $swap_dev['size']); $swap_dev_elem->addAttribute('used', $swap_dev['used']); } } } } // NET if (!empty($settings['show']['network']) && isset($info['Network Devices']) && is_array($info['Network Devices'])) { $net = $xml->addChild('net'); foreach ($info['Network Devices'] as $device => $stats) { $nic = $net->addChild('interface'); $nic->addAttribute('device', $device); $nic->addAttribute('type', $stats['type']); $nic->addAttribute('sent', $stats['sent']['bytes']); $nic->addAttribute('recieved', $stats['recieved']['bytes']); } } // TEMPS if (!empty($settings['show']['temps']) && isset($info['Temps']) && count($info['Temps']) > 0) { $temps = $xml->addChild('temps'); foreach ($info['Temps'] as $stat) { $temp = $temps->addChild('temp'); $temp->addAttribute('path', $stat['path']); $temp->addAttribute('name', $stat['name']); $temp->addAttribute('temp', $stat['temp'] . ' ' . $stat['unit']); } } // Batteries if (!empty($settings['show']['battery']) && isset($info['Battery']) && count($info['Battery']) > 0) { $bats = $xml->addChild('batteries'); foreach ($info['Battery'] as $bat) { $bat = $bats->addChild('battery'); $bat->addAttribute('device', $bat['device']); $bat->addAttribute('state', $bat['state']); $bat->addAttribute('percentage', $bat['percentage']); } } // SERVICES if (!empty($settings['show']['services']) && isset($info['services']) && count($info['services']) > 0) { $services = $xml->addChild('services'); foreach ($info['services'] as $service => $state) { $state_parts = explode(' ', $state['state'], 2); $service_elem = $services->addChild('service'); $service_elem->addAttribute('name', $service); $service_elem->addAttribute('state', $state_parts[0] . (array_key_exists(1, $state_parts) ? ' ' . $state_parts[1] : '')); $service_elem->addAttribute('pid', $state['pid']); $service_elem->addAttribute('threads', $state['threads'] ? $state['threads'] : '?'); $service_elem->addAttribute('mem_usage', $state['memory_usage'] ? $state['memory_usage'] : '?'); } } // DEVICES if (!empty($settings['show']['devices']) && isset($info['Devices'])) { $show_vendor = array_key_exists('hw_vendor', $info['contains']) ? $info['contains']['hw_vendor'] === false ? false : true : true; $devices = $xml->addChild('devices'); for ($i = 0, $num_devs = count($info['Devices']); $i < $num_devs; $i++) { $device = $devices->addChild('device'); $device->addAttribute('type', $info['Devices'][$i]['type']); if ($show_vendor) { $device->addAttribute('vendor', $info['Devices'][$i]['vendor']); } $device->addAttribute('name', $info['Devices'][$i]['device']); } } // DRIVES if (!empty($settings['show']['hd']) && isset($info['HD']) && is_array($info['HD'])) { $show_stats = array_key_exists('drives_rw_stats', $info['contains']) ? $info['contains']['drives_rw_stats'] === false ? false : true : true; $drives = $xml->addChild('drives'); foreach ($info['HD'] as $drive) { $drive_elem = $drives->addChild('drive'); $drive_elem->addAttribute('device', $drive['device']); $drive_elem->addAttribute('vendor', $drive['vendor'] ? $drive['vendor'] : $lang['unknown']); $drive_elem->addAttribute('name', $drive['name']); if ($show_stats) { $drive_elem->addAttribute('reads', $drive['reads'] ? $drive['reads'] : 'unknown'); $drive_elem->addAttribute('writes', $drive['writes'] ? $drive['writes'] : 'unknown'); } $drive_elem->addAttribute('size', $drive['size'] ? $drive['size'] : 'unknown'); if (is_array($drive['partitions']) && count($drive['partitions']) > 0) { $partitions = $drive_elem->addChild('partitions'); foreach ($drive['partitions'] as $partition) { $partition_elem = $partitions->addChild('partition'); $partition_elem->addAttribute('name', isset($partition['number']) ? $drive['device'] . $partition['number'] : $partition['name']); $partition_elem->addAttribute('size', $partition['size']); } } } } // Sound cards? lol if (!empty($settings['show']['sound']) && isset($info['SoundCards']) && count($info['SoundCards']) > 0) { $cards = $xml->addChild('soundcards'); foreach ($info['SoundCards'] as $card) { $card_elem = $cards->addChild('card'); $card_elem->addAttribute('number', $card['number']); $card_elem->addAttribute('vendor', empty($card['vendor']) ? 'unknown' : $card['vendor']); $card_elem->addAttribute('card', $card['card']); } } // File system mounts if (!empty($settings['show']['mounts'])) { $has_devices = false; $has_labels = false; $has_types = false; foreach ($info['Mounts'] as $mount) { if (!empty($mount['device'])) { $has_devices = true; } if (!empty($mount['label'])) { $has_labels = true; } if (!empty($mount['devtype'])) { $has_types = true; } } $mounts = $xml->addChild('mounts'); foreach ($info['Mounts'] as $mount) { $mount_elem = $mounts->addChild('mount'); if (preg_match('/^.+:$/', $mount['device']) == 1) { $mount['device'] .= DIRECTORY_SEPARATOR; } if ($has_types) { $mount_elem->addAttribute('type', $mount['devtype']); } if ($has_devices) { $mount_elem->addAttribute('device', $mount['device']); } $mount_elem->addAttribute('mountpoint', $mount['mount']); if ($has_labels) { $mount_elem->addAttribute('label', $mount['label']); } $mount_elem->addAttribute('fstype', $mount['type']); if ($settings['show']['mounts_options'] && !empty($mount['options'])) { $mount_elem->addAttribute('options', implode(',', $mount['options'])); } $mount_elem->addAttribute('size', $mount['size']); $mount_elem->addAttribute('used', $mount['used']); $mount_elem->addAttribute('free', $mount['free']); } } // RAID arrays if (!empty($settings['show']['raid']) && isset($info['Raid']) && count($info['Raid']) > 0) { $raid_elem = $xml->addChild('raid'); foreach ($info['Raid'] as $raid) { $array = $raid_elem->addChild('array'); $active = explode('/', $raid['count']); $array->addAttribute('device', $raid['device']); $array->addAttribute('level', $raid['level']); $array->addAttribute('status', $raid['status']); $array->addAttribute('size', $raid['size']); $array->addAttribute('active', $active[1] . '/' . $active[0]); $drives = $array->addChild('drives'); foreach ($raid['drives'] as $drive) { $drive_elem = $drives->addChild('drive'); $drive_elem->addAttribute('drive', $drive['drive']); $drive_elem->addAttribute('state', $drive['state']); } } } // Timestamp $xml->addChild('timestamp', $info['timestamp']); // Extensions if (count($info['extensions']) > 0) { $extensions = $xml->addChild('extensions'); foreach ($info['extensions'] as $ext) { $header = false; if (is_array($ext) && count($ext) > 0) { $this_ext = $extensions->addChild(LinfoCommon::xmlStringSanitize($ext['root_title'])); foreach ((array) $ext['rows'] as $i => $row) { if ($row['type'] == 'header') { $header = $i; } elseif ($row['type'] == 'values') { $this_row = $this_ext->addChild('row'); if ($header !== false && array_key_exists($header, $ext['rows'])) { foreach ($ext['rows'][$header]['columns'] as $ri => $rc) { $this_row->addChild(LinfoCommon::xmlStringSanitize($rc), $ext['rows'][$i]['columns'][$ri]); } } } } } } } // Out it if (!headers_sent()) { header('Content-type: text/xml'); } echo $xml->asXML(); // Comment which has stats and generator echo '<!-- Generated in ' . round(microtime(true) - $this->linfo->getTimeStart(), 2) . ' seconds by ' . $this->linfo->getAppName() . ' (' . $this->linfo->getVersion() . ')-->'; } catch (Exception $e) { throw new LinfoFatalException('Creation of XML error: ' . $e->getMessage()); } }
public function result() { if (!$this->res) { return false; } $rows[] = array('type' => 'header', 'columns' => array('VM Name', 'Status', 'RAM Allocation', 'CPUs', 'CPU Time', 'Block Storage')); foreach ($this->VMs as $name => $info) { $disks = array(); foreach ($info['storage'] as $disk) { $disks[] = $disk['device'] . (isset($disk['file']) && isset($disk['capacity']) ? ': ' . $disk['file'] . ' (' . LinfoCommon::byteConvert($disk['capacity'], 2) . ')' : ''); } $rows[] = array('type' => 'values', 'columns' => array($name, $info['state'] == 1 ? '<span style="color: green;">On</span>' : '<span style="color: maroon;">Off</span>', LinfoCommon::byteConvert($info['memory'] * 1024, 2), $info['nrVirtCpu'], $info['cpuUsed'] ? $info['cpuUsed'] : 'N/A', $disks ? implode('<br />', $disks) : 'None')); } // Give it off return array('root_title' => 'libvirt Virtual Machines', 'rows' => $rows); }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Use sysctl to get unix timestamp of boot. Very elegant! if (preg_match('/^\\{ sec \\= (\\d+).+$/', $this->sysctl['kern.boottime'], $m) == 0) { return ''; } // Boot unix timestamp $booted = $m[1]; // Get it textual, as in days/minutes/hours/etc return LinfoCommon::secondsConvert(time() - $booted) . '; booted ' . date($this->settings['dates'], $booted); }
public static function tearDownAfterClass() { self::$parser = null; LinfoCommon::unconfig(); LinfoCommon::$path_prefix = false; }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Short and sweet $booted = $this->sysctl['kern.boottime']; if ($booted == false) { return 'Unknown'; } // Is it not a timestamp? if (!is_numeric($booted)) { $booted = strtotime($booted); } // Give it return LinfoCommon::secondsConvert(time() - $booted) . '; booted ' . date($this->settings['dates'], $booted); }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Use sysctl to get unix timestamp of boot. Very elegant! if (preg_match('/^\\{ sec \\= (\\d+).+$/', $this->sysctl['kern.boottime'], $m) == 0) { return ''; } // Boot unix timestamp $booted = $m[1]; // Give it return array('text' => LinfoCommon::secondsConvert(time() - $booted), 'bootedTimestamp' => $booted); }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Use sysctl $booted = strtotime($this->sysctl['kern.boottime']); // Give it return LinfoCommon::secondsConvert(time() - $booted) . '; booted ' . date($this->settings['dates'], $booted); }
/** * Run a command and cache its output for later * * @throws CallExtException * @param string $name name of executable to call * @param string $switches command arguments */ public function exec($name, $switches = '') { // Sometimes it is necessary to call a program with sudo $attempt_sudo = array_key_exists('sudo_apps', self::$settings) && in_array($name, self::$settings['sudo_apps']); // Have we gotten it before? if (array_key_exists($name . $switches, $this->cliCache)) { return $this->cliCache[$name . $switches]; } // Try finding the exec foreach ($this->searchPaths as $path) { // Found it; run it if (is_file($path . $name) && is_executable($path . $name)) { // Complete command, path switches and all $command = "{$path}{$name} {$switches}"; // Sudoing? $command = $attempt_sudo ? LinfoCommon::locateActualPath(LinfoCommon::arrayAppendString($this->searchPaths, 'sudo', '%2s%1s')) . ' ' . $command : $command; // Result of command $result = `{$command}`; // Increment call count self::$callCount++; // Cache that $this->cliCache[$name . $switches] = $result; // Give result return $result; } } // Never got it throw new CallExtException('Exec `' . $name . '\' not found'); }
/** * getUpTime * * @access public * @return string uptime */ public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } $booted_str = ""; foreach ($this->wmi->ExecQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem") as $os) { $booted_str = $os->LastBootUpTime; break; } $booted = array('year' => substr($booted_str, 0, 4), 'month' => substr($booted_str, 4, 2), 'day' => substr($booted_str, 6, 2), 'hour' => substr($booted_str, 8, 2), 'minute' => substr($booted_str, 10, 2), 'second' => substr($booted_str, 12, 2)); $booted_ts = mktime($booted['hour'], $booted['minute'], $booted['second'], $booted['month'], $booted['day'], $booted['year']); return LinfoCommon::secondsConvert(time() - $booted_ts) . '; booted ' . date($this->settings['dates'], $booted_ts); }
public function getUpTime() { // Time? if (!empty($this->settings['timer'])) { $t = new LinfoTimerStart('Uptime'); } // Use sysctl $booted = strtotime($this->sysctl['kern.boottime']); // Give it return array('text' => LinfoCommon::secondsConvert(time() - $booted), 'bootedTimestamp' => $booted); }
/** * Get the PCI ids from /sys * * @access private */ private function _fetchPciIdsLinux() { foreach ((array) @glob('/sys/bus/pci/devices/*', GLOB_NOSORT) as $path) { // See if we can use simple vendor/device files and avoid taking time with regex if (($f_device = LinfoCommon::getContents($path . '/device', '')) && ($f_vend = LinfoCommon::getContents($path . '/vendor', '')) && $f_device != '' && $f_vend != '') { list(, $v_id) = explode('x', $f_vend, 2); list(, $d_id) = explode('x', $f_device, 2); $this->_pci_entries[$v_id][$d_id] = 1; } elseif (is_readable($path . '/uevent') && preg_match('/pci\\_(?:subsys_)?id=(\\w+):(\\w+)/', strtolower(LinfoCommon::getContents($path . '/uevent')), $match)) { $this->_pci_entries[$match[1]][$match[2]] = 1; } elseif (is_readable($path . '/modalias') && preg_match('/^pci:v0{4}([0-9A-Z]{4})d0{4}([0-9A-Z]{4})/', LinfoCommon::getContents($path . '/modalias'), $match)) { $this->_pci_entries[strtolower($match[1])][strtolower($match[2])] = 1; } } }
/** * Get brand/name of motherboard/server through /sys' interface to dmidecode * * @access public */ public function getModel() { $info = array(); $vendor = LinfoCommon::getContents('/sys/devices/virtual/dmi/id/board_vendor', false); $name = LinfoCommon::getContents('/sys/devices/virtual/dmi/id/board_name', false); $product = LinfoCommon::getContents('/sys/devices/virtual/dmi/id/product_name', false); if (!$name) { return false; } // Don't add vendor to the mix if the name starts with it if ($vendor && strpos($name, $vendor) !== 0) { $info[] = $vendor; } $info[] = $name; $infostr = implode(' ', $info); // product name is usually bullshit, but *occasionally* it's a useful name of the computer, such as // dell latitude e6500 or hp z260 if ($product && strpos($name, $product) === false && strpos($product, 'Filled') === false) { return $product . ' (' . $infostr . ')'; } else { return $infostr; } }