<?PHP
/* Copyright 2010, Lime Technology LLC.
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 */
/* Modifications made to GUI, Copyright 2012, Andrew Hamer-Adams. */
/* Adapted by Bergware International (May 2012) */
?>
<?
// Helper functions
function my_scale($value, &$units, $precision = NULL) {
  global $display;
  $scale = $display['scale'];
  $number = isset($display['number']) ? $display['number'] : '.,';
  $dot = substr($number,0,1);
  $comma = substr($number,1,1);
  $unit = array('B','KB','MB','GB','TB','PB');
  if ($scale==0 && !$precision) {
    $units = '';
    return number_format($value, 0, $dot, $comma);
  } else {
    $base = $value ? floor(log($value, 1000)) : 0;
    if ($scale>0 && $base>$scale) $base = $scale;
    $units = $unit[$base];
    $value = round($value/pow(1000, $base), $precision ? $precision : 2);
    return number_format($value, $precision ? $precision : (($value-intval($value)==0 || $value>=100) ? 0 : ($value>=10 ? 1 : 2)), $dot, ($value>=10000 ? $comma : ''));
  }
}
function my_number($value) {
  global $display;
  $number = isset($display['number']) ? $display['number'] : '.,';
  $dot = substr($number,0,1);
  $comma = substr($number,1,1);
  return number_format($value, 0, $dot, ($value>=10000 ? $comma : ''));
}
function my_time($time, $fmt = NULL) {
  global $display;
  if (!$fmt) $fmt = $display['date'].($display['date']!='%c' ? ", {$display['time']}" : " %Z");
  return $time ? strftime($fmt, $time) : "unset";
}
function my_temp($value) {
  global $display;
  $unit = $display['unit'];
  $dot = isset($display['number']) ? substr($display['number'],0,1) : '.';
  return is_numeric($value) ? (($unit=='C' ? str_replace('.', $dot, $value) : round(9/5*$value+32))." &deg;{$unit}") : $value;
}
function mk_option($select, $value, $text, $extra = "") {
  return "<option value='{$value}'".($value==$select ? " selected" : "").(strlen($extra) ? " {$extra}" : "").">{$text}</option>";
}
function mk_option_check($name, $value, $text = "") {
  if ($text) {
    $checked = strpos($name, $value)===false ? "" : " selected";
    return "<option value='{$value}'{$checked}>$text</option>";
  }
  if (strpos($name, 'disk')!==false) {
    $checked = strpos($value.',', $name.',')===false ? "" : " selected";
    return "<option value='{$name}'{$checked}>".my_disk($name)."</option>";
  }
}
function my_disk($name) {
  return ucfirst(preg_replace('/^(disk)/','${1} ',$name));
}
function my_word($num) {
  $words = array('zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty');
  return $num<=count($words) ? $words[$num] : $num;
}
function my_count($num) {
  return "Array of ".my_word($num)." protected disk".($num!=1 ? 's' : '');
}
function day_count($time) {
  global $var;
  $days = floor($var['currTime']/86400)-floor($time/86400);
  switch (true) {
  case ($days<0):
    return "";
  case ($days==0):
    return " (today)";
  case ($days==1):
    return " (yesterday)";
  case ($days<=31):
    return " (".my_word($days)." days ago)";
  case ($days<=61):
    return " <span class='orange-text'>({$days} days ago)</span>";
  case ($days>61):
    return " <span class='red-text'>({$days} days ago)</span>";
  }
}
function plus($val, $word, $last = false) {
  return ($val || $last) ? ($val.' '.$word.($val!=1 ? 's' : '').($last ? '' : ', ')) : '';
}
function my_check($time) {
  global $disks;
  $days = floor($time/86400);
  $time -= $days*86400;
  $hour = floor($time/3600);
  $mins = $time/60%60;
  $secs = $time%60;
  return plus($days, 'day').plus($hour, 'hour').plus($mins, 'minute').plus($secs, 'second', true).". Average speed: ".my_scale($disks['parity']['size']*1024/$time,$unit,1)." $unit/sec";
}
function end_time($time) {
  $days = floor($time/1440);
  $time -= $days*1440;
  $hour = floor($time/60);
  $mins = $time%60;
  return plus($days, 'day').plus($hour, 'hour').plus($mins, 'minute', true);
}
function my_key() {
  $keyfile = exec("find /boot/config -name '*.key'");
  return strlen($keyfile) ? my_time(filemtime($keyfile)) : "";
}
function help_link($text, $link = "") {
  global $sf, $page;
  $file = "$sf/icons/".strtolower(str_replace(' ','_',$text)).".png";
  if (!is_file("/usr/local/emhttp{$file}")) $file = "$sf/icons/default.png";
  if ($link=="") $link = $text;
  $href = "javascript:openHelp(\"{$page['Plugin']}/{$link}\");";
  return "<a href='{$href}'><img src='{$file}' class='icon'>".my_disk($text)."</a>";
}
function title_link() {
  global $page;
  $link = array_key_exists('Help', $page) ? $page['Help'] : $page['Title'];
  return help_link($page['Title'], $link);
}
function urlencode_path($path) {
  return str_replace("%2F", "/", urlencode($path));
}
// Return sorted set of pages on the indicated menu.
function find_pages($menu) {
  global $page_array;
  $pages = array();
  foreach ($page_array as $page) {
    $tok = strtok($page['Menu'], " ");
    while ($tok!==false) {
      $delim = strpos($tok, ":");
      if ($delim) {
        $t = substr($tok, 0, $delim);
        if ($t==$menu) {
          $key = substr($tok, $delim + 1).$page['Name'];
          $pages[$key] = $page;
          break;
        }
      } else {
        if ($tok==$menu) {
          $pages[$page['Name']] = $page;
          break;
        }
      }
      $tok = strtok(" ");
    }
  }
  ksort($pages);
  return $pages;
}
// Suppose we want to render the page "http://tower/Main/Disk?name=disk1"
// emhttp calls 'popen(cmdline)' where cmdline is:

