allow setting a base path for RRDs and use it
[php-utility-classes.git] / include / classes / rrdstat.php-class
index 3d7b84d11e5ec510a644756dca435ab89aa5b66a..5e8cc6659c92b68f849e72bd2800c0a39b554ebf 100644 (file)
@@ -1,9 +1,140 @@
 <?php
-// ************ RRD status class **************
+/* ***** BEGIN LICENSE BLOCK *****
+ *
+ * The contents of this file are subject to Austrian copyright reegulations
+ * ("Urheberrecht"); you may not use this file except in compliance with
+ * those laws.
+ * This contents and any derived work, if it gets distributed in any way,
+ * is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
+ * either express or implied.
+ *
+ * The Original Code is KaiRo's RRD statistics class.
+ *
+ * The Initial Developer of the Original Code is
+ * KaiRo - Robert Kaiser.
+ * Portions created by the Initial Developer are Copyright (C) 2005
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Robert Kaiser <kairo@kairo.at>
+ *
+ * ***** END LICENSE BLOCK ***** */
+
 class rrdstat {
+  // rrdstat PHP class
+  // rrdtool statistics functions
+  //
+  // function rrdstat($rrdconfig, [$conf_id])
+  //   CONSTRUCTOR
+  //     if $conf_id is set, $rrdconfig is a total configuration set
+  //     else it's the configuration for this one RRD
+  //     currently only a config array is supported, XML config is planned
+  //
+  // var $rrd_file
+  // RRD file name
+  //
+  // var $basename
+  // base name for this RRD (usually file name without .rrd)
+  //
+  // var $basedir
+  // base directory for this RRD (with a trailing slash)
+  //   note that $rrd_file usually includes that path as well, but graph directory gets based on this value
+  //
+  // var $config_all
+  // complete, raw configuration array set
+  //
+  // var $config_raw
+  // configuration array set for current RRD
+  //
+  // var $config_graph
+  // configuration array set for default graph in this RRD
+  //
+  // var $config_page
+  // configuration array set for default page in this RRD
+  //
+  // var $rrd_fields
+  // definition of this RRD's fields
+  //
+  // var $rra_base
+  // definition of this RRD's base RRAs
+  //
+  // var $rrd_step
+  // basic stepping of this RRD in seconds (default: 300)
+  //
+  // var $rra_add_max
+  // should RRAs for MAX be added for every base RRA? (bool, default: true)
+  //
+  // var $status
+  // status of the RRD (unused/ok/readonly/graphonly)
+  //   note that most functions require certain status values
+  //   (e.g. update only works if status is ok, graph for ok/readonly/graphonly)
+  //
+  // function set_def($rrdconfig, [$conf_id])
+  //   set definitions based on given configuration
+  //   [intended for internal use, called by the constructor]
+  //
+  // function create()
+  //   create RRD file according to set config
+  //
+  // function update([$upArray])
+  //   feed new data into RRD (either use given array of values or use auto-update info from config)
+  //
+  // function fetch([$cf] = 'AVERAGE', $resolution = null, $start = null, $end = null)
+  //   fetch data from the defined RRD
+  //     using given consolidation function [default is AVERAGE],
+  //     resolution (seconds, default is the RRD's stepping),
+  //     start and end times (unix epoch, defaults are the RRD's last update time)
+  //
+  // function last_update()
+  //   fetch time of last update in this RRD file
+  //
+  // function graph([$timeframe], [$sub], [$extra])
+  //   create a RRD graph (and return all meta info in a flat string)
+  //     for given timeframe (day [default]/week/month/year),
+  //     sub-graph ID (if given) and extra config options (if given)
+  //
+  // function graph_plus([$timeframe], [$sub], [$extra])
+  //   create a RRD graph (see above) and return meta info as a ready-to-use array
+  //
+  // function page([$sub], [$page_extras], [$graph_extras])
+  //   create a (HTML) page and return it in a string
+  //     for given sub-page ID (if given, default is a simple HTML page)
+  //     and extra page and graph config options (if given)
+  //
+  // function simple_html([$sub], [$page_extras], [$graph_extras])
+  //   create a simple (MRTG-like) HTML page and return it in a string
+  //   XXX: this is here temporarily for compat only, it's preferred to use page()!
+  //
+  // function page_index($pconf)
+  //   create a bare, very simple index list HTML page and return it in a string
+  //   using given page config options
+  //   [intended for internal use, called by page()]
+  //
+  // function page_overview($pconf, [$graph_extras])
+  //   create an overview HTML page (including graphs) and return it in a string
+  //   using given page config options and extra graph options (if given)
+  //   [intended for internal use, called by page()]
+  //
+  // function page_simple($pconf, [$graph_extras])
+  //   create a simple (MRTG-like) HTML page and return it in a string
+  //   using given page config options and extra graph options (if given)
+  //   [intended for internal use, called by page()]
+  //
+  // function h_page_statsArray($pconf)
+  //   return array of stats to list on a page, using given page config options
+  //   [intended for internal use, called by page_*()]
+  //
+  // function h_page_footer()
+  //   return generic page footer
+  //   [intended for internal use, called by page_*()]
+  //
+  // function text_quote($text)
+  //   return a quoted/escaped text for use in rrdtool commandline text fields
 
   var $rrd_file = null;
+  var $basename = null;
+  var $basedir = null;
 
+  var $config_all = null;
   var $config_raw = null;
   var $config_graph = null;
   var $config_page = null;
@@ -19,10 +150,10 @@ class rrdstat {
     // ***** init RRD stat module *****
     $this->set_def($rrdconfig, $conf_id);
 
-    if (!is_null($this->rrd_file)) {
+    if (($this->status == 'unused') && !is_null($this->rrd_file)) {
       if (!is_writeable($this->rrd_file)) {
         if (!file_exists($this->rrd_file)) {
-          if (touch($this->rrd_file)) { $this->create(); }
+          if (@touch($this->rrd_file)) { $this->create(); }
           else { trigger_error('RRD file can not be created', E_USER_WARNING); }
         }
         else {
@@ -58,51 +189,71 @@ class rrdstat {
       $iinfo = $complete_conf;
     }
 
-    if (!isset($iinfo['file'])) { return false; }
-
-    $this->rrd_file = $iinfo['file'];
+    if (isset($iinfo['path']) && strlen($iinfo['path'])) {
+      $this->basedir = $iinfo['path'];
+      if (substr($this->basedir, -1) != '/') { $this->basedir .= '/'; }
+    }
 
-    // fields (data sources, DS)
-    //  name - DS name
-    //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
-    //  heartbeat - if no sample recieved for that time, store UNKNOWN
-    //  min - U (unconstrained) or minimum value
-    //  max - U (unconstrained) or maximum value
-    //  update - this string will be fed into eval() for updating this field
-    if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
-      $this->rrd_fields = $iinfo['fields'];
+    if (isset($iinfo['graph-only']) && $iinfo['graph-only'] && !is_null($conf_id)) {
+      $this->basename = $conf_id;
+      $this->status = 'graphonly';
+    }
+    elseif (isset($iinfo['file'])) {
+      $this->rrd_file = (($iinfo['file']{0} != '/')?$this->basedir:'').$iinfo['file'];
+      $this->basename = (substr($this->rrd_file, -4) == '.rrd')?substr($this->rrd_file, 0, -4):$this->rrd_file;
+    }
+    elseif (!is_null($conf_id) && file_exists($conf_id.'.rrd')) {
+      $this->rrd_file = (($iinfo['file']{0} != '/')?$this->basedir:'').$conf_id.'.rrd';
+      $this->basename = $conf_id;
     }
     else {
-      $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
-      $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
+      $this->basename = !is_null($conf_id)?$conf_id:'xxx.unknown';
     }
 
+    if (!is_null($this->rrd_file)) {
+      // fields (data sources, DS)
+      //  name - DS name
+      //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
+      //  heartbeat - if no sample recieved for that time, store UNKNOWN
+      //  min - U (unconstrained) or minimum value
+      //  max - U (unconstrained) or maximum value
+      //  update - this string will be fed into eval() for updating this field
+      if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
+        $this->rrd_fields = $iinfo['fields'];
+      }
+      else {
+        $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
+        $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
+      }
 
-    // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
-    //
-    // archives (RRAs):
-    // 600 samples of 5 minutes  (2 days and 2 hours)
-    // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
-    // 775 samples of 2 hours    (above + 50 days)
-    // 797 samples of 1 day      (above + 732 days, rounded up to 797)
 
-    $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
+      // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
+      //
+      // archives (RRAs):
+      // 600 samples of 5 minutes  (2 days and 2 hours)
+      // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
+      // 775 samples of 2 hours    (above + 50 days)
+      // 797 samples of 1 day      (above + 732 days, rounded up to 797)
 
-    if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
-      $this->rra_base = $iinfo['rra_base'];
-    }
-    else {
-      $this->rra_base[] = array('step' => 1, 'rows' => 600);
-      $this->rra_base[] = array('step' => 6, 'rows' => 700);
-      $this->rra_base[] = array('step' => 24, 'rows' => 775);
-      $this->rra_base[] = array('step' => 288, 'rows' => 797);
-    }
+      $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
+
+      if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
+        $this->rra_base = $iinfo['rra_base'];
+      }
+      else {
+        $this->rra_base[] = array('step' => 1, 'rows' => 600);
+        $this->rra_base[] = array('step' => 6, 'rows' => 700);
+        $this->rra_base[] = array('step' => 24, 'rows' => 775);
+        $this->rra_base[] = array('step' => 288, 'rows' => 797);
+      }
 
-    $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
+      $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
+    }
 
     if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
     if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
     $this->config_raw = $iinfo;
+    $this->config_all = $complete_conf;
   }
 
   function create() {
@@ -136,54 +287,96 @@ class rrdstat {
         }
       }
     }
-    $output = array(); $return_var = null;
-    exec($create_cmd, $output, $return_var);
-    if ($return_var) { trigger_error('rrd create returned with value '.$return_var, E_USER_WARNING); }
+    $return = `$create_cmd 2>&1`;
+    if (strpos($return, 'ERROR') !== false) {
+      trigger_error($this->rrd_file.' - rrd create error: '.$return, E_USER_WARNING);
+    }
     else { $this->status = 'ok'; }
   }
 
   function update($upArray = null) {
     // feed new data into RRD
-    if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
+    if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return false; }
     $upvals = array();
