Menu="Dashboard"
Nchan="wg_poller,update_1,update_2,update_3,ups_status:stop"
---
<?PHP
/* Copyright 2005-2022, Lime Technology
 * Copyright 2012-2022, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
*/
?>
<?
function dmidecode($key,$n,$all=true) {
  $entries = array_filter(explode($key,shell_exec("dmidecode -qt$n")));
  $properties = [];
  foreach ($entries as $entry) {
    $property = [];
    foreach (explode("\n",$entry) as $line) if (strpos($line,': ')!==false) {
      [$key,$value] = my_explode(': ',trim($line));
      $property[$key] = $value;
    }
    $properties[] = $property;
  }
  return $all ? $properties : $properties[0];
}
function export_settings($protocol,$share) {
  if ($protocol!='yes' || $share['export']=='-') return "-";
  if ($share['export']=='e') return _(ucfirst($share['security']));
  return '<em>'._(ucfirst($share['security'])).'</em>';
}
function vpn_peers($file) {
  $peers = [];
  $entries = array_filter(array_map('trim',preg_split('/\[(Interface|Peer)\]/',file_get_contents($file))));
  foreach($entries as $key => $entry) {
    $noname = true;
    foreach (explode("\n",$entry) as $row) {
      if ($key>1 && $row[0]=='#') {$peers[$key-1] = substr($row,1); $noname = false;}
    }
    if ($key>1 && $noname) $peers[$key-1] = "Peer ".($key-1);
  }
  return $peers;
}
// adjust the text color in log window
$fgcolor = in_array($theme,['white','azure']) ? '#1c1c1c' : '#f2f2f2';
exec("sed -ri 's/^\.logLine\{color:#......;/.logLine{color:$fgcolor;/' $docroot/plugins/dynamix.docker.manager/log.htm >/dev/null &");

$dockerd = pgrep('dockerd');
$libvirtd = pgrep('libvirtd');
$apcupsd = file_exists('/var/run/apcupsd.pid');
$conf  = glob('/etc/wireguard/wg*.conf');
$wireguard = is_executable('/usr/bin/wg') && count($conf);
$started = $var['fsState']=='Started';
$sleep = isset($display['sleep']);
$array_size = $array_used = 0;
$extra_size = $extra_used = 0;
$cache_size = $cache_used = [];
$cache_type = $cache_rate = [];

$parity = $var['mdResync'];
$mover = file_exists('/var/run/mover.pid');
$btrfs = exec('pgrep -cf /sbin/btrfs');
$dot = $display['number'][0];

foreach ($disks as $disk) {
  switch ($disk['type']) {
  case 'Data':
    if (isset($disk['fsFree'])) {
      $array_size += $disk['fsSize'];
      $array_used += $disk['fsSize']-$disk['fsFree'];
    }
    break;
  case 'Cache':
    $name = $disk['name'];
    if (in_array($name,$pools)) {
      $cache_size[$name] = $disk['fsSize'];
      $cache_used[$name] = $disk['fsSize']-$disk['fsFree'];
      $cache_type[$name] = $disk['rotational'] ? ($disk['luksState'] ? 'disk-encrypted' : 'disk') : 'nvme';
      $cache_rate[$name] = number_format(100*$cache_used[$name]/($cache_size[$name] ?: 1),1,$dot,'');
      if (!$disks[$name]['devices']) unset($pools[array_search($name,$pools)]);
    }
    break;
  }
}
foreach ($devs as $disk) {
  $extra_size += $disk['sectors']*$disk['sector_size'];
}
$array_percent = number_format(100*$array_used/($array_size ?: 1),1,$dot,'');
exec('cat /sys/devices/system/cpu/*/topology/thread_siblings_list|sort -nu', $cpus);
$wg_up = $wireguard ? exec("wg show interfaces") : '';
$wg_up = $wg_up ? explode(' ',$wg_up) : [];
$up    = count($wg_up);
$down  = max(count($conf)-$up,0);
$fans  = exec("sensors -uA 2>/dev/null|grep -c 'fan[0-9]_input'");
$autofan = is_executable("$docroot/plugins/dynamix.system.autofan/scripts/rc.autofan");
$group = $var['shareSMBEnabled']=='yes' | $var['shareNFSEnabled']=='yes';
$names = [];
$cache_only = $encrypted = 0;
foreach ($shares as $share) {
  if ($share['useCache']=='only') $cache_only++;
  if ($share['luksStatus']>0) $encrypted++;
}
$passwd = $nopass = 0;
foreach ($users as $user) if ($user['passwd']=='yes') $passwd++; else $nopass++;

$boot   = "/boot/config/plugins/dynamix";
$myfile = "case-model.cfg";
$mycase = file_exists("$boot/$myfile") ? file_get_contents("$boot/$myfile") : false;

$board  = dmidecode('Base Board Information','2',0);
$serial = _("s/n").": ".($board['Serial Number'] ?? "--");
$board  = ($board['Manufacturer'] ?? "").' '.($board['Product Name'] ?? "").' '.(isset($board['Version']) ? ", "._("Version")." ".$board['Version'] : "");

$bios = dmidecode('BIOS Information','0',0);
$biosdate = _("BIOS dated").": "._(my_time(strtotime($bios['Release Date'] ?? ""),$display['date']),0);
$bios = $bios['Vendor'].(isset($bios['Version']) ? ", "._("Version")." ".$bios['Version'] : "");

$cpu = dmidecode('Processor Information','4',0);
$cpumodel = str_ireplace(["Processor","(C)","(R)","(TM)"],["","&#169;","&#174;","&#8482;"],$cpu['Version'] ?? exec("grep -Pom1 'model name\s+:\s*\K.+' /proc/cpuinfo"));
$cpumodel .= (strpos($cpumodel,'@')===false && !empty($cpu['Current Speed']) ? " @ {$cpu['Current Speed']}" : "");

$total = exec("awk '/^MemTotal/{print $2*1024}' /proc/meminfo");
unset($ports); exec("ls /sys/class/net|grep -Po '^(lo|(bond|eth)\d+)$'",$ports);

$sizes = ['MB','GB','TB'];
$memory_type = $ecc = '';
$memory_installed = $memory_maximum = 0;
$memory_devices = dmidecode('Memory Device','17');
foreach ($memory_devices as $device) {
  if (!is_numeric($device['Size'][0])) continue;
  [$size, $unit] = my_explode(' ',$device['Size']);
  $base = array_search($unit,$sizes);
  if ($base!==false) $memory_installed += $size*pow(1024,$base);
  if (!$memory_type && $device['Type']!='Unknown') $memory_type = $device['Type'];
}
$memory_array = dmidecode('Physical Memory Array','16');
foreach ($memory_array as $device) {
  [$size, $unit] = my_explode(' ',$device['Maximum Capacity']);
  $base = array_search($unit,$sizes);
  if ($base>=1) $memory_maximum += $size*pow(1024,$base);
  if (!$ecc && $device['Error Correction Type']!='None') $ecc = "{$device['Error Correction Type']} ";
}
if ($memory_installed >= 1024) {
  $memory_installed = round($memory_installed/1024);
  $memory_maximum = round($memory_maximum/1024);
  $unit = 'GiB';
} else $unit = 'MiB';

// If maximum < installed then roundup maximum to the next power of 2 size of installed. E.g. 6 -> 8 or 12 -> 16
$low = $memory_maximum < $memory_installed;
if ($low) $memory_maximum = pow(2,ceil(log($memory_installed)/log(2)));