// "cd /usr/local/emhttp; /usr/bin/php /plugins/webGui/template.php name=disk1&path=Main/Disk"
//                                     argv[0]                      argv[1]

// The output of popen() (i.e., the output generated by template.php) is written to
// the http socket (after http headers have been output).

// Here's the document root of the webGui plugin
$root = '/'.dirname($argv[0]);

// SF plugin references
$sf = '/plugins/simpleFeatures';
$sn = '/plugins/notifications';

// Parse the 'querystring'
// variables provided by emhttp:
//   path=<path>   page path, e.g., path=Main/Disk
//   prev=<path>   prev path, e.g., prev=Main (used to determine if page was refreshed)
parse_str($argv[1]);

// The current "task" is the first element of the path
$task = strtok($path, "/");
$page = null;

// Read emhttp status
$var     = parse_ini_file("/var/local/emhttp/var.ini");
$sec     = parse_ini_file("/var/local/emhttp/sec.ini", TRUE);
$devs    = parse_ini_file("/var/local/emhttp/devs.ini", TRUE);
$disks   = parse_ini_file("/var/local/emhttp/disks.ini", TRUE);
$users   = parse_ini_file("/var/local/emhttp/users.ini", TRUE);
$shares  = parse_ini_file("/var/local/emhttp/shares.ini", TRUE);
$sec_nfs = parse_ini_file("/var/local/emhttp/sec_nfs.ini", TRUE);
$sec_afp = parse_ini_file("/var/local/emhttp/sec_afp.ini", TRUE);

// Bergware additions
$sf_ini = parse_ini_file("/var/local/emhttp/simpleFeatures.ini", TRUE);
$confirm = &$sf_ini['confirm'];
$display = &$sf_ini['display'];

// Set default time zone for PHP scripts
date_default_timezone_set($var['timeZone']);