-    foreach($this->rrd_fields as $ds) {
-      if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
-      elseif (isset($ds['update'])) {
-        $val = null; $evalcode = null;
-        if (substr($ds['update'], 0, 4) == 'val:') {
-          $evalcode = 'print(trim('.substr($ds['update'], 4).'));';
-        }
-        elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
-          $snmphost = 'localhost'; $snmpcomm = 'public';
-          list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
-          $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
-          $ifnr = null;
-          foreach ($iflist as $ifdesc) {
-            if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
-          }
-          $oid = null;
-          if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
-          elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
-          if (!is_null($ifnr) && !is_null($oid)) {
-            $evalcode = 'print(trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)));';
-          }
-        }
-        else { $evalcode = $ds['update']; }
+    if (isset($this->config_raw['update'])) {
+      if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $this->config_raw['update'], $regs)) {
+        $upfunc = create_function('', $regs[1]);
+        $upvals = $upfunc();
+      }
+      else {
+        $evalcode = $this->config_raw['update'];
         if (!is_null($evalcode)) {
           ob_start();
           eval($evalcode);
-          $val = ob_get_contents();
+          $ret = ob_get_contents();
+          if (strlen($ret)) { $upvals = explode("\n", $ret); }
           ob_end_clean();
         }
       }
-      else { $val = null; }
-      $upvals[] = is_null($val)?'U':$val;
-    }
-    $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
-    $output = array(); $return_var = null;
-    exec($update_cmd, $output, $return_var);
-    if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
-  return ($return_var == 0);
+    }
+    else {
+      foreach ($this->rrd_fields as $ds) {
+        if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
+        elseif (isset($ds['update'])) {
+          $val = null; $evalcode = null;
+          if (substr($ds['update'], 0, 4) == 'val:') {
+            $evalcode = 'function { return trim('.substr($ds['update'], 4).')); }';
+          }
+          elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
+            $snmphost = 'localhost'; $snmpcomm = 'public';
+            list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
+            $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
+            $ifnr = null;
+            foreach ($iflist as $ifdesc) {
+              if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
+            }
+            $oid = null;
+            if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
+            elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
+            if (!is_null($ifnr) && !is_null($oid)) {
+              $evalcode = 'function { return trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)); }';
+            }
+          }
+          else { $evalcode = $ds['update']; }
+          if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $evalcode, $regs)) {
+            $upfunc = create_function('', $regs[1]);
+            $val = $upfunc();
+          }
+          elseif (!is_null($evalcode)) {
+            ob_start();
+            eval($evalcode);
+            $val = ob_get_contents();
+            ob_end_clean();
+          }
+        }
+        else { $val = null; }
+        $upvals[$ds['name']] = $val;
+      }
+    }
+    $key_names = (!is_numeric(array_shift(array_keys($upvals))));
+    if (in_array('L', $upvals)) {
+      // for at least one value, we need to set the same as the last recorded value
+      $fvals = $this->fetch();
+      $rowids = array_shift($fvals);
+      $lastvals = array_shift($fvals);
+      foreach (array_keys($upvals, 'L') as $akey) {
+        $upvals[$akey] = $key_names?$lastvals[$akey]:$lastvals[$rowids[$akey]];
+      }
+    }
+    $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
+    array_walk($upvals, $walkfunc);
+    $return = null;
+    if (count($upvals)) {
+      $update_cmd = 'rrdtool update '.$this->rrd_file.($key_names?' --template '.implode(':', array_keys($upvals)):'').' N:'.implode(':', $upvals);
+      $return = `$update_cmd 2>&1`;
+    }
+
+    if (strpos($return, 'ERROR') !== false) {
+      trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
+      $success = false;
+    }
+    else { $success = true; }
+  return $success;
   }
 
   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