switch ($display['theme']) {
  case 'white': $color = '#1c1b1b'; $grid = '#e3e3e3'; break;
  case 'black': $color = '#f2f2f2'; $grid = '#2b2b2b'; break;
  case 'azure': $color = '#606e7f'; $grid = '#f3f0f4'; break;
  case 'gray' : $color = '#606e7f'; $grid = '#0c0f0b'; break;
  default     : $color = '#1c1b1b'; $grid = '#e3e3e3'; break;
}
?>
<link type="text/css" rel="stylesheet" href="<?autov('/webGui/styles/jquery.switchbutton.css')?>">
<link type="text/css" rel="stylesheet" href="<?autov('/webGui/styles/jquery.ui.css')?>">
<link type="text/css" rel="stylesheet" href="<?autov("/plugins/dynamix.docker.manager/styles/style-$theme.css")?>">
<style>
div.frame{float:left;margin:14px 0}
div#iframe-popup{display:none;-webkit-overflow-scrolling:touch}
div.last{padding-bottom:12px}
div.left{float:left;width:66%;margin-top:-12px}
div.right{float:right;margin:-20px 0 0 0;text-align:center}
div[id$=chart]{margin-top:-12px;margin-bottom:-24px;padding:0}
.section,.next{cursor:grab}
span.ctrl{float:right;margin-right:10px}
span.outer{float:left}
span.inner{width:<?=$themes1?153:140?>px}
span.ups{width:200px;display:inline-block;margin-bottom:4px}
span.tx{width:75px;display:inline-block}
span.busy,i.inactive{opacity:0.5}
span#inbound{width:75px;display:inline-block}
span#load{width:120px;display:inline-block}
span#util{margin-left:20px}
span#ups_model{margin-right:30px}
span[id^=cpu],span[id^=sys]{width:0}
select#cpuline,select#netline{border:none;padding:0 12px 0 0}
i.heat{margin-left:8px}
i.ups{margin-right:8px}
a.cpu_close,span.hand{cursor:pointer;z-index:1001}
tr.hidden{display:none;height:0;lineheight:0}
td.none{text-align:center;padding-top:12px}
input[value=Edit]{margin:12px 0 0 0;padding:5px 10px}
.sys_view,.mb_view,.cpu_view,.cpu_open,.mem_view,.port_view,.ups_view,.fan_view,.docker_view,.vm_view,.parity_view,.array_view,.my_view,.extra_view{display:none}
.share1,.share2,.share3,.view1,.view2,.view3,.view4,.user1,.user2,.user3{display:none}
.port_view,.chevron,#apps,#vms{z-index:10000}
#shares_view_on,#users_view_on,#array_view_on,#extra_view_on{display:none}
#db-box2{margin-bottom:140px}
<?foreach ($pools as $pool):?>
._<?=$pool?>_view{display:none}
#_<?=$pool?>_view_on{display:none}
<?endforeach;?>
form[name=boot]{display:none}
.flat{height:0;lineheight:0}
.wrap{white-space:normal}
<?if ($themes2):?>
.switch-button-background{top:16px}
.switch-button-label{margin-top:0}
<?else:?>
.switch-button-background{top:12px}
<?endif;?>
</style>
<script src="<?autov('/webGui/javascript/jquery.apexcharts.js')?>"></script>
<script src="<?autov('/webGui/javascript/jquery.switchbutton.js')?>"></script>
<script src="<?autov('/plugins/dynamix.docker.manager/javascript/docker.js')?>"></script>
<script src="<?autov('/plugins/dynamix.vm.manager/javascript/vmmanager.js')?>"></script>

<?$N=0?>
<div class='frame'>
<table id='db-box1' class='share_status dashboard box1'>
<thead sort='<?=$N?>' class='sortable'><tr><td></td><td colspan='3' class='next'><?=$var['NAME']?>
<i class='fa fa-fw chevron mt0' id='sys_view' onclick='toggleChevron("sys_view",0)'></i>
<a href='/Dashboard/Settings/Identification' title="_(Go to identification settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<span class='ctrl'>
<?if ($parity||$mover||$btrfs):?>
<span class='fa fa-fw fa-<?=$started?'stop':'play'?>-circle busy' title="<?=$started?_("Stop the array"):_("Start the array")?>"></span>
<?else:?>
<span class='fa fa-fw fa-<?=$started?'stop':'play'?>-circle hand' title="<?=$started?_("Stop the array"):_("Start the array")?>" onclick='<?=$started?'Stop':'Start'?>Array()'></span>
<?endif;?>
<?if($sleep):?><span class='fa fa-fw fa-moon-o hand' title="_(Put system to sleep)_" onclick='Sleep()'></span><?endif;?>
<span class='fa fa-fw fa-refresh hand' title="_(Reboot the system)_" onclick='Reboot()'></span>
<span class='fa fa-fw fa-power-off hand' title="_(Shutdown the system)_" onclick='Shutdown()'></span></span>
</td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sys_view sortable'>
<tr><td></td><td colspan='3'>
<div class='left'>
<span class='header'>_(Description)_</span><span class='text'><br>
<?=$var['COMMENT']?><br>
<?=$var['SYS_MODEL']?><br><br></span>
<span class='header'>_(Registration)_</span><br>Unraid OS <b><em><?=$var['regTy']?></em></b><br><br>
<span class='header'>_(Uptime)_</span><br><span class='uptime'></span>
</div>
<div class='right'>
<span id='casing'>
<?if ($mycase):?>
<?if (substr($mycase,-4)!='.png'):?>
<i id='mycase' class='case-<?=$mycase?>'></i><br>
<?else:?>
<img id='mycase' src='<?=autov("/webGui/images/$mycase")?>'><br>
<?endif;?>
<?else:?>
<i id='mycase' class='fa fa-hdd-o'></i><br>
<?endif;?>
</span>
<input type='button' value="_(Edit)_" style="margin-right:0" onclick='openChanges("select_case <?=$myfile?>", "_(Select Case Model)_", "selectcase")'>
</div>
</td><td></td></tr>
</tbody>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-motherboard'></i><div class='section'>_(Motherboard)_<br><span id='mb-temp'></span><br><br></div>
<i class='fa fa-fw chevron' id='mb_view' onclick='toggleChevron("mb_view",0)'></i>
<a href='#' onclick='InfoButton();' title="_(Show Information)_"><i class='fa fa-fw fa-info-circle chevron'></i></a>
</td><td></td></tr>
<tr class='mb_view'><td></td><td colspan='3'><?=$board?><br><?=$bios?><br><?=$biosdate?></td><td></td></tr>
</tbody>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-cpu'></i><div class='section'>_(Processor)_<br>
<span id='load'><i class='ups fa fa-bars'></i>_(Load)_: <span class='cpu'>0%</span></span><span id='cpu-temp'></span><br><br></div>
<i class='fa fa-fw chevron' id='cpu_view' onclick='toggleChevron("cpu_view",1)'></i>
<a href='/Dashboard/Settings/CPUset' title="_(Go to CPU pinning settings)_"><i class='fa fa-fw fa-cog chevron'></i></a>
</td><td></td></tr>
<tr class='cpu_view'><td></td><td colspan='3'><?=$cpumodel?><br>
<a onclick='toggleCPU()' title="_(Click to toggle details)_" class='cpu_close'>_(Show details)_</a><span id='chart-toggle' style='float:right'>
<span><select id='cpuline' class='auto' title="_(Select time frame)_" onchange='changeCPUline(this.value)'>
<?=mk_option("","10", _("10 s"));?>
<?=mk_option("","30", _("30 s"));?>
<?=mk_option("","60", _("1 m"));?>
<?=mk_option("","120", _("2 m"));?>
<?=mk_option("","300", _("5 m"));?>
</select></span><a onclick='toggleChart()' title="_(Click to toggle CPU chart)_"><span class="hand fa fa-fw fa-bar-chart"></span></a></span></td><td></td></tr>
<tr class='cpu_chart' style='display:none'><td colspan='4'><div id='cpuchart'></div></td><td></td></tr>
<tr class='cpu_open'><td></td><td>_(Overall Load)_:</td><td colspan='2'><span class='cpu load'>0%</span><div class='usage-disk sys'><span id='cpu'></span><span></span></div></td><td></td></tr>
<?
foreach ($cpus as $pair) {
  [$cpu1, $cpu2] = my_preg_split('/[,-]/',$pair);
  echo "<tr class='cpu_open'><td></td>";
  if ($cpu2)
    echo "<td>CPU $cpu1 - HT $cpu2</td><td><span class='cpu$cpu1 load'>0%</span><div class='usage-disk sys'><span id='cpu$cpu1'></span><span></span></div></td><td><span class='cpu$cpu2 load'>0%</span><div class='usage-disk sys'><span id='cpu$cpu2'></span><span></span></div></td>";
  else
    echo "<td>CPU $cpu1</td><td colspan='2'><span class='cpu$cpu1 load'>0%</span><div class='usage-disk sys'><span id='cpu$cpu1'></span><span></span></div></td>";
  echo "<td></td></tr>";
}
?>
</tbody>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-ram'></i><div class='section'>_(Memory)_<br><span><?="$memory_installed $unit $memory_type $ecc"?><span id='util'>_(Utilization)_: <span class='sys0'>0%</span></span><br><br></div>
<i class='fa fa-fw chevron' id='mem_view' onclick='toggleChevron("mem_view",0)'></i>
<a href='/Dashboard/Tools/Processes' title="_(View Running Processes)_"><i class='fa fa-fw fa-info-circle chevron'></i></a>
</td><td></td></tr>
<tr class='mem_view'><td></td><td>_(Maximum size)_: <?="$memory_maximum $unit"?><?=$low?'*':''?></td><td><i class='mm'>_(RAM)_</i><span class='sys0 load'>0%</span><div class='usage-disk sys'><span id='sys0'></span><span></span></div></td>
<td><i class='mm'>_(Flash)_</i><span class='sys1 load'>0%</span><div class='usage-disk sys'><span id='sys1'></span><span></span></div></td><td></td></tr>
<tr class='mem_view'><td></td><td>_(Usable size)_: <?=my_scale($total,$unit,1,null,1024)." $unit"?></td><td><i class='mm'>_(Log)_</i><span class='sys2 load'>0%</span><div class='usage-disk sys'><span id='sys2'></span><span></span></div></td>
<td><?if (exec("df /var/lib/docker|grep -om1 '^/'")):?><i class='mm'>_(Docker)_</i><span class='sys3 load'>0%</span><div class='usage-disk sys'><span id='sys3'></span><span></span></div><?endif;?></td><td></td></tr>
</tbody>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-ethernet'></i><div class='section'>_(Interface)_<br>
<select name="port_select" onchange="portSelect(this.value)">
<?foreach ($ports as $port):?>
<?=mk_option("",$port,_($port))?>
<?endforeach;?>
</select>
<span>_(Inbound)_: <span id='inbound'>---</span>_(Outbound)_: <span id='outbound'>---</span></span><br><br></div>
<i class='fa fa-fw chevron' id='port_view' onclick='toggleChevron("port_view",2)'></i>
<a href='/Dashboard/Settings/NetworkSettings' title="_(Go to network settings)_"><i class='fa fa-fw fa-cog chevron'></i></a>
</td><td></td></tr>
<tr class='port_view'><td></td>
<td><select class='port_view' name="enter_view" onchange="changeView(this.value)">
<?=mk_option("", "0", _("General info"))?>
<?=mk_option("", "1", _("Counters info"))?>
<?=mk_option("", "2", _("Errors info"))?>
<?=mk_option("", "3", _("Network traffic"))?>
</select></td>
<td><i class='view1'>_(Mode of operation)_</i><i class='view2'>_(Received packets)_</i><i class='view3'>_(Receive counters)_</i><i class='fa fa-fw fa-arrow-down view4 red-text'></i>&nbsp;<i class='view4 red-text'>_(Inbound)_</i></td>
<td><i class='view1'></i><i class='view2'>_(Transmitted packets)_</i><i class='view3'>_(Transmit counters)_</i><i class='fa fa-fw fa-arrow-up view4 orange-text'></i>&nbsp;<i class='view4 orange-text'>_(Outbound)_</i>
<span class='view4' style='float:right;margin-right:24px'><select id='netline' class='auto' title="_(Select time frame)_" onchange='changeNetline(this.value)'>
<?=mk_option("","10", _("10 s"));?>
<?=mk_option("","30", _("30 s"));?>
<?=mk_option("","60", _("1 m"));?>
<?=mk_option("","120", _("2 m"));?>
<?=mk_option("","300", _("5 m"));?>
</select></span></td><td></td></tr>
<?
$c = 0;
foreach ($ports as $port) {
  $last = ($port=='lo')?' last':'';
  echo "<tr class='view1{$last}'><td></td><td>$port</td><td colspan='2' id='main".($c++)."'></td><td></td></tr>";
}
$c = 0;
foreach ($ports as $port) {
  $last = ($port=='lo')?' last':'';
  echo "<tr class='view2{$last}'><td></td><td>$port</td><td id='port{$c}'></td><td id='port".($c+1)."'></td><td></td></tr>";
  $c += 2;
}
$c = 0;
foreach ($ports as $port) {
  echo "<tr class='view3'><td></td><td>$port</td><td id='link{$c}'></td><td id='link".($c+1)."'></td><td></td></tr>";
  $c += 2;
}
?>
<tr class="view4"><td colspan="4"><div id="netchart"></div></td><td></td></tr>
</tbody>
<?if ($wireguard):?>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-vpn'></i><div class='section'>_(VPN)_<br><span class='ups'>_(Active tunnels)_: <span id='vpn-active'><?=$up?></span></span><span class='ups'>_(Inactive tunnels)_: <span id='vpn-inactive'><?=$down?></span></span><br><br></div>
<i class='fa fa-fw chevron' id='vpn_view' onclick='toggleChevron("vpn_view",0)'></i>
<a href='/Settings/VPNmanager' title="_(Go to VPN settings)_"><i class='fa fa-fw fa-cog chevron'></i></a>
</td><td></td></tr>
<?foreach ($conf as $wg):?>
<?$vpn = basename($wg,'.conf'); $peers = vpn_peers($wg);?>
<tr class='vpn_view'><td></td><td class='vpn'><i class='icon-vpn vpn<?=in_array($vpn,$wg_up)?'':' inactive'?>' onclick="toggleVPN($(this),'<?=$vpn?>')" title="Toggle tunnel state"></i><?="Tunnel $vpn"?></td><td class='vpn right'>_(Activity)_</td><td class='vpn right'>_(Handshake)_</td><td></td></tr>
<?foreach ($peers as $i => $peer):?>
<tr class='vpn_view'><td></td><td class='left'><?=$peer?></td><td class='right' id='<?="$vpn-rx-".($i-1)?>'>---</td><td class='right' id='<?="$vpn-hs-".($i-1)?>'>_(inactive)_</td><td></td></tr>
<?endforeach;?>
<?endforeach;?>
</tbody>
<?endif;?>
<?if ($apcupsd):?>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-ups'></i><div class='section'>_(Power)_<br>
<span><i class='ups fa fa-shield'></i>_(UPS Model)_: </span><span id='ups_model'></span>
<span><i class='ups fa fa-bars'></i>_(UPS Load)_: </span><span id='ups_loadpct'></span><br><br></div>
<i class='fa fa-fw chevron' id='ups_view' onclick='toggleChevron("ups_view",0)'></i>
<a href='/Dashboard/Settings/UPSsettings' title="_(Go to UPS settings)_"><i class='fa fa-fw fa-cog chevron'></i></a>
</td><td></td></tr>
<tr class='ups_view'><td></td><td colspan='3'>
<span class='ups'><i class='ups fa fa-fw fa-plug'></i>_(UPS status)_:</span><span id='ups_status'></span><br>
<span class='ups'><i class='ups fa fa-fw fa-battery'></i>_(Battery charge)_:</span><span id='ups_bcharge'></span><br>
<span class='ups'><i class='ups fa fa-fw fa-clock-o'></i>_(Runtime left)_:</span><span id='ups_timeleft'></span><br>
<span class='ups'><i class='ups fa fa-fw fa-bolt'></i>_(Nominal power)_:</span><span id='ups_nompower'></span><br>
<span class='ups'><i class='ups fa fa-fw fa-ellipsis-h'></i>_(Output voltage)_:</span><span id='ups_outputv'></span><br>
</td><td></td></tr>
</tbody>
<?endif;?>
<?if ($fans):?>
<thead sort='<?=++$N?>'><tr class='hidden'><td></td><td colspan='3'></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='sortable'>
<tr><td></td><td colspan='3' class='next'><i class='icon-fan'></i><div class='section'>_(Airflow)_<br><span>_(Fan count)_: <?=$fans?></span><br><br></div>
<i class='fa fa-fw chevron' id='fan_view' onclick='toggleChevron("fan_view",0)'></i>
<?if ($autofan):?>
<a href='/Dashboard/Settings/FanSettings' title="_(Go to fan settings)_"><i class='fa fa-fw fa-cog chevron'></i></a>
<?endif;?>
</td><td></td></tr>
<?
$tr_fan = "<tr class='fan_view'><td></td>";
$tr_end = "<td></td></tr>";
$hdr = []; $row = []; $i = 0;
$hdr[0] = $row[0] = $tr_fan;
for ($fan=0; $fan<$fans; $fan++) {
  if ($fan && $fan%3==0) {
    $hdr[$i] .= $tr_end; $row[$i] .= $tr_end; $i++;
    $hdr[$i] = $row[$i] = $tr_fan;
  }
  $hdr[$i] .= "<td>"._('FAN')." $fan</td>";
  $row[$i] .= "<td id='fan$fan'></td>";
}
$rest = ($fans%3) ? 3-($fans%3) : 0;
for ($fan=0; $fan<$rest; $fan++) $hdr[$i] .= "<td></td>"; $row[$i] .= "<td></td>";
if ($rest) {$hdr[$i] .= $tr_end; $row[$i] .= $tr_end;}
for ($n=0; $n<=$i; $n++) echo $hdr[$n].$row[$n];
?>
</tbody>
<?endif;?>
</table>

<?$N=0?>
<table id='db-box3' class='share_status dashboard box3'>
<?if ($display['dashapps']!='none'):?>
<?if ($dockerd && ($display['dashapps']=='icons' || $display['dashapps']=='docker')):?>
<thead sort='<?=$N?>' class='sortable'><tr><td></td><td colspan='4' class='next'>_(Docker Containers)_<i class='fa fa-fw chevron mt0' id='docker_view' onclick='toggleChevron("docker_view",0)'></i>
<a href='/Dashboard/Settings/DockerSettings' title="_(Go to Docker settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<span class='info apps'><input type='checkbox' id='apps'></span></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='docker_view sortable'></tbody>
<?endif;?>
<?if ($libvirtd && ($display['dashapps']=='icons' || $display['dashapps']=='vms')):?>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='4' class='next'>_(Virtual Machines)_<i class='fa fa-fw chevron mt0' id='vm_view' onclick='toggleChevron("vm_view",0)'></i>
<a href='/Dashboard/Settings/VMSettings' title="_(Go to VM settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<span class='info vms'><input type='checkbox' id='vms'></span></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='vm_view sortable'></tbody>
<?endif;?>
<?endif;?>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='4' class='next'>_(Shares)_<i class='fa fa-fw chevron mt0' id='shares_view' onclick='toggleChevron("shares_view",4)'></i>
<a href='/Shares' title="_(Go to Share settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a><span class='info'><?=sprintf(_("Share count: %s with %s cache only and %s encrypted"),count($shares),$cache_only,$encrypted)?></span>
<?if ($group):?>
<select name="enter_share" onchange="changeMode(this.value)">
<?if ($var['shareSMBEnabled']=='yes'):?>
<?=mk_option("", "0", "SMB")?>
<?endif;?>
<?if ($var['shareNFSEnabled']=='yes'):?>
<?=mk_option("", "2", "NFS")?>
<?endif;?>
</select>
<?endif;?>
</td><td></td></tr>
<tr id='shares_view_on'><td></td><td>_(Name)_</td><td>_(Description)_</td><td>_(Security)_</td><td>_(Streams)_</td><td></td></tr>
</thead>
<?if ($var['shareSMBEnabled']=='yes'):?>
<tbody sort='<?=$N?>' class='smb share share1 sortable'><?
$i = 0;
foreach ($shares as $name => $share) {
  $i++;
  $list = "<a href=\"/Dashboard/Shares/Share?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  if ($share['luksStatus']>0) $list = str_replace('blue-text','green-text',$list);
  elseif ($share['useCache']=='only') $list = str_replace('blue-text','orange-text',$list);
  $comment = compress($share['comment'],40);
  $security = export_settings($var['shareSMBEnabled'], $sec[$name]);
  echo "<tr><td></td><td><i class='icon-folder'></i>$list</td><td>$comment</td><td>$security</td><td id='share{$i}'>0</td><td></td></tr>";
}
if (!count($shares)) echo "<tr><td></td><td colspan='4' class='none'>"._("No shares present")."</td><td></td></tr>";
?></tbody>
<?endif;?>
<?if ($var['shareNFSEnabled']=='yes'):?>
<tbody sort='<?=$N?>' class='nfs share share3 sortable'><?
foreach ($shares as $name => $share) {
  $list = "<a href=\"/Dashboard/Shares/Share?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  if ($share['luksStatus']>0) $list = str_replace('blue-text','green-text',$list);
  elseif ($share['useCache']=='only') $list = str_replace('blue-text','orange-text',$list);
  $comment = compress($share['comment'],40);
  $security = export_settings($var['shareNFSEnabled'], $sec_nfs[$name]);
  echo "<tr><td></td><td><i class='icon-folder'></i>$list</td><td>$comment</td><td>$security</td><td>-</td><td></td></tr>";
}
if (!count($shares)) echo "<tr><td></td><td colspan='4' class='none'>"._("No shares present")."</td><td></td></tr>";
?></tbody>
<?endif;?>
<?if (!$group):?>
<tbody sort='<?=$N?>' class='share sortable'><?
foreach ($shares as $name => $share) {
  $list = "<a href=\"/Dashboard/Shares/Share?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  if ($share['luksStatus']>0) $list = str_replace('blue-text','green-text',$list);
  elseif ($share['useCache']=='only') $list = str_replace('blue-text','orange-text',$list);
  $comment = compress($share['comment'],40);
  echo "<tr><td></td><td><i class='icon-folder'></i>$list</td><td>$comment</td><td>-</td><td>-</td><td></td></tr>";
}
if (!count($shares)) echo "<tr><td></td><td colspan='4' class='none'>"._("No shares present")."</td><td></td></tr>";
?></tbody>
<?endif;?>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='4' class='next'>_(Users)_<i class='fa fa-fw chevron mt0' id='users_view' onclick='toggleChevron("users_view",3)'></i>
<a href='/Users' title="_(Go to User settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a><span class='info'><?=sprintf(_("User count: %s with %s unprotected"),count($users),$nopass)?></span>
</td><td></td></tr><tr id='users_view_on'><td></td><td>_(Name)_</td><td>_(Description)_</td><td>_(Write)_</td><td>_(Read)_</td><td></td></tr></thead>
<?if ($var['shareSMBEnabled']=='yes'):?>
<tbody sort='<?=$N?>' class='smb user user1 sortable'><?
foreach ($users as $user) {
  $name = $user['name'];
  $list = "<a href=\"/Dashboard/Users/UserEdit?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  $desc = compress($user['desc'],40);
  if ($name=='root') {
    $write = '-'; $read = '-';
  } else {
    $write = 0; $read = 0;
    foreach ($shares as $share) {
      $access = $sec[$share['name']];
      if ($access['export']=='-') continue;
      switch ($access['security']) {
      case 'public':
        $write++;
        break;
      case 'secure':
        if (in_array($name,explode(',',$access['writeList']))) $write++; else $read++;
        break;
      case 'private':
        if (in_array($name,explode(',',$access['writeList']))) $write++;
        if (in_array($name,explode(',',$access['readList']))) $read++;
        break;
      }
    }
  }
  if ($user['passwd']!='yes') $list = str_replace('blue-text','orange-text',$list);
  echo "<tr><td></td><td><i class='icon-user'></i>$list</td><td>$desc</td><td>$write</td><td>$read</td><td></td></tr>";
}
?></tbody>
<?endif;?>
<?if ($var['shareNFSEnabled']=='yes'):?>
<tbody sort='<?=$N?>' class='nfs user user3 sortable'><?
foreach ($users as $user) {
  $name = $user['name'];
  $list = "<a href=\"/Dashboard/Users/UserEdit?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  $desc = compress($user['desc'],40);
  $write = '-'; $read = '-';
  if ($user['passwd']!='yes') $list = str_replace('blue-text','orange-text',$list);
  echo "<tr><td></td><td><i class='icon-user'></i>$list</td><td>$desc</td><td>$write</td><td>$read</td><td></td></tr>";
}
?></tbody>
<?endif;?>
<?if (!$group):?>
<tbody sort='<?=$N?>' class='user sortable'><?
foreach ($users as $user) {
  $name = $user['name'];
  $list = "<a href=\"/Dashboard/Users/UserEdit?name=".urlencode($name)."\" class=\"blue-text\" title=\"$name settings\">".compress($name,20)."</a>";
  $desc = compress($user['desc'],40);
  if ($user['passwd']!='yes') $list = str_replace('blue-text','orange-text',$list);
  echo "<tr><td></td><td><i class='icon-user'></i>$list</td><td>$desc</td><td>-</td><td>-</td><td></td></tr>";
}
?></tbody>
<?endif;?>
</table>

<?$N=0?>
<table id='db-box2' class='share_status dashboard box2'>
<thead sort='<?=$N?>' class='sortable'><tr><td></td><td colspan='5' class='next'>_(Parity)_<i class='fa fa-fw chevron mt0' id='parity_view' onclick='toggleChevron("parity_view",0)'></i>
<a href='/Dashboard/Settings/Scheduler' title="_(Go to scheduler settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<span class='info title'></span></td><td></td></tr></thead>
<tbody sort='<?=$N?>' class='parity_view sortable'>
<tr><td></td><td colspan='5' id='parity' class="wrap"></td><td></td></tr>
<tr><td></td><td colspan='5' id='program' class="wrap"></td><td></td></tr>
</tbody>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='5' class='next'>_(Array)_<?if (!$started):?> (_(stopped)_)<?endif;?><i class='fa fa-fw chevron mt0' id='array_view' onclick='toggleChevron("array_view",0)'></i>
<a href='/Dashboard/Settings/DiskSettings' title="_(Go to disk settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<?if ($started):?><span class='info'><?=sprintf(_("%s used of %s (%s %%)"),my_scale($array_used*1024,$unit)." $unit",my_scale($array_size*1024,$unit,-1,-1)." $unit",$array_percent)?></span><?endif;?>
</td><td></td></tr>
<tr class='my_view'><td></td><td id='array_info' colspan='5'></td><td></td></tr>
<tr id='array_view_on'><td></td><td>_(Device)_</td><td>_(Status)_</td><td>_(Temp)_</td><td>_(SMART)_</td><td>_(Utilization)_</td><td></td></tr>
</thead>
<tbody sort='<?=$N?>' class='array_view sortable' id='array_list'></tbody>
<?$i=0?>
<?foreach ($pools as $pool):?>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='5' class='next'><?=ucfirst($pool)?><?if (!$started):?> (_(stopped)_)<?endif;?><i class='fa fa-fw chevron mt0' id='_<?=$pool?>_view' onclick='toggleChevron("_<?=$pool?>_view",0)'></i>
<a href='/Dashboard/Settings/DiskSettings' title="_(Go to disk settings)_"><i class='fa fa-fw fa-cog chevron mt0'></i></a>
<?if ($started):?><span class='info'><?=sprintf(_("%s used of %s (%s %%)"),my_scale($cache_used[$pool]*1024,$unit)." $unit",my_scale($cache_size[$pool]*1024,$unit,-1,-1)." $unit",$cache_rate[$pool])?></span><?endif;?>
</td><td></td></tr>
<tr class='my_view'><td></td><td id='cache_info<?=$i?>' colspan='5'></td><td></td></tr>
<tr id='_<?=$pool?>_view_on'><td></td><td>_(Device)_</td><td>_(Status)_</td><td>_(Temp)_</td><td>_(SMART)_</td><td>_(Utilization)_</td><td></td></tr>
</thead>
<tbody sort='<?=$N?>' class='_<?=$pool?>_view sortable' id='cache_list<?=$i++?>'></tbody>
<?endforeach;?>
<?if ($devs):?>
<thead sort='<?=++$N?>' class='sortable'><tr><td></td><td colspan='5' class='next'>_(Unassigned)_<i class='fa fa-fw chevron mt0' id='extra_view' onclick='toggleChevron("extra_view",0)'></i><span class='info'></span></td><td></td></tr>
<tr class='my_view'><td></td><td id='extra_info' colspan='5'></td><td></td></tr>
<tr id='extra_view_on'><td></td><td>_(Device)_</td><td>_(Status)_</td><td>_(Temp)_</td><td>_(SMART)_</td><td>_(Utilization)_</td><td></td></tr>
</thead>
<tbody sort='<?=$N?>' class='extra_view sortable' id='extra_list'></tbody>
<?endif;?>
</table>
</div>
<form name='boot' method='POST' action='/webGui/include/Boot.php'>
<input type='hidden' name='csrf_token' value='<?=$var['csrf_token']?>'>
<input type='hidden' name='cmd' value=''>
</form>
<div id="iframe-popup"></div>
&nbsp;
<script>
Number.prototype.pad = function(size){var s=String(this);while(s.length<(size||2)){s='0'+s;}return s;}
Array.prototype.tail = function(t){return this.slice(-t).map(function(o){return o.y;}).join(';');}

var ports    = [<?=implode(',',array_map('escapestring',$ports))?>];
var cpu      = [];
var rxd      = [];
var txd      = [];
var cputime  = 0;
var nettime  = 0;
var cpuline  = $.cookie('cpuline')||30;
var netline  = $.cookie('netline')||30;
var update2  = true;

var options_cpu = {
  series:[{name:'load', data:cpu.slice()}],
  chart:{height:120, type:'line', fontFamily:'clear-sans', animations:{enabled:true, easing:'linear', dynamicAnimation:{speed:1000}}, toolbar:{show:false}, zoom:{enabled:false}},
  dataLabels:{enabled:false},
  tooltip:{enabled:false},
  stroke:{curve:'smooth', width:1},
  colors:['#ff8c2f'],
  markers:{size:0},
  xaxis:{type:'datetime', range:cpuline-1, labels:{show:false}, axisTicks:{show:false}, axisBorder:{show:false}},
  yaxis:{max:100, tickAmount:4, labels:{formatter:function(v,i){return v.toFixed(0)+' %';}, style:{colors:'<?=$color?>'}}, axisBorder:{show:false}, axisTicks:{show:false}},
  grid:{show:true, borderColor:'<?=$grid?>'},
  legend:{show:false}
};
var options_net = {
  series:[{name:'receive', data:rxd.slice()},{name:'transmit', data:txd.slice()}],
  chart:{height:120, type:'line', fontFamily:'clear-sans', animations:{enabled:true, easing:'linear', dynamicAnimation:{speed:1000}}, toolbar:{show:false}, zoom:{enabled:false}},
  dataLabels:{enabled:false},
  tooltip:{enabled:false},
  stroke:{curve:'smooth', width:1},
  colors:['#e22828','#ff8c2f'],
  markers:{size:0},
  xaxis:{type:'datetime', range:netline-1, labels:{show:false}, axisTicks:{show:false}, axisBorder:{show:false}},
  yaxis:{tickAmount:4, labels:{formatter:function(v,i){return autoscale(v,'bps',1);}, style:{colors:'<?=$color?>'}}, axisBorder:{show:false}, axisTicks:{show:false}},
  grid:{show:true, borderColor:'<?=$grid?>'},
  legend:{show:false}
};

var cpuchart = new ApexCharts(document.querySelector('#cpuchart'), options_cpu);
var netchart = new ApexCharts(document.querySelector('#netchart'), options_net);

if ($.cookie('port_select')!=null && !ports.includes($.cookie('port_select'))) $.removeCookie('port_select');
var port_select = $.cookie('port_select')||ports[0];

function initCharts(clear) {
  $.post('/webGui/include/InitCharts.php',{cmd:'get'},function(data) {
    data = JSON.parse(data);
    // initialize graphs entries
    var now = new Date().getTime();
    if (!clear) {
      var c = data.cpu.split(';');
      var r = data.rxd.split(';');
      var t = data.txd.split(';');
      for (var i=0; i < cpuline; i++) {
        var x = now + i;
        var y = c[i]||0; cpu.push({x,y});
      }
      cputime = x + 1;
    } else {
      // clear network graph
      var r = ''; var t = '';
      rxd = []; txd = [];
    }
    for (var i=0; i < netline; i++) {
      var x = now + i;
      var y = r[i]||0; rxd.push({x,y});
      var y = t[i]||0; txd.push({x,y});
    }
    nettime = x + 1;
  });
}
function resetCharts() {
  // prevent unlimited graph growing
  cpu = cpu.slice(-cpuline);
  rxd = rxd.slice(-netline);
  txd = txd.slice(-netline);
}
function addChartCpu(load) {
  cputime++;
  var i = cpu.length - cpuline;
  if (i > 0) { // clear value outside graph
    i = i - 1;
    cpu[i].x = cputime - cpuline;
    cpu[i].y = 0;
  }
  cpu.push({x:cputime, y:load});
}
function addChartNet(rx, tx) {
  nettime++;
  var i = rxd.length - netline;
  if (i > 0) { // clear value outside graph
    i = i - 1;
    rxd[i].x = nettime - netline;
    rxd[i].y = 0;
    txd[i].x = nettime - netline;
    txd[i].y = 0;
  }
  rxd.push({x:nettime, y:rx});
  txd.push({x:nettime, y:tx});
}
<?if ($wireguard):?>
function toggleVPN(id,vtun) {
  var up = $('#vpn-active');
  var down = $('#vpn-inactive');
  if (id.hasClass('inactive')) {
    $.post('/webGui/include/update.wireguard.php',{'#cmd':'toggle','#wg':'start','#vtun':vtun},function(on){if (on){
      id.removeClass('inactive');
      up.text(up.text()*1+1);
      if (down.text()>0) down.text(down.text()*1-1);
    }});
  } else {
    $.post('/webGui/include/update.wireguard.php',{'#cmd':'toggle','#wg':'stop','#vtun':vtun});
    id.addClass('inactive');
    down.text(down.text()*1+1);
    if (up.text()>0) up.text(up.text()*1-1);
    $('td[id^="'+vtun+'-hs"]').text('inactive');
    $('td[id^="'+vtun+'-rx"]').text('---');
  }
}
<?endif;?>
function noApps() {
  if ($('span.outer.apps:visible').length==0) $('#no_apps').show(); else $('#no_apps').hide();
}
function noVMs() {
  if ($('span.outer.vms:visible').length==0) $('#no_vms').show(); else $('#no_vms').hide();
}
function loadlist(init) {
  if (init) {
    $('#apps').switchButton({labels_placement:'left', off_label:"_(All Apps)_", on_label:"_(Started only)_", checked:$.cookie('my_apps')=='startedOnly'});
    $('#vms').switchButton({labels_placement:'left', off_label:"_(All VMs)_", on_label:"_(Started only)_", checked:$.cookie('my_vms')=='startedOnly'});
    $('#apps').change(function(){
      $('span.outer.apps.stopped').finish().toggle('fast',function(){noApps();})
      $('#apps').is(':checked') ? $.cookie('my_apps','startedOnly',{expires:3650}) : $.removeCookie('my_apps');
    });
    $('#vms').change(function(){
      $('span.outer.vms.stopped').finish().toggle('fast',function(){noVMs();});
      $('#vms').is(':checked') ? $.cookie('my_vms','startedOnly',{expires:3650}) : $.removeCookie('my_vms');
    });
    context.init({preventDoubleContext:false,left:true,above:false});
  }
  $.post('/webGui/include/DashboardApps.php',{display:'<?=$display['dashapps']?>',docker:'<?=$dockerd?>',vms:'<?=$libvirtd?>'},function(d) {
    var data = d.split(/\0/);
    $('.docker_view').html(data[0]);
    $('.vm_view').html(data[1]);
    if ($.cookie('my_apps')!=null) $('span.apps.stopped').hide(0,function(){noApps();});
    if ($.cookie('my_vms')!=null) $('span.vms.stopped').hide(0,function(){noVMs();});
    context.init({preventDoubleContext:false,left:true,above:false});
  });
}
function getCase() {
  $.post('/webGui/include/SelectCase.php',{mode:'get',file:'<?=$myfile?>'},function(model){
    if (!model) {
      $('#casing').html("<i id='mycase' class='fa fa-hdd-o'></i><br>");
    } else if (model.indexOf('.png')<0) {
      $('#casing').html("<i id='mycase' class='case-"+model+"'></i><br>");
    } else {
      var now = new Date();
      $('#casing').html("<img id='mycase' src='/webGui/images/"+model+"?v="+now.getTime()+"'><br>");
    }
  });
}
function changeMode(item) {
  var user = $.cookie('users_view');
  var share = $.cookie('shares_view');
  if (item==0) $.removeCookie('enter_share'); else $.cookie('enter_share',item,{expires:3650});
<?if ($var['shareSMBEnabled']=='yes'):?>
  if (item==0 && user==null) $('.smb.user1').show(); else $('.smb.user1').hide();
  if (item==0 && share==null) $('.smb.share1').show(); else $('.smb.share1').hide();
<?endif;?>
<?if ($var['shareNFSEnabled']=='yes'):?>
  if (item==2 && user==null) $('.nfs.user3').show(); else $('.nfs.user3').hide();
  if (item==2 && share==null) $('.nfs.share3').show(); else $('.nfs.share3').hide();
<?endif;?>
}
function changeView(item) {
  if (item==0) $.removeCookie('enter_view'); else $.cookie('enter_view',item,{expires:3650});
  if (item==0) $('.view1').show(); else $('.view1').hide();
  if (item==1) $('.view2').show(); else $('.view2').hide();
  if (item==2) $('.view3').show(); else $('.view3').hide();
  if (item==3) $('.view4').show(); else $('.view4').hide();
}
function changeCPUline(val) {
  cpuline = val;
  if (val==30) $.removeCookie('cpuline'); else $.cookie('cpuline',val,{expires:3650});
  cpuchart.updateOptions({xaxis:{range:cpuline-1}});
}
function changeNetline(val) {
  netline = val;
  if (val==30) $.removeCookie('netline'); else $.cookie('netline',val,{expires:3650});
  netchart.updateOptions({xaxis:{range:netline-1}});
}
function smartMenu(table) {
  $(table).find('[id^="smart-"]').each(function() {
    var opts = [];
    var id = '#'+$(this).attr('id');
    var page = $(this).attr('name');
    var view = $(this).attr('class');
    var disk = id.substr(id.indexOf('-')+1);
    opts.push({text:"_(Attributes)_",icon:'fa-sitemap',action:function(e){e.preventDefault();attributes(page,disk);}});
    opts.push({divider:true});
    opts.push({text:"_(Capabilities)_",icon:'fa-user',action:function(e){e.preventDefault();capabilities(page,disk);}});
    opts.push({divider:true});
    opts.push({text:"_(Identity)_",icon:'fa-home',action:function(e){e.preventDefault();identity(page,disk);}});
    if (view.search('green-text') == -1) {
      opts.push({divider:true});
      opts.push({text:"_(Acknowledge)_",icon:'fa-check-square-o',action:function(e){e.preventDefault();acknowledge(id,disk);}});
    }
    $(id).bind('click',function(){update2=false;}).bind('mouseout',function(){setTimeout(function(){update2=true;},15000);});
    context.attach(id,opts);
  });
}
function portMenu() {
  var select = 'select[name="port_select"]';
  var option = $(select+' option');
  for (var i=0; i < option.length; i++) {
    if (option[i].value == port_select) {option[i].selected = true; break;}
  }
}
function portSelect(name) {
  $.cookie('port_select',name,{expires:3650});
  initCharts(true);
  port_select = name;
}
function moreInfo(data,table) {
  var info = [];
  if (data[1]>0) info.push(data[1]+" _(failed device)_"+(data[1]==1?'':'s'));
  if (data[2]>0) info.push(data[2]+" _(heat warning)_"+(data[2]==1?'':'s'));
  if (data[3]>0) info.push(data[3]+" _(SMART error)_"+(data[3]==1?'':'s'));
  if (data[4]>0) info.push(data[4]+" _(utilization warning)_"+(data[4]==1?'':'s'));
  return info.length ? "<div class='last'><i class='icon-u-triangle failed'></i><span class='failed'>"+table+" _(has)_ "+info.join('. ')+".</span></div>" : "";
}
function autoscale(value,text,size,kilo) {
  if (kilo==null) kilo = 1000;
  var unit = kilo==1024 ? ['','ki','Mi','Gi','Ti','Pi','Ei'] :['','k','M','G','T','P','E'];
  var base = value>1?Math.floor(Math.log(value)/Math.log(kilo)):0;
  var data = base<unit.length?value/Math.pow(kilo, base):0;
  var scale = (data<100?100:10)/size;
  if (data==0) base=0;
  return ((Math.round(scale*data)/scale)+' '+unit[base]+text).replace(".","<?=$display['number'][0]?>");
}
function update900() {
  // prevent chart overflowing, reset every 15 minutes
  resetCharts();
  setTimeout(update900,900000);
}
function attributes(page,disk) {
  var tab = page=='New' ? 'tab2' : 'tab3';
  $.cookie('one',tab);
  location.replace('/Dashboard/'+page+'?name='+disk);
}
function capabilities(page,disk) {
  var tab = page=='New' ? 'tab3' : 'tab4';
  $.cookie('one',tab);
  location.replace('/Dashboard/'+page+'?name='+disk);
}
function identity(page,disk) {
  var tab = page=='New' ? 'tab4' : 'tab5';
  $.cookie('one',tab);
  location.replace('/Dashboard/'+page+'?name='+disk);
}
function acknowledge(id,disk) {
  $.post('/webGui/include/Acknowledge.php',{disk:disk},function(){$(id).removeClass('fa-thumbs-o-down orange-text').addClass('fa-thumbs-o-up green-text');$(id.replace('smart','text')).text("<?=_('healthy')?>");});
}
function dropdown(menu) {
  var select = 'select[name="'+menu+'"]';
  var size   = $(select+' option').length;
  var option = $.cookie(menu)||0;
  if (option >= size) option = size - 1;
  $(select+' option')[option].selected = true;
  $(select).change();
}
function toggleChevron(field,action) {
  switch (action) {
    case 0:
    case 1: var view = field; break;
    case 2: var view = $.cookie('enter_view')||0; view++; view = 'view'+view; break;
    case 3: var view = $.cookie('enter_share')||0; view++; view = 'user'+view; break;
    case 4: var view = $.cookie('enter_share')||0; view++; view = 'share'+view; break;
  }
  toggleView(field,false,view);
  var visible = $('.'+view).is(':visible');
  var chevron = visible ? 'fa-chevron-up' : 'fa-chevron-down';
  var remove  = visible ? 'fa-chevron-down' : 'fa-chevron-up';
  $('i#'+field).removeClass(remove).addClass(chevron);
  if (action==1) {
    if (visible) toggleCPU(true); else $('.cpu_open').hide();
  } else if (action==2) {
    $('.'+field).toggle();
  }
}
function toggleCPU(init) {
  if (!init) {if ($.cookie('cpu')===undefined) $.cookie('cpu','close',{expires:3650}); else $.removeCookie('cpu');}
  if ($.cookie('cpu_view')===undefined) {
    if ($.cookie('cpu')===undefined) {
      $('.cpu_open').show();
      $('.cpu_close').text("_(Hide details)_");
      toggleChart(true);
    } else {
      $('.cpu_open').hide();
      $('.cpu_close').text("_(Show details)_");
    }
  } else {
    $('.cpu_open').hide();
  }
}
function toggleChart(init) {
  if (!init) {if ($.cookie('cpu-chart')===undefined) $.cookie('cpu-chart','close',{expires:3650}); else $.removeCookie('cpu-chart');}
    if ($.cookie('cpu-chart')===undefined) {
      $('.cpu_chart').show();
      $('#cpuline').show();
    } else {
      $('.cpu_chart').hide();
      $('#cpuline').hide();
    }
}
function toggleView(field,init,view) {
  if (!view) view = $.cookie(field)||field;
  if (!init) {if ($.cookie(field)===undefined) $.cookie(field,view,{expires:3650}); else $.removeCookie(field);}
  var visible = $.cookie(field)===undefined;
  if (visible) $('.'+view).show().removeClass('flat'); else $('.'+view).hide().addClass('flat');
  var unset = true;
  switch (field) {
  case 'users_view':
    visible = $('.user').is(':visible');
    unset = false;
  case 'shares_view':
    if (unset) visible = $('.share').is(':visible');
  case 'array_view':
<?foreach ($pools as $pool):?>
  case '_<?=$pool?>_view':
<?endforeach;?>
  case 'extra_view':
    var on = $('#'+field+'_on');
    var off = $('#'+field+'_off');
    if (visible) {on.show(); off.hide();} else {off.show(); on.hide();}
    break;
  case 'docker_view':
    if (visible) $('span.info.apps').show(); else $('span.info.apps').hide();
    if (init) setTimeout(noApps,200); else noApps();
    break;
  case 'vm_view':
    if (visible) $('span.info.vms').show(); else $('span.info.vms').hide();
    if (init) setTimeout(noVMs,200); else noVMs();
    break;
  }
  if (init) {
    var chevron = visible ? 'fa-chevron-up' : 'fa-chevron-down';
    $('#'+field).addClass(chevron);
  }
}
function StopArray() {
<?if ($confirm['stop']):?>
  swal({title:"_(Proceed)_?",text:"_(This will stop the array)_",type:'warning',html:true,showCancelButton:true,confirmButtonText:"_(Proceed)_",cancelButtonText:"_(Cancel)_"},function(){StopArrayNow();});
<?else:?>
   StopArrayNow();
<?endif;?>
}
function StopArrayNow() {
  $('span.hand').prop('onclick',null).off('click').addClass('busy').css('cursor','default');
  $.post('/update.htm',{startState:'<?=$var['mdState']?>',cmdStop:'Stop',csrf_token:'<?=$var['csrf_token']?>'},function(){refresh();});
}
function StartArray() {
<?if ($confirm['stop']):?>
  swal({title:"_(Proceed)_?",text:"_(This will start the array)_",type:'warning',html:true,showCancelButton:true,confirmButtonText:"_(Proceed)_",cancelButtonText:"_(Cancel)_"},function(){StartArrayNow();});
<?else:?>
  StartArrayNow();
<?endif;?>
}
function StartArrayNow() {
  $('span.hand').prop('onclick',null).off('click').addClass('busy').css('cursor','default');
  $.post('/update.htm',{startState:'<?=$var['mdState']?>',cmdStart:'Start',csrf_token:'<?=$var['csrf_token']?>'},function(){refresh();});
}
function Reboot() {
<?if ($confirm['down']):?>
  swal({title:"_(Proceed)_?",text:"_(This will reboot the system)_",type:'warning',html:true,showCancelButton:true,confirmButtonText:"_(Proceed)_",cancelButtonText:"_(Cancel)_"},function(){RebootNow();});
<?else:?>
  RebootNow();
<?endif;?>
}
function RebootNow() {
  document.boot.cmd.value = 'reboot';
  document.boot.submit();
}
function Shutdown() {
<?if ($confirm['down']):?>
  swal({title:"_(Proceed)_?",text:"_(This will shutdown the system)_",type:'warning',html:true,showCancelButton:true,confirmButtonText:"_(Proceed)_",cancelButtonText:"_(Cancel)_"},function(){ShutdownNow();});
<?else:?>
  ShutdownNow();
<?endif;?>
}
function ShutdownNow() {
  document.boot.cmd.value = 'shutdown';
  document.boot.submit();
}
<?if ($sleep):?>
function Sleep() {
<?if ($confirm['sleep']):?>
  swal({title:"_(Proceed)_?",text:"_(This will put the system to sleep)_",type:'warning',html:true,showCancelButton:true,confirmButtonText:"_(Proceed)_",cancelButtonText:"_(Cancel)_"},function(){SleepNow();});
<?else:?>
  SleepNow();
<?endif;?>
}
function SleepNow() {
  $('#statusraid').append('&nbsp;&bullet;&nbsp;<span class="warning" style="font-weight:bold">System in sleep mode</span>');
  $.get('/plugins/dynamix.s3.sleep/include/SleepMode.php',function(){refresh();});
}
<?endif;?>
function sortTable(table,index) {
  if (!index) return;
  index = index.split(';');
  for (var i=0,n; n=index[i]; i++) {
    table.find('thead[sort="'+n+'"]').appendTo(table);
    table.find('tbody[sort="'+n+'"]').appendTo(table);
  }
}
function setColor(l, t1, t2) {
  switch (true) {
  case (t1 > 0 && l >= t1): return 'redbar';
  case (t2 > 0 && l >= t2): return 'orangebar';
  default: return '';}
}

var dashboard = new NchanSubscriber('/sub/cpuload,update1,update2,update3<?=$wireguard?",wireguard":""?>',{subscriber:'websocket'});
dashboard.on('message',function(msg,meta) {
  switch (meta.id.channel()) {
  case 0:
    var ini = parseINI(msg);
    // cpu load
    $.each(ini,function(k,v) {
      var load = v['host'];
      var color = setColor(load, 90, 70);
      if (k=='cpu') {
        addChartCpu(load);
        cpuchart.updateSeries([{data:cpu}]);
      }
      $('.'+k).text(load+'%');
      $('#'+k).finish().animate({width:load+'%'},{step:function(){$('#'+k).css('overflow','visible').removeClass().addClass(color);}});
    });
    break;
  case 1:
    var part = msg.split('\1');
    // memory & disk load
    $.each(part[0].split('\0'),function(k,v) {
      var load = v.slice(0,-1);
      var color = setColor(load, <?=$display['critical']?>, <?=$display['warning']?>);
      $('.sys'+k).text(v);
      $('#sys'+k).finish().animate({width:v},{step:function(){$('#sys'+k).css('overflow','visible').removeClass().addClass(color);}});
    });
<?if ($fans):?>
    // fans rpm
    $.each(part[1].split('\0'),function(k,v) {$('#fan'+k).html(v);});
<?endif;?>
<?if ($var['fsState']=='Started' && $group):?>
    // stream counters (smb only)
    var tag = $('.smb').is(':visible') ? 'smb' : $('.nfs').is(':visible') ? 'nfs' : '';
    if (tag == 'smb') $.each(part[2].split('\0'),function(k,v) {$('#share'+(k+1)).html(v);});
<?endif;?>
    break;
  case 2:
    if (!update2) break;
    var part = msg.split('\1');
    var data = part[0].split('\0');
    var info = moreInfo(data,"_(Array)_");
    // array devices
    $('#array_list').html(data[0]);
    $('#array_info').parent().css('display',info?'':'none');
    $('#array_info').html(info);
    smartMenu('#array_list');
    // pool devices
    var text = part[1].split('\r');
    for (var i=0,t; t=text[i]; i++) {
      var data = t.split('\0');
      var info = moreInfo(data,"_(Cache)_");
      $('#cache_list'+i).html(t);
      $('#cache_info'+i).parent().css('display',info?'':'none');
      $('#cache_info'+i).html(info);
      smartMenu('#cache_list'+i);
    }
<?if ($devs):?>
    // unassigned devices
    var data = part[2].split('\0');
    var info = moreInfo(data,"_(Unassigned)_");
    $('#extra_list').html(data[0]);
    $('#extra_info').parent().css('display',info?'':'none');
    $('#extra_info').html(info);
    smartMenu('#extra_list');
<?endif;?>
    // parity status
    $('span.info.title').html(part[3]);
    // parity schedule
    var data = part[4].split('\0');
    $('#parity').html(data[0]);
    $('#program').html(data[1]);
    break;
  case 3:
    var part = msg.split('\1');
    var ports = part[0].split('\n');
    // rx & tx speeds
    for (var i=0,port; port=ports[i]; i++) {
      var data = port.split('\0');
      if (data[0] == port_select) {
        $('#inbound').text(data[1]);
        $('#outbound').text(data[2]);
        addChartNet(data[3], data[4]);
        netchart.updateSeries([{data:rxd},{data:txd}]);
        break;
      }
    }
    // port counters
    $.each(part[1].split('\0'),function(k,v) {$('#main'+k).html(v);});
    $.each(part[2].split('\0'),function(k,v) {$('#port'+k).html(v);});
    $.each(part[3].split('\0'),function(k,v) {$('#link'+k).html(v);});
    break;
  case 4:
    // wireguard tunnels
    var n = {};
    var rows = msg.split('\0');
    for (var i=0,row; row=rows[i]; i++) {
      var info = row.split(';');
      var vtun = info[0];
      if (typeof n[vtun]=='undefined') n[vtun] = 0; else n[vtun]++;
      if (info[1] == 0) {
        $('td#'+vtun+'-hs-'+n[vtun]).text("_(not received)_");
      } else if (info[1] > 86400) {
        var d = parseInt(info[1]/86400);
        var s = d==1 ? " _(day)_" : " _(days)_";
        $('td#'+vtun+'-hs-'+n[vtun]).text(sprintf("_(%s ago)_",d+s));
      } else {
        var h = parseInt(info[1]/3600).pad();
        var m = parseInt(info[1]/60%60).pad();
        var s = parseInt(info[1]%60).pad();
        $('td#'+vtun+'-hs-'+n[vtun]).text(sprintf("_(%s ago)_",h+':'+m+':'+s));
      }
      $('td#'+vtun+'-rx-'+n[vtun]).html(info[2]+'&nbsp;<i class="fa fa-fw fa-arrow-down"></i><span class="tx">'+info[3]+'&nbsp;<i class="fa fa-fw fa-arrow-up"></i></span>');
    }
    break;
  }
});
<?if ($apcupsd):?>
var apcups = new NchanSubscriber('/sub/apcups',{subscriber:'websocket'});
apcups.on('message',function(data) {
  data = data.split(';');
  $('#ups_model').html(data[0]);
  $('#ups_status').html(data[1]);
  $('#ups_bcharge').html(data[2]);
  $('#ups_timeleft').html(data[3]);
  $('#ups_nompower').html(data[4]);
  $('#ups_loadpct').html(data[5]);
  $('#ups_outputv').html(data[6]);
});
<?endif;?>

var sortableHelper = function(e,ui){
  var width = [];
  var table = ui.parent();
  ui.find('tr:first').children().each(function(){width.push($(this).width());});
  if (ui.prop('nodeName').toLowerCase()=='tbody') {
    var sort = ui.attr('sort');
    var head = table.find('thead[sort="'+sort+'"]');
    if (head.find('tr:first').is(':visible')) ui = head.clone();
  }
  ui.find('tr:first').children().each(function(i){$(this).width(width[i]);});
  return ui;
};

$(function() {
  initCharts();
  cpuchart.render();
  netchart.render();
  $('table').sortable({helper:sortableHelper,items:'.sortable',handle:'.section,.next',cursor:'move',axis:'y',containment:'parent',delay:100,opacity:0.5,zIndex:9999,
  update:function(e,ui){
    var table = ui.item.parent();
    var index = [], prev = -1;
    if (ui.item.prop('nodeName').toLowerCase()=='tbody') {
      table.find('tbody').each(function(){
        var sort = $(this).attr('sort');
        var head = table.find('thead[sort="'+sort+'"]');
        if (sort != prev) {
          head.remove().insertBefore($(this));
          index.push(sort);
          prev = sort;
        } else {
          $(this).remove().insertAfter(head);
        }
      });
    } else {
      table.find('thead').each(function(){
        var sort = $(this).attr('sort');
        var body = table.find('tbody[sort="'+sort+'"]');
        body.remove().insertAfter($(this));
        index.push(sort);
      });
    }
    var sorted = true;
    for (var x = 0; x < index.length-1; x++) {
      if (index[x+1]-index[x]!=1) {sorted=false; break;}
    }
    sorted ? $.removeCookie(table.prop('id')) : $.cookie(table.prop('id'),index.join(';'),{expires:3650});
  }});
<?if ($group):?>
  dropdown('enter_share');
<?endif;?>
  dropdown('enter_view');
  dashboard.start();
<?if ($apcupsd):?>
  apcups.start();
<?endif;?>
  update900();
  toggleChart(true);
  toggleCPU(true);
  toggleView('sys_view',true);
  toggleView('mb_view',true);
  toggleView('cpu_view',true);
  toggleView('mem_view',true);
  toggleView('port_view',true);
<?if ($wireguard):?>
  toggleView('vpn_view',true);
<?endif;?>
<?if ($fans):?>
  toggleView('fan_view',true);
<?endif;?>
<?if ($apcupsd):?>
  toggleView('ups_view',true);
<?endif;?>
<?if ($dockerd && ($display['dashapps']=='icons' || $display['dashapps']=='docker')):?>
  toggleView('docker_view',true);
<?endif;?>
<?if ($libvirtd && ($display['dashapps']=='icons' || $display['dashapps']=='vms')):?>
  toggleView('vm_view',true);
<?endif;?>
  toggleView('parity_view',true);
  toggleView('array_view',true);
<?foreach ($pools as $pool):?>
  toggleView('_<?=$pool?>_view',true);
<?endforeach;?>
<?if ($devs):?>
  toggleView('extra_view',true);
<?endif;?>
  toggleView('users_view',true);
  toggleView('shares_view',true);
  portMenu();
  loadlist(true);
  sortTable($('#db-box1'),$.cookie('db-box1'));
  sortTable($('#db-box2'),$.cookie('db-box2'));
  sortTable($('#db-box3'),$.cookie('db-box3'));
  $('#cpuline').val(cpuline);
  $('#netline').val(netline);
  // remember latest graph values
  $(window).on('beforeunload',function(e){
    var data = {};
    data.cpu = cpu.tail(cpuline);
    data.rxd = rxd.tail(netline);
    data.txd = txd.tail(netline);
    $.post('/webGui/include/InitCharts.php',{cmd:'set',data:JSON.stringify(data)});
  });
});
</script>