// Build the pages
$page_array = array();
foreach (glob("plugins/*/*.page", GLOB_NOSORT) as $entry) {
  $page           = parse_ini_file($entry);
  $page['Name']   = basename($entry, ".page");
  $page['Root']   = dirname($entry);
  $page['Plugin'] = basename($page['Root']);

// assign defaults
  if (!isset($page['Author']))
    $page['Author'] = "anonymous";
  if (!isset($page['Version']))
    $page['Version'] = "unknown";
  if (!isset($page['Title']))
    $page['Title'] = $page['Name'];
  if (!isset($page['Type']))
    $page['Type'] = "echo 'Not much here.'";
  if (!isset($page['Icon']))
    $page['Icon'] = "$root/images/default.png";
  else
    $page['Icon'] = "{$page['Root']}/{$page['Icon']}";
  if (!isset($page['Menu']))
    $page['Menu'] = "";

// handle conditional inclusion on menus
  if (isset($page['Cond'])) {
    $cond = &$page['Cond'];
    eval("\$enabled=$cond;");
    if (!$enabled) $page['Menu'] = "";
  }

// add to page_array
  $page_array[$page['Name']] = $page;
}
// Here's the page we're rendering
  $myPage = $page_array[basename($path)];

// Gittyup
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title><?=$var['NAME']?>/<?=$myPage['Name']?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?if ($display['refresh']):?>
<meta http-equiv="Refresh" content="<?=$display['refresh']?>">
<?endif;?>
<link type="image/gif" rel="shortcut icon" href="<?=$root?>/style/<?=$var['mdColor']?>.gif">
<link type="text/css" rel="stylesheet" href="<?=$root?>/style/template.css">
<link type="text/css" rel="stylesheet" href="<?=$sf?>/style/jquery.jgrowl.css">
<link type="text/css" rel="stylesheet" href="<?=$sf?>/style/ui.dropdown.checklist.css">
<link type="text/css" rel="stylesheet" href="<?=$sf?>/style/shadowbox.css">

<?if (!$display['icons']):?>
<style>#title img.icon {display: none;}</style>
<?endif;?>

<script type="text/javascript" src="<?=$sf?>/scripts/jquery.js"></script>
<script type="text/javascript" src="<?=$sf?>/scripts/jquery.jgrowl.js"></script>
<script type="text/javascript" src="<?=$sf?>/scripts/jquery.ui.custom.js"></script>
<script type="text/javascript" src="<?=$sf?>/scripts/ui.dropdown.checklist.js"></script>
<script type="text/javascript" src="<?=$sf?>/scripts/shadowbox.js"></script>
<?if ($display['banner'] && $display['snow']):?>
<script type="text/javascript" src="<?=$sf?>/scripts/snowstorm.js"></script>
<script>
snowStorm.targetElement = 'header';
snowStorm.flakeBottom = 92;
snowStorm.vMaxX = 2;
snowStorm.vMaxY = 1;
snowStorm.show();
<?else:?>
<script>
<?endif;?>

Shadowbox.init({
  handleOversize: "resize",
  displayNav: true,
  onClose: function() { enableInput() }
});

// server uptime & update period
var uptime = <?=strtok(exec("cat /proc/uptime"),' ')?>;
var period = 1; //seconds