@@ -203,7 +396,7 @@ class rrdstat {
     $return = `$fetch_cmd 2>&1`;
 
     if (strpos($return, 'ERROR') !== false) {
-      trigger_error('rrd fetch error: '.$return, E_USER_WARNING);
+      trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
       $fresult = false;
     }
     else {
@@ -215,7 +408,7 @@ class rrdstat {
         foreach ($rows as $row) {
           if (strlen(trim($row))) {
             $rvals = preg_split('/\s+/', $row);
-            $rtime = array_shift($rvals);
+            $rtime = str_replace(':', '', array_shift($rvals));
             $rv_array = array();
             foreach ($rvals as $key=>$rval) {
               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
@@ -228,6 +421,17 @@ class rrdstat {
   return $fresult;
   }
 
+  function last_update() {
+    // fetch time of last update in this RRD file
+    static $last_update;
+    if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
+      $last_cmd = 'rrdtool last '.$this->rrd_file;
+      $return = trim(`$last_cmd 2>&1`);
+      $last_update = is_numeric($return)?$return:null;
+    }
+  return isset($last_update)?$last_update:null;
+  }
+
   function graph($timeframe = 'day', $sub = null, $extra = null) {
     // create a RRD graph
     static $gColors;
@@ -235,7 +439,7 @@ class rrdstat {
       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
     }
 
-    if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
+    if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
 
     // assemble configuration
     $gconf = (array)$extra;
@@ -258,15 +462,16 @@ class rrdstat {
     }
 
     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
-    else { $fname = str_replace('.rrd', (is_null($sub)?'':'-%s').'-%t%f', $this->rrd_file); }
+    else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
     $fname = str_replace('%s', strval($sub), $fname);
     $fname = str_replace('%t', $timeframe, $fname);
     $fname = str_replace('%f', $fmt_ext, $fname);
     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
-    if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
+    if (isset($gconf['path']) && ($fname{0} != '/')) { $fname = $gconf['path'].'/'.$fname; }
+    if ($fname{0} != '/') { $fname = $this->basedir.$fname; }
     $fname = str_replace('//', '/', $fname);
 
-    $graphrows = array(); $gC = 0;
+    $graphrows = array(); $specialrows = array(); $gC = 0;
     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
 
     if ($timeframe == 'day') {
@@ -295,8 +500,8 @@ class rrdstat {
       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
       // vertical lines at month borders
-      $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
-      $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
+      $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
+      $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
     }
     else {
       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
@@ -312,6 +517,7 @@ class rrdstat {
           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
           if ($grow['dType'] == 'DEF') {
             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
+            if (isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
           }
           else {
@@ -332,6 +538,7 @@ class rrdstat {
             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
           }
           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
+          if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
           $graphrows[] = $grow;
         }
       }
@@ -352,6 +559,10 @@ class rrdstat {
         }
         $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
+        if (isset($ds['legend'])) {
+          $grow['legend'] = $ds['legend'];
+          if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
+        }
         $graphrows[] = $grow;
       }
     }
@@ -381,7 +592,7 @@ class rrdstat {
     else {
       foreach ($graphrows as $grow) {
         if (isset($grow['gType']) && strlen($grow['gType'])) {
-          $textprefix = isset($grow['legend'])?$grow['legend']:$grow['name'];
+          $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
           // XXX: use lines below once we have rrdtol 1.2
           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
@@ -420,7 +631,11 @@ class rrdstat {
     foreach ($graphrows as $grow) {
       if (isset($grow['dType']) && strlen($grow['dType'])) {
         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
-        $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
+        if ($grow['dType'] == 'DEF') {
+          $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
+          $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
+        }
+        else { $gDefs .= $grow['rpn_expr']; }
       }
       if (isset($grow['gType']) && strlen($grow['gType'])) {
         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
@@ -444,16 +659,72 @@ class rrdstat {
     $return = `$graph_cmd 2>&1`;
 
     if (strpos($return, 'ERROR') !== false) {
-      trigger_error('rrd graph error: '.$return, E_USER_WARNING);
+      trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
       $return = $graph_cmd."\n\n".$return;
     }
     $return = 'file:'.$fname."\n".$return;
   return $return;
   }
 
+  function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
+    // create a RRD graph and return meta info as a ready-to-use array
+    $gmeta = array('filename'=>null);
+    $ret = $this->graph($timeframe, $sub, $extra);
+    if (strpos($ret, "\n\n") !== false) { $gmeta['graph_cmd'] = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
+    else { $gmeta['graph_cmd'] = null; }
+    $grout = explode("\n", $ret);
+    foreach ($grout as $gline) {
+      if (preg_match('/^file:(.+)$/', $gline, $regs)) {
+        $gmeta['filename'] = $regs[1];
+      }
+      elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
+        $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
+      }
+      elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
+        $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
+      }
+      elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
+        $gmeta['var'][$regs[1]] = $regs[2];
+      }
+      elseif (strlen(trim($gline))) {
+        $gmeta['info'][] = $gline;
+      }
+    }
+    if (is_null($gmeta['filename'])) {
+      $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
+    }
+  return $gmeta;
+  }
+
+  function page($sub = null, $page_extras = null, $graph_extras = null) {
+    // create a (HTML) page and return it in a string
+
+    // assemble configuration
+    $pconf = (array)$page_extras;
+    if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
+      $pconf = $pconf + $this->config_raw['page.'.$sub];
+    }
+    $pconf = $pconf + (array)$this->config_page;
+
+    $return = null;
+    switch ($pconf['type']) {
+      case 'index':
+        $return = $this->page_index($pconf);
+        break;
+      case 'overview':
+        $return = $this->page_overview($pconf, $graph_extras);
+        break;
+      case 'simple':
+      default:
+        $return = $this->page_simple($pconf, $graph_extras);
+        break;
+    }
+  return $return;
+  }
+
   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
     // create a simple (MRTG-like) HTML page and return it in a string
-    $basename = str_replace('.rrd', '', $this->rrd_file);
+    // XXX: this is here temporarily for compat only, it's preferred to use page()!
 
     // assemble configuration
     $pconf = (array)$page_extras;
@@ -462,7 +733,150 @@ class rrdstat {
     }
     $pconf = $pconf + (array)$this->config_page;
 
-    $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$basename.' - RRD statistics';
+  return $this->page_simple($pconf, $graph_extras);
+  }
+
+  function page_index($pconf) {
+    // create a bare, very simple index list HTML page and return it in a string
+
+    $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics index';
+
+    $out = '<html><head>';
+    $out .= '<title>'.$ptitle.'</title>';
+    $out .= '<style>';
+    if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
+    else {
+      $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
+      $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
+      $out .= 'li.scanfile { font-style: italic; }';
+    }
+    if (isset($pconf['style'])) { $out .= $pconf['style']; }
+    $out .= '</style>';
+    $out .= '</head>';
+    $out .= '<body>';
+
+    $out .= '<h1>'.$ptitle.'</h1>';
+    if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
+      $out .= '<p class="intro">'.$pconf['text_intro'].'</p>';
+    }
+    elseif (!isset($pconf['text_intro'])) {
+      $out .= '<p class="intro">The following RRD stats are available:</p>';
+    }
+
+    $stats = $this->h_page_statsArray($pconf);
+
+    $out .= '<ul class="indexlist">';
+    foreach ($stats as $stat) {
+      $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
+      $surl = '?stat='.$stat['name'];
+      $out .= '<a href="'.$surl.'">'.$stat['name'].'</a>';
+      if (isset($stat['sub']) && count($stat['sub'])) {
+        $sprt = array();
+        foreach ($stat['sub'] as $ssub) { $sprt[] = '<a href="'.$surl.'&sub='.$ssub.'">'.$ssub.'</a>'; }
+        $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
+      }
+      $out .= '</li>';
+    }
+    $out .= '</ul>';
+
+    $out .= $this->h_page_footer();
+    $out .= '</body></html>';
+  return $out;
+  }
+
+  function page_overview($pconf, $graph_extras = null) {
+    // create an overview HTML page (including graphs) and return it in a string
+
+    $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics overview';
+
+    $out = '<html><head>';
+    $out .= '<title>'.$ptitle.'</title>';
+    $out .= '<style>';
+    if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
+    else {
+      $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
+      $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }';
+      $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
+      $out .= 'img.rrdgraph { border: none; }';
+    }
+    if (isset($pconf['style'])) { $out .= $pconf['style']; }
+    $out .= '</style>';
+    $out .= '</head>';
+    $out .= '<body>';
+
+    $out .= '<h1>'.$ptitle.'</h1>';
+    if (isset($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'; }
+
+    $stats = $this->h_page_statsArray($pconf);
+
+    $num_rows = is_numeric($pconf['num_rows'])?$pconf['num_rows']:2;
+    $num_cols = ceil(count($stats)/$num_rows);
+
+    $out .= '<table class="overview">';
+    for ($col = 0; $col < $num_cols; $col++) {
+      $out .= '<tr>';
+      for ($row = 0; $row < $num_rows; $row++) {
+        $idx = $col * $num_rows + $row;
+        $out .= '<td>';
+        if ($idx < count($stats)) {
+          list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
+          $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
+          $g_sub = $this->config_all[$sname][$s_psname]['graph_sub'];
+
+          if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
+            $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
+          }
+          elseif (isset($this->config_all[$sname]['page']['title_page'])) {
+            $s_ptitle = $this->config_all[$sname]['page']['title_page'];
+          }
+          else {
+            $s_ptitle = $sname.(isset($s_psub)?' ('.$s_psub.')':'').' statistics';
+          }
+          if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
+            $out .= '<h2>'.$s_ptitle.'</h2>';
+          }
+
+          $s_rrd = new rrdstat($this->config_all, $sname);
+          if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
+            $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
+            $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
+            if (isset($pconf['graph_url'])) {
+              $gURL = $pconf['graph_url'];
+              $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
+              $fname = str_replace('%p', $gmeta['filename'], $gURL);
+              if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
+            }
+            else {
+              $gURL = $gmeta['filename'];
+            }
+            $out .= '<a href="?stat='.$sname.(isset($s_psub)?'&sub='.$s_psub:'').'"';
+            $out .= '<img src="'.$gURL.'"';
+            $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
+            $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
+            $out .= '</a>';
+          }
+          else {
+            $out .= 'RRD error: status is "'.$s_rrd->status.'"';
+          }
+        }
+        else {
+          $out .= '&nbsp;';
+        }
+        $out .= '</td>';
+      }
+      $out .= '</tr>';
+    }
+    $out .= '</table>';
+
+    $out .= $this->h_page_footer();
+    $out .= '</body></html>';
+  return $out;
+  }
+
+  function page_simple($pconf, $graph_extras = null) {
+    // create a simple (MRTG-like) HTML page and return it in a string
+
+    $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$this->basename.' - RRD statistics';
     $gtitle = array();
     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
@@ -488,40 +902,27 @@ class rrdstat {
 
     $out .= '<h1>'.$ptitle.'</h1>';
     if (!isset($pconf['show_update']) || $pconf['show_update']) {
-      $out .= '<p class="last_up">Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
+      $out .= '<p class="last_up">Last Update: '.(is_null($this->last_update())?'unknown':date('Y-m-d H:i:s', $this->last_update())).'</p>';
     }
 
-    if (in_array($this->status, array('ok','readonly'))) {
-      $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
+    $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
+    if (in_array($this->status, array('ok','readonly','graphonly'))) {
       foreach (array('day','week','month','year') as $tframe) {
-        $ret = $this->graph($tframe, $g_sub, $graph_extras);
-        if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
-        else { $graph_cmd = null; }
-        $grout = explode("\n",$ret);
-        $gfilename = null;
-        $gmeta = array();
-        foreach ($grout as $gline) {
-          if (preg_match('/^file:(.+)$/', $gline, $regs)) {
-            $gfilename = $regs[1];
-          }
-          elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
-            $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
-          }
-          elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
-            $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
-          }
-          elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
-            $gmeta['var'][$regs[1]] = $regs[2];
-          }
-          elseif (strlen(trim($gline))) {
-            $gmeta['info'][] = $gline;
-          }
+        $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
+        if (isset($pconf['graph_url'])) {
+          $gURL = $pconf['graph_url'];
+          $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
+          $fname = str_replace('%p', $gmeta['filename'], $gURL);
+          if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
+        }
+        else {
+          $gURL = $gmeta['filename'];
         }
         $out .= '<div class="'.$tframe.'">';
 //         $out .= '<p>'.nl2br($ret).'</p>';
         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
-        $out .= '<img src="'.(!is_null($gfilename)?$gfilename:$basename.(!is_null($g_sub)?'-'.$g_sub:'').'-'.$tframe.'.png').'"';
-        $out .= ' alt="'.$basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
+        $out .= '<img src="'.$gURL.'"';
+        $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
         if (isset($gmeta['data']) && count($gmeta['data'])) {
           $out .= '<table class="gdata">';
@@ -544,31 +945,65 @@ class rrdstat {
             $out .= '<p class="ginfo">'.$gval.'</p>';
           }
         }
+        $out .= '</div>';
       }
     }
     else {
       $out .= 'RRD error: status is "'.$this->status.'"';
     }
-    $out .= '</div>';
-
-    $out .= '<p class="footer">';
-    $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
-    $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
-    $out .= '</p>';
 
+    $out .= $this->h_page_footer();
     $out .= '</body></html>';
   return $out;
   }
 
-  function last_update() {
-    // fetch time of last update in this RRD file
-    static $last_update;
-    if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
-      $last_cmd = 'rrdtool last '.$this->rrd_file;
-      $return = trim(`$last_cmd 2>&1`);
-      $last_update = is_numeric($return)?$return:null;
+  function h_page_statsArray($pconf) {
+    // return array of stats to list on a page
+    $stats = array();
+    $snames = array(); $s_exclude = array(); $sfiles = array();
+    if (isset($pconf['index_ids'])) {
+      foreach (explode(',', $pconf['index_ids']) as $iid) {
+        if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
+        else { $snames[] = $iid; }
+      }
     }
-  return isset($last_update)?$last_update:null;
+    if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
+      foreach ($this->config_all as $iname=>$rinfo) {
+        if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
+            !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
+          $snames[] = $iname;
+        }
+      }
+    }
+    foreach ($snames as $iname) {
+      $newstat = array('name'=>$iname);
+      $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
+      if (is_array($this->config_all[$iname])) {
+        foreach ($this->config_all[$iname] as $key=>$val) {
+          if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
+        }
+      }
+      $stats[] = $newstat;
+    }
+    if (isset($pconf['scan_files']) && $pconf['scan_files']) {
+      $rrdfiles = glob('*.rrd');
+      foreach ($rrdfiles as $rrdfile) {
+        $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
+        if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
+          $stats[] = array('name'=>$iname, 'class'=>'scanfile');
+        }
+      }
+    }
+  return $stats;
+  }
+
+  function h_page_footer() {
+    // return generic page footer
+    $out = '<p class="footer">';
+    $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
+    $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
+    $out .= '</p>';
+  return $out;
   }
 
   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }