0cc03ef556fc62aada4882a69cef84bc2c8d6fdf
[php-utility-classes.git] / include / classes / rrdstat.php-class
1 <?php
2 /* ***** BEGIN LICENSE BLOCK *****
3  *
4  * The contents of this file are subject to Austrian copyright reegulations
5  * ("Urheberrecht"); you may not use this file except in compliance with
6  * those laws.
7  * This contents and any derived work, if it gets distributed in any way,
8  * is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
9  * either express or implied.
10  *
11  * The Original Code is KaiRo's RRD statistics class.
12  *
13  * The Initial Developer of the Original Code is
14  * KaiRo - Robert Kaiser.
15  * Portions created by the Initial Developer are Copyright (C) 2005
16  * the Initial Developer. All Rights Reserved.
17  *
18  * Contributor(s): Robert Kaiser <kairo@kairo.at>
19  *
20  * ***** END LICENSE BLOCK ***** */
21
22 class rrdstat {
23   // rrdstat PHP class
24   // rrdtool statistics functions
25   //
26   // function rrdstat($rrdconfig, [$conf_id])
27   //   CONSTRUCTOR
28   //     if $conf_id is set, $rrdconfig is a total configuration set
29   //     else it's the configuration for this one RRD
30   //     currently only a config array is supported, XML config is planned
31   //
32   // var $rrd_file
33   // RRD file name
34   //
35   // var $basename
36   // base name for this RRD (usually file name without .rrd)
37   //
38   // var $config_all
39   // complete, raw configuration array set
40   //
41   // var $config_raw
42   // configuration array set for current RRD
43   //
44   // var $config_graph
45   // configuration array set for default graph in this RRD
46   //
47   // var $config_page
48   // configuration array set for default page in this RRD
49   //
50   // var $rrd_fields
51   // definition of this RRD's fields
52   //
53   // var $rra_base
54   // definition of this RRD's base RRAs
55   //
56   // var $rrd_step
57   // basic stepping of this RRD in seconds (default: 300)
58   //
59   // var $rra_add_max
60   // should RRAs for MAX be added for every base RRA? (bool, default: true)
61   //
62   // var $status
63   // status of the RRD (unused/ok/readonly/graphonly)
64   //   note that most functions require certain status values
65   //   (e.g. update only works if status is ok, graph for ok/readonly/graphonly)
66   //
67   // function set_def($rrdconfig, [$conf_id])
68   //   set definitions based on given configuration
69   //   [intended for internal use, called by the constructor]
70   //
71   // function create()
72   //   create RRD file according to set config
73   //
74   // function update([$upArray])
75   //   feed new data into RRD (either use given array of values or use auto-update info from config)
76   //
77   // function fetch([$cf] = 'AVERAGE', $resolution = null, $start = null, $end = null)
78   //   fetch data from the defined RRD
79   //     using given consolidation function [default is AVERAGE],
80   //     resolution (seconds, default is the RRD's stepping),
81   //     start and end times (unix epoch, defaults are the RRD's last update time)
82   //
83   // function last_update()
84   //   fetch time of last update in this RRD file
85   //
86   // function graph([$timeframe], [$sub], [$extra])
87   //   create a RRD graph (and return all meta info in a flat string)
88   //     for given timeframe (day [default]/week/month/year),
89   //     sub-graph ID (if given) and extra config options (if given)
90   //
91   // function graph_plus([$timeframe], [$sub], [$extra])
92   //   create a RRD graph (see above) and return meta info as a ready-to-use array
93   //
94   // function page([$sub], [$page_extras], [$graph_extras])
95   //   create a (HTML) page and return it in a string
96   //     for given sub-page ID (if given, default is a simple HTML page)
97   //     and extra page and graph config options (if given)
98   //
99   // function simple_html([$sub], [$page_extras], [$graph_extras])
100   //   create a simple (MRTG-like) HTML page and return it in a string
101   //   XXX: this is here temporarily for compat only, it's preferred to use page()!
102   //
103   // function page_index($pconf)
104   //   create a bare, very simple index list HTML page and return it in a string
105   //   using given page config options
106   //   [intended for internal use, called by page()]
107   //
108   // function page_overview($pconf, [$graph_extras])
109   //   create an overview HTML page (including graphs) and return it in a string
110   //   using given page config options and extra graph options (if given)
111   //   [intended for internal use, called by page()]
112   //
113   // function page_simple($pconf, [$graph_extras])
114   //   create a simple (MRTG-like) HTML page and return it in a string
115   //   using given page config options and extra graph options (if given)
116   //   [intended for internal use, called by page()]
117   //
118   // function h_page_statsArray($pconf)
119   //   return array of stats to list on a page, using given page config options
120   //   [intended for internal use, called by page_*()]
121   //
122   // function h_page_footer()
123   //   return generic page footer
124   //   [intended for internal use, called by page_*()]
125   //
126   // function text_quote($text)
127   //   return a quoted/escaped text for use in rrdtool commandline text fields
128
129   var $rrd_file = null;
130   var $basename = null;
131
132   var $config_all = null;
133   var $config_raw = null;
134   var $config_graph = null;
135   var $config_page = null;
136
137   var $rrd_fields = array();
138   var $rra_base = array();
139   var $rrd_step = 300;
140   var $rra_add_max = true;
141
142   var $status = 'unused';
143
144   function rrdstat($rrdconfig, $conf_id = null) {
145     // ***** init RRD stat module *****
146     $this->set_def($rrdconfig, $conf_id);
147
148     if (($this->status == 'unused') && !is_null($this->rrd_file)) {
149       if (!is_writeable($this->rrd_file)) {
150         if (!file_exists($this->rrd_file)) {
151           if (@touch($this->rrd_file)) { $this->create(); }
152           else { trigger_error('RRD file can not be created', E_USER_WARNING); }
153         }
154         else {
155           if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
156           else { trigger_error('RRD file is not readable', E_USER_WARNING); }
157         }
158       }
159       else {
160         $this->status = 'ok';
161       }
162     }
163   }
164
165   function set_def($rrdconfig, $conf_id = null) {
166     if (is_array($rrdconfig)) {
167       // we have an array in the format we like to have
168       $complete_conf =& $rrdconfig;
169     }
170     else {
171       // we have something else (XML data?), try to generate the iinfo aray from it
172       $complete_conf =& $rrdconfig;
173     }
174
175     if (!is_null($conf_id)) {
176       $iinfo = isset($complete_conf[$conf_id])?$complete_conf[$conf_id]:array();
177       if (isset($complete_conf['*'])) {
178         $iinfo = (array)$iinfo + (array)$complete_conf['*'];
179         if (isset($complete_conf['*']['graph'])) { $iinfo['graph'] = (array)$iinfo['graph'] + (array)$complete_conf['*']['graph']; }
180         if (isset($complete_conf['*']['page'])) { $iinfo['page'] = (array)$iinfo['page'] + (array)$complete_conf['*']['page']; }
181       }
182     }
183     else {
184       $iinfo = $complete_conf;
185     }
186
187     if (isset($iinfo['graph-only']) && $iinfo['graph-only'] && !is_null($conf_id)) {
188       $this->basename = $conf_id;
189       $this->status = 'graphonly';
190     }
191     elseif (isset($iinfo['file'])) {
192       $this->rrd_file = $iinfo['file'];
193       $this->basename = (substr($this->rrd_file, -4) == '.rrd')?substr($this->rrd_file, 0, -4):$this->rrd_file;
194     }
195     elseif (!is_null($conf_id) && file_exists($conf_id.'.rrd')) {
196       $this->rrd_file = $conf_id.'.rrd';
197       $this->basename = $conf_id;
198     }
199     else {
200       $this->basename = !is_null($conf_id)?$conf_id:'xxx.unknown';
201     }
202
203     if (!is_null($this->rrd_file)) {
204       // fields (data sources, DS)
205       //  name - DS name
206       //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
207       //  heartbeat - if no sample recieved for that time, store UNKNOWN
208       //  min - U (unconstrained) or minimum value
209       //  max - U (unconstrained) or maximum value
210       //  update - this string will be fed into eval() for updating this field
211       if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
212         $this->rrd_fields = $iinfo['fields'];
213       }
214       else {
215         $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
216         $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
217       }
218
219
220       // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
221       //
222       // archives (RRAs):
223       // 600 samples of 5 minutes  (2 days and 2 hours)
224       // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
225       // 775 samples of 2 hours    (above + 50 days)
226       // 797 samples of 1 day      (above + 732 days, rounded up to 797)
227
228       $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
229
230       if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
231         $this->rra_base = $iinfo['rra_base'];
232       }
233       else {
234         $this->rra_base[] = array('step' => 1, 'rows' => 600);
235         $this->rra_base[] = array('step' => 6, 'rows' => 700);
236         $this->rra_base[] = array('step' => 24, 'rows' => 775);
237         $this->rra_base[] = array('step' => 288, 'rows' => 797);
238       }
239
240       $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
241     }
242
243     if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
244     if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
245     $this->config_raw = $iinfo;
246     $this->config_all = $complete_conf;
247   }
248
249   function create() {
250     // create RRD file
251
252     // compose create command
253     $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
254     foreach ($this->rrd_fields as $ds) {
255       if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
256       if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
257       if (!isset($ds['min'])) { $ds['min'] = 'U'; }
258       if (!isset($ds['max'])) { $ds['max'] = 'U'; }
259       $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
260     }
261     foreach ($this->rra_base as $rra) {
262       if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
263       if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
264       if (!isset($rra['step'])) { $rra['step'] = 1; }
265       if (!isset($rra['rows'])) { $rra['rows'] = 600; }
266       $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
267     }
268     if ($this->rra_add_max) {
269       foreach ($this->rra_base as $rra) {
270         if (!isset($rra['cf'])) {
271           // only rows that have no CF set will be looked at here
272           $rra['cf'] = 'MAX';
273           if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
274           if (!isset($rra['step'])) { $rra['step'] = 1; }
275           if (!isset($rra['rows'])) { $rra['rows'] = 600; }
276           $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
277         }
278       }
279     }
280     $return = `$create_cmd 2>&1`;
281     if (strpos($return, 'ERROR') !== false) {
282       trigger_error($this->rrd_file.' - rrd create error: '.$return, E_USER_WARNING);
283     }
284     else { $this->status = 'ok'; }
285   }
286
287   function update($upArray = null) {
288     // feed new data into RRD
289     if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return false; }
290     $upvals = array();
291     if (isset($this->config_raw['update'])) {
292       if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $this->config_raw['update'], $regs)) {
293         $upfunc = create_function('', $regs[1]);
294         $upvals = $upfunc();
295       }
296       else {
297         $evalcode = $this->config_raw['update'];
298         if (!is_null($evalcode)) {
299           ob_start();
300           eval($evalcode);
301           $ret = ob_get_contents();
302           if (strlen($ret)) { $upvals = explode("\n", $ret); }
303           ob_end_clean();
304         }
305       }
306     }
307     else {
308       foreach ($this->rrd_fields as $ds) {
309         if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
310         elseif (isset($ds['update'])) {
311           $val = null; $evalcode = null;
312           if (substr($ds['update'], 0, 4) == 'val:') {
313             $evalcode = 'function { return trim('.substr($ds['update'], 4).')); }';
314           }
315           elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
316             $snmphost = 'localhost'; $snmpcomm = 'public';
317             list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
318             $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
319             $ifnr = null;
320             foreach ($iflist as $ifdesc) {
321               if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
322             }
323             $oid = null;
324             if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
325             elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
326             if (!is_null($ifnr) && !is_null($oid)) {
327               $evalcode = 'function { return trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)); }';
328             }
329           }
330           else { $evalcode = $ds['update']; }
331           if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $evalcode, $regs)) {
332             $upfunc = create_function('', $regs[1]);
333             $val = $upfunc();
334           }
335           elseif (!is_null($evalcode)) {
336             ob_start();
337             eval($evalcode);
338             $val = ob_get_contents();
339             ob_end_clean();
340           }
341         }
342         else { $val = null; }
343         $upvals[$ds['name']] = $val;
344       }
345     }
346     $key_names = (!is_numeric(array_shift(array_keys($upvals))));
347     if (in_array('L', $upvals)) {
348       // for at least one value, we need to set the same as the last recorded value
349       $fvals = $this->fetch();
350       $rowids = array_shift($fvals);
351       $lastvals = array_shift($fvals);
352       foreach (array_keys($upvals, 'L') as $akey) {
353         $upvals[$akey] = $key_names?$lastvals[$akey]:$lastvals[$rowids[$akey]];
354       }
355     }
356     $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
357     array_walk($upvals, $walkfunc);
358     $return = null;
359     if (count($upvals)) {
360       $update_cmd = 'rrdtool update '.$this->rrd_file.($key_names?' --template '.implode(':', array_keys($upvals)):'').' N:'.implode(':', $upvals);
361       $return = `$update_cmd 2>&1`;
362     }
363
364     if (strpos($return, 'ERROR') !== false) {
365       trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
366       $success = false;
367     }
368     else { $success = true; }
369   return $success;
370   }
371
372   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
373     // fetch data from a RRD
374     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
375
376     if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
377     if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
378     if (!is_numeric($end)) { $end = $this->last_update(); }
379     elseif ($end < 0) { $end += $this->last_update(); }
380     $end = intval($end/$resolution)*$resolution;
381     if (!is_numeric($start)) { $start = $end; }
382     elseif ($start < 0) { $start += $end; }
383     $start = intval($start/$resolution)*$resolution;
384
385     $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
386     $return = `$fetch_cmd 2>&1`;
387
388     if (strpos($return, 'ERROR') !== false) {
389       trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
390       $fresult = false;
391     }
392     else {
393       $fresult = array();
394       $rows = explode("\n", $return);
395       $fields = preg_split('/\s+/', array_shift($rows));
396       if (array_shift($fields) == 'timestamp') {
397         $fresult[0] = $fields;
398         foreach ($rows as $row) {
399           if (strlen(trim($row))) {
400             $rvals = preg_split('/\s+/', $row);
401             $rtime = str_replace(':', '', array_shift($rvals));
402             $rv_array = array();
403             foreach ($rvals as $key=>$rval) {
404               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
405             }
406             $fresult[$rtime] = $rv_array;
407           }
408         }
409       }
410     }
411   return $fresult;
412   }
413
414   function last_update() {
415     // fetch time of last update in this RRD file
416     static $last_update;
417     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
418       $last_cmd = 'rrdtool last '.$this->rrd_file;
419       $return = trim(`$last_cmd 2>&1`);
420       $last_update = is_numeric($return)?$return:null;
421     }
422   return isset($last_update)?$last_update:null;
423   }
424
425   function graph($timeframe = 'day', $sub = null, $extra = null) {
426     // create a RRD graph
427     static $gColors;
428     if (!isset($gColors)) {
429       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
430     }
431
432     if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
433
434     // assemble configuration
435     $gconf = (array)$extra;
436     if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
437       $gconf = $gconf + $this->config_raw['graph.'.$sub];
438     }
439     $gconf = $gconf + (array)$this->config_graph;
440
441     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
442       $format = $gconf['format']; $fmt_ext = '.svg';
443     }
444     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
445       $format = $gconf['format']; $fmt_ext = '.eps';
446     }
447     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
448       $format = $gconf['format']; $fmt_ext = '.pdf';
449     }
450     else {
451       $format = 'PNG'; $fmt_ext = '.png';
452     }
453
454     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
455     else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
456     $fname = str_replace('%s', strval($sub), $fname);
457     $fname = str_replace('%t', $timeframe, $fname);
458     $fname = str_replace('%f', $fmt_ext, $fname);
459     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
460     if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
461     $fname = str_replace('//', '/', $fname);
462
463     $graphrows = array(); $specialrows = array(); $gC = 0;
464     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
465
466     if ($timeframe == 'day') {
467       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
468       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
469       // vertical lines at day borders
470       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
471       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
472       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
473     }
474     elseif ($timeframe == 'week') {
475       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
476       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
477       // vertical lines at week borders
478       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
479       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
480     }
481     elseif ($timeframe == 'month') {
482       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
483       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
484       // vertical lines at month borders
485       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
486       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
487     }
488     elseif ($timeframe == 'year') {
489       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
490       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
491       // vertical lines at month borders
492       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
493       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
494     }
495     else {
496       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
497       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
498     }
499
500     if (isset($gconf['rows']) && count($gconf['rows'])) {
501       foreach ($gconf['rows'] as $erow) {
502         if (isset($erow['name']) && strlen($erow['name'])) {
503           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
504           $grow = array();
505           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
506           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
507           if ($grow['dType'] == 'DEF') {
508             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
509             if (isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
510             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
511           }
512           else {
513             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
514           }
515           if (isset($erow['scale'])) {
516             $graphrows[] = $grow;
517             $grow = array();
518             $grow['dType'] = 'CDEF';
519             $grow['name'] = $erow['name'];
520             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
521           }
522           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
523           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
524           if ($gC >= count($gColors)) { $gC = 0; }
525           if (isset($erow['legend'])) {
526             $grow['legend'] = $erow['legend'];
527             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
528           }
529           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
530           if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
531           $graphrows[] = $grow;
532         }
533       }
534     }
535     else {
536       foreach ($this->rrd_fields as $key=>$ds) {
537         $grow = array();
538         $grow['dType'] = 'DEF';
539         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
540         $grow['dsname'] = $ds['name'];
541         $grow['cf'] = 'AVERAGE';
542         if (isset($gconf['scale'])) {
543           $graphrows[] = $grow;
544           $grow = array();
545           $grow['dType'] = 'CDEF';
546           $grow['name'] = $ds['name'];
547           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
548         }
549         $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
550         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
551         if (isset($ds['legend'])) {
552           $grow['legend'] = $ds['legend'];
553           if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
554         }
555         $graphrows[] = $grow;
556       }
557     }
558
559     if (isset($gconf['special']) && count($gconf['special'])) {
560       foreach ($gconf['special'] as $crow) {
561         $srow = array();
562         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
563         if ($grow['sType'] != 'COMMENT') {
564           // XXX: use line below and remove cf var once we have rrdtol 1.2
565           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
566           $srow['name'] = $crow['name'];
567           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
568           if (isset($crow['cf'])) {
569             // XXX: use line below once we have rrdtol 1.2
570             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
571           }
572           elseif (isset($crow['rpn_expr'])) {
573             // XXX: does only work with rrdtool 1.2
574             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
575           }
576         }
577         $srow['text'] = isset($crow['text'])?$crow['text']:'';
578         $specialrows[] = $srow;
579       }
580     }
581     else {
582       foreach ($graphrows as $grow) {
583         if (isset($grow['gType']) && strlen($grow['gType'])) {
584           $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
585           // XXX: use lines below once we have rrdtol 1.2
586           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
587           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
588           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
589           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
590           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
591         }
592       }
593     }
594
595     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
596     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
597     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
598     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
599     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
600     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
601       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
602     }
603     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
604     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
605     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
606     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
607     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
608     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
609     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
610     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
611     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
612     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
613       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
614     }
615     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
616       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
617     }
618     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
619
620     foreach ($graphrows as $grow) {
621       if (isset($grow['dType']) && strlen($grow['dType'])) {
622         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
623         if ($grow['dType'] == 'DEF') {
624           $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
625           $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
626         }
627         else { $gDefs .= $grow['rpn_expr']; }
628       }
629       if (isset($grow['gType']) && strlen($grow['gType'])) {
630         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
631         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
632         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
633         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
634         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
635         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
636       }
637     }
638
639     foreach ($specialrows as $srow) {
640       $addSpecial .= ' '.$srow['sType'];
641       // XXX: eliminate cf once we have rrdtool 1.2
642       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
643       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
644       $addSpecial .= ':'.$this->text_quote($srow['text']);
645     }
646
647     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
648     $return = `$graph_cmd 2>&1`;
649
650     if (strpos($return, 'ERROR') !== false) {
651       trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
652       $return = $graph_cmd."\n\n".$return;
653     }
654     $return = 'file:'.$fname."\n".$return;
655   return $return;
656   }
657
658   function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
659     // create a RRD graph and return meta info as a ready-to-use array
660     $gmeta = array('filename'=>null);
661     $ret = $this->graph($timeframe, $sub, $extra);
662     if (strpos($ret, "\n\n") !== false) { $gmeta['graph_cmd'] = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
663     else { $gmeta['graph_cmd'] = null; }
664     $grout = explode("\n", $ret);
665     foreach ($grout as $gline) {
666       if (preg_match('/^file:(.+)$/', $gline, $regs)) {
667         $gmeta['filename'] = $regs[1];
668       }
669       elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
670         $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
671       }
672       elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
673         $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
674       }
675       elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
676         $gmeta['var'][$regs[1]] = $regs[2];
677       }
678       elseif (strlen(trim($gline))) {
679         $gmeta['info'][] = $gline;
680       }
681     }
682     if (is_null($gmeta['filename'])) {
683       $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
684     }
685   return $gmeta;
686   }
687
688   function page($sub = null, $page_extras = null, $graph_extras = null) {
689     // create a (HTML) page and return it in a string
690
691     // assemble configuration
692     $pconf = (array)$page_extras;
693     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
694       $pconf = $pconf + $this->config_raw['page.'.$sub];
695     }
696     $pconf = $pconf + (array)$this->config_page;
697
698     $return = null;
699     switch ($pconf['type']) {
700       case 'index':
701         $return = $this->page_index($pconf);
702         break;
703       case 'overview':
704         $return = $this->page_overview($pconf, $graph_extras);
705         break;
706       case 'simple':
707       default:
708         $return = $this->page_simple($pconf, $graph_extras);
709         break;
710     }
711   return $return;
712   }
713
714   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
715     // create a simple (MRTG-like) HTML page and return it in a string
716     // XXX: this is here temporarily for compat only, it's preferred to use page()!
717
718     // assemble configuration
719     $pconf = (array)$page_extras;
720     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
721       $pconf = $pconf + $this->config_raw['page.'.$sub];
722     }
723     $pconf = $pconf + (array)$this->config_page;
724
725   return $this->page_simple($pconf, $graph_extras);
726   }
727
728   function page_index($pconf) {
729     // create a bare, very simple index list HTML page and return it in a string
730
731     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics index';
732
733     $out = '<html><head>';
734     $out .= '<title>'.$ptitle.'</title>';
735     $out .= '<style>';
736     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
737     else {
738       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
739       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
740       $out .= 'li.scanfile { font-style: italic; }';
741     }
742     if (isset($pconf['style'])) { $out .= $pconf['style']; }
743     $out .= '</style>';
744     $out .= '</head>';
745     $out .= '<body>';
746
747     $out .= '<h1>'.$ptitle.'</h1>';
748     if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
749       $out .= '<p class="intro">'.$pconf['text_intro'].'</p>';
750     }
751     elseif (!isset($pconf['text_intro'])) {
752       $out .= '<p class="intro">The following RRD stats are available:</p>';
753     }
754
755     $stats = $this->h_page_statsArray($pconf);
756
757     $out .= '<ul class="indexlist">';
758     foreach ($stats as $stat) {
759       $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
760       $surl = '?stat='.$stat['name'];
761       $out .= '<a href="'.$surl.'">'.$stat['name'].'</a>';
762       if (isset($stat['sub']) && count($stat['sub'])) {
763         $sprt = array();
764         foreach ($stat['sub'] as $ssub) { $sprt[] = '<a href="'.$surl.'&sub='.$ssub.'">'.$ssub.'</a>'; }
765         $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
766       }
767       $out .= '</li>';
768     }
769     $out .= '</ul>';
770
771     $out .= $this->h_page_footer();
772     $out .= '</body></html>';
773   return $out;
774   }
775
776   function page_overview($pconf, $graph_extras = null) {
777     // create an overview HTML page (including graphs) and return it in a string
778
779     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics overview';
780
781     $out = '<html><head>';
782     $out .= '<title>'.$ptitle.'</title>';
783     $out .= '<style>';
784     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
785     else {
786       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
787       $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }';
788       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
789       $out .= 'img.rrdgraph { border: none; }';
790     }
791     if (isset($pconf['style'])) { $out .= $pconf['style']; }
792     $out .= '</style>';
793     $out .= '</head>';
794     $out .= '<body>';
795
796     $out .= '<h1>'.$ptitle.'</h1>';
797     if (isset($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'; }
798
799     $stats = $this->h_page_statsArray($pconf);
800
801     $num_rows = is_numeric($pconf['num_rows'])?$pconf['num_rows']:2;
802     $num_cols = ceil(count($stats)/$num_rows);
803
804     $out .= '<table class="overview">';
805     for ($col = 0; $col < $num_cols; $col++) {
806       $out .= '<tr>';
807       for ($row = 0; $row < $num_rows; $row++) {
808         $idx = $col * $num_rows + $row;
809         $out .= '<td>';
810         if ($idx < count($stats)) {
811           list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
812           $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
813           $g_sub = $this->config_all[$sname][$s_psname]['graph_sub'];
814
815           if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
816             $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
817           }
818           elseif (isset($this->config_all[$sname]['page']['title_page'])) {
819             $s_ptitle = $this->config_all[$sname]['page']['title_page'];
820           }
821           else {
822             $s_ptitle = $sname.(isset($s_psub)?' ('.$s_psub.')':'').' statistics';
823           }
824           if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
825             $out .= '<h2>'.$s_ptitle.'</h2>';
826           }
827
828           $s_rrd = new rrdstat($this->config_all, $sname);
829           if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
830             $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
831             $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
832             if (isset($pconf['graph_url'])) {
833               $gURL = $pconf['graph_url'];
834               $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
835               $fname = str_replace('%p', $gmeta['filename'], $gURL);
836               if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
837             }
838             else {
839               $gURL = $gmeta['filename'];
840             }
841             $out .= '<a href="?stat='.$sname.(isset($s_psub)?'&sub='.$s_psub:'').'"';
842             $out .= '<img src="'.$gURL.'"';
843             $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
844             $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
845             $out .= '</a>';
846           }
847           else {
848             $out .= 'RRD error: status is "'.$s_rrd->status.'"';
849           }
850         }
851         else {
852           $out .= '&nbsp;';
853         }
854         $out .= '</td>';
855       }
856       $out .= '</tr>';
857     }
858     $out .= '</table>';
859
860     $out .= $this->h_page_footer();
861     $out .= '</body></html>';
862   return $out;
863   }
864
865   function page_simple($pconf, $graph_extras = null) {
866     // create a simple (MRTG-like) HTML page and return it in a string
867
868     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$this->basename.' - RRD statistics';
869     $gtitle = array();
870     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
871     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
872     $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
873     $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
874
875     $out = '<html><head>';
876     $out .= '<title>'.$ptitle.'</title>';
877     $out .= '<style>';
878     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
879     else {
880       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
881       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
882       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
883       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
884       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
885       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
886     }
887     if (isset($pconf['style'])) { $out .= $pconf['style']; }
888     $out .= '</style>';
889     $out .= '</head>';
890     $out .= '<body>';
891
892     $out .= '<h1>'.$ptitle.'</h1>';
893     if (!isset($pconf['show_update']) || $pconf['show_update']) {
894       $out .= '<p class="last_up">Last Update: '.(is_null($this->last_update())?'unknown':date('Y-m-d H:i:s', $this->last_update())).'</p>';
895     }
896
897     $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
898     if (in_array($this->status, array('ok','readonly','graphonly'))) {
899       foreach (array('day','week','month','year') as $tframe) {
900         $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
901         if (isset($pconf['graph_url'])) {
902           $gURL = $pconf['graph_url'];
903           $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
904           $fname = str_replace('%p', $gmeta['filename'], $gURL);
905           if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
906         }
907         else {
908           $gURL = $gmeta['filename'];
909         }
910         $out .= '<div class="'.$tframe.'">';
911 //         $out .= '<p>'.nl2br($ret).'</p>';
912         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
913         $out .= '<img src="'.$gURL.'"';
914         $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
915         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
916         if (isset($gmeta['data']) && count($gmeta['data'])) {
917           $out .= '<table class="gdata">';
918           foreach ($gmeta['data'] as $field=>$gdata) {
919             $out .= '<tr><th>'.$field.'</th>';
920             foreach ($gdata as $gkey=>$gval) {
921               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
922             }
923             $out .= '</tr>';
924           }
925           $out .= '</table>';
926         }
927         if (isset($gmeta['var']) && count($gmeta['var'])) {
928           foreach ($gmeta['var'] as $gkey=>$gval) {
929             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
930           }
931         }
932         if (isset($gmeta['info']) && count($gmeta['info'])) {
933           foreach ($gmeta['info'] as $gval) {
934             $out .= '<p class="ginfo">'.$gval.'</p>';
935           }
936         }
937         $out .= '</div>';
938       }
939     }
940     else {
941       $out .= 'RRD error: status is "'.$this->status.'"';
942     }
943
944     $out .= $this->h_page_footer();
945     $out .= '</body></html>';
946   return $out;
947   }
948
949   function h_page_statsArray($pconf) {
950     // return array of stats to list on a page
951     $stats = array();
952     $snames = array(); $s_exclude = array(); $sfiles = array();
953     if (isset($pconf['index_ids'])) {
954       foreach (explode(',', $pconf['index_ids']) as $iid) {
955         if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
956         else { $snames[] = $iid; }
957       }
958     }
959     if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
960       foreach ($this->config_all as $iname=>$rinfo) {
961         if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
962             !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
963           $snames[] = $iname;
964         }
965       }
966     }
967     foreach ($snames as $iname) {
968       $newstat = array('name'=>$iname);
969       $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
970       if (is_array($this->config_all[$iname])) {
971         foreach ($this->config_all[$iname] as $key=>$val) {
972           if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
973         }
974       }
975       $stats[] = $newstat;
976     }
977     if (isset($pconf['scan_files']) && $pconf['scan_files']) {
978       $rrdfiles = glob('*.rrd');
979       foreach ($rrdfiles as $rrdfile) {
980         $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
981         if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
982           $stats[] = array('name'=>$iname, 'class'=>'scanfile');
983         }
984       }
985     }
986   return $stats;
987   }
988
989   function h_page_footer() {
990     // return generic page footer
991     $out = '<p class="footer">';
992     $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
993     $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
994     $out .= '</p>';
995   return $out;
996   }
997
998   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
999 }
1000 ?>