function add(value, label, last) {
  return parseInt(value)+' '+label+(parseInt(value)!=1?'s':'')+(!last?', ':'');
}
function updateTime() {
  document.getElementById('uptime').innerHTML = add(uptime/86400,'day')+add(uptime/3600%24,'hour')+add(uptime/60%60,'minute',true);
  uptime += period;
  setTimeout('updateTime()', period*1000);
}
function disableInput() {
  for (var i=0,input; input=top.document.getElementsByTagName('input')[i]; i++) { input.disabled = true; }
  for (var i=0,button; button=top.document.getElementsByTagName('button')[i]; i++) { button.disabled = true; }
  for (var i=0,select; select=top.document.getElementsByTagName('select')[i]; i++) { select.disabled = true; }
  for (var i=0,link; link=top.document.getElementsByTagName('a')[i]; i++) { link.style.color = "gray"; } //fake disable
}
function enableInput() {
  for (var i=0,input; input=top.document.getElementsByTagName('input')[i]; i++) { input.disabled = false; }
  for (var i=0,button; button=top.document.getElementsByTagName('button')[i]; i++) { button.disabled = false; }
  for (var i=0,select; select=top.document.getElementsByTagName('select')[i]; i++) { select.disabled = false; }
  for (var i=0,link; link=top.document.getElementsByTagName('a')[i]; i++) { link.style.color = "#3B5998"; } 
  for (var i=0,link; link=top.document.getElementById("menu").getElementsByTagName('a')[i]; i++) { link.style.color = "#FFFFFF"; } 
  for (var i=0,link; link=top.document.getElementById("header").getElementsByTagName('a')[i]; i++) { link.style.color = "#6FA239"; } 
  for (var i=0,link; link=top.document.getElementById("title").getElementsByTagName('a')[i]; i++) { link.style.color = "#333333"; } 
}
function refresh() {
  disableInput();
  window.location = window.location;
}
function done() {
  var path = window.location.pathname;
  var x = path.indexOf("/",1);
  if (x!=-1) path = path.substring(0,x);
  window.location.replace(path);
}
function chkDelete(form, button) {
  button.value = form.confirmDelete.checked ? 'Delete' : 'Apply';
}
function openWindow(url, name) {
  var width=((screen.width*2)/3)||0;
  var height=((screen.height*2)/3)||0;
  var features="resizeable=yes,scrollbars=yes,width=" + width + ",height=" + height;
  var myWindow=window.open(url, name, features);
  myWindow.focus();
  return myWindow;
}
function openHelp(topic) {
  var url="http://lime-technology.com/wiki/index.php?title=Plugin/" + topic.replace(/ /g, "_");
  openWindow(url, "unRaidHelp");
}
function openLog(title) {
  Shadowbox.close();
  var url="/update.htm?cmd=/usr/bin/tail -f /var/log/syslog&forkCmd=Start";
  var myWindow=openWindow(url, "unRaidLog");
  myWindow.document.title = title;
  return myWindow;
}
$(document).ready(function() {
  updateTime();
  $('#openlog').click(function() { $('#sb-wrapper').prepend('<a id="sb-nav-newclose" onClick="openLog(\'<?=$var['NAME']?> System Log\');" title="New Window"></a>'); });
  $('#openinfo').click(function(){ $('#sb-nav-newclose').hide(); });
  $.jGrowl.defaults.closer = false;
  $.ajax( {
    type: "POST", url: "<?=$sn?>/notify.php", data: {cmd: "get"}, success: function(result) {
      if (result) {
        var json = $.parseJSON(result);
        $.each(json, function(i, object) {
          var notification = $.parseJSON(object);
          $.jGrowl(notification.subject+'<br>'+notification.description, {
            sticky: true,
            position: "<?=$sf_ini['notify']['position'];?>",
            header: notification.plugin+': '+notification.timestamp,
            theme: notification.importance+' '+notification.file,
            close: function(e,m,o) {$.post("<?=$sn?>/notify.php", {cmd: "archive", file: notification.file});}
          });
        });
      }
    }, error: function(){}
  });
  var json = "";
  var refreshId = setInterval(function() {
  $.ajax( {
   type: "POST", url: "<?=$sn?>/notify.php", data: {cmd: "get"}, success: function(result) {
     if (result) {
       var json = $.parseJSON(result);
       $.each(json, function(i, object) {
         var notification = $.parseJSON(object);
         $.jGrowl(notification.subject+'<br>'+notification.description, {
           sticky: true,
           position: "<?=$sf_ini['notify']['position'];?>",
           header: notification.plugin+': '+notification.timestamp,
           theme: notification.importance+' '+notification.file,
           beforeOpen: function(e,m,o) {if ($('.jGrowl-notification').hasClass(notification.file)) { return(false);}},
           close: function(e,m,o) {$.post("<?=$sn?>/notify.php", { cmd: "archive", file: notification.file});}
         });
       });
     }
   }, error: function(){}
  });
  }, 5000);
});

var mobiles=['ipad','iphone','ipod','android'];
var device=navigator.platform.toLowerCase();
for (var i=0,mobile; mobile=mobiles[i]; i++){
  if (device.indexOf(mobile)>=0) { $('.footer').css('position', 'static'); break; }
}
</script>
</head>
<body>
  <div id="template">
   <div id="header" class="<?=$display['banner']?>">
    <div class="logo">
     <a href="http://lime-technology.com"><img src="<?=$root?>/images/logo.png" title="unRAID" border="0"/><br/>
     <strong>unRAID Server <?=$var['regTy']?></strong></a>
    </div>
    <div class="block"><span class="text-left"><strong>
     Server<br/>
     Description<br/>
     Version<br/>
     Uptime
     </strong></span>
     <span class="text-right">
     <?=$var['NAME'].' -- '.$var['IPADDR']?><br/>
     <?=$var['COMMENT']?><br/>
     <?=$var['version']?><br/>
     <div id="uptime"></div>
     </span>
    </div>
   </div>
   <div id="menu">
    <div id="nav_block">
     <div id="nav_left">
<?    $pages = find_pages("Tasks");
      foreach ($pages as $page):
        $link = "/{$page['Name']}";
        if ($page['Name']==$task):
?>        <div id="nav_item" class="active"><a href="<?=$link?>"><?=$page['Name']?></a></div>
<?      else:?>
          <div id="nav_item"><a href="<?=$link?>"><?=$page['Name']?></a></div>
<?      endif;
      endforeach;
?>   </div>
     <div id="nav_right">
      <div id="nav_item"><a href="/update.htm?cmd=/usr/bin/tail%20-n%2040%20-f%20/var/log/syslog&forkCmd=Start" title="<?=ucfirst($var['NAME'])?> System Log" rel="shadowbox;height=600;width=800;" id="openlog"><img src="<?=$sf?>/icons/page_white_text.png" class="system"/>Log</a></div>
      <div id="nav_item"><a href="<?=$sf?>/SystemInformation.php" rel="shadowbox;height=380;width=350" id="openinfo" title="System Information"><img src="<?=$sf?>/icons/monitor.png" class="system"/>Info</a></div>
     </div>
    </div>
   </div>
<? if ($myPage['Type']=="xmenu"):
     $pages = find_pages($myPage['Name']);
   else:
     $pages = array();
     $pages[$myPage['Name']] = $myPage;
   endif;
   foreach ($pages as $page):
     eval("\$page['Title']=\"$page[Title]\";");
?>   <div id="title"><span class="left"><?=title_link()?></span></div>
<?   if ($page['Type']=="menu"):
       $pgs = find_pages($page['Name']);
       foreach ($pgs as $pg):
         $link = "{$path}/{$pg['Name']}";
?>       <div class="Panel">
          <a href="<?=$link?>"><img class="PanelImg" src="<?=$pg['Icon']?>" title="<?=$pg['Title']?>" alt="<?=$pg['Title']?>"/><br/>
          <div class="PanelText"><?=$pg['Title']?></div></a>
         </div>
<?     endforeach;
     elseif ($page['Type']=="php"):
       include "{$page['Root']}/{$page['Name']}.php";
     else:
       passthru($page['Type']);
     endif;
   endforeach;
?> <br/>
  </div>
  <iframe id="progressFrame" name="progressFrame" frameborder="0"></iframe>
<?if ($confirm['warn']):?>
<script>
$(document).ready(function() {
  $('form').each(function(){$(this).change(function() {
    $.jGrowl("You have uncommitted form changes", {sticky: false, theme: "bottom", position: "bottom", life: 10000});});
  });
});
</script>
<?endif;?>
  <div id="footer">
<? if ($var['fsState']=="Started") { echo '<span class="green"><strong>Array Started</strong></span>'; }
   if ($var['fsState']=="Stopped") { echo '<span class="red"><strong>Array Stopped</strong></span>'; }
   if ($var['mdResync']!=0) {
     echo '|<span class="orange"><strong>';
     if ($var['mdNumInvalid']==0) {
       echo 'Parity-Check:';
     } else {
       if ($var['mdInvalidDisk']==0) {
         echo 'Parity-Sync:';
       } else {
         echo 'Data-Rebuild:';
       }
     }
     echo ' '.round(($var['mdResyncPos']/($var['mdResync']/100+1)), 1).' %';
     echo '</strong></span>';
   }
?> <div id="copyright">Author: <?=$myPage['Author']?>. Version: <?=$myPage['Version']?>.&nbsp;&nbsp;unRAID&#8482; webGui &copy; 2010-2011 Lime Technology LLC</div>
  </div>
</body>
</html>