d67216516bfe661e9b7487314d016bdb234cbe6d
[php-utility-classes.git] / include / classes / rrdstat.php-class
1 <?php
2 // ************ RRD status class **************
3 class rrdstat {
4
5   var $rrd_file = null;
6
7   var $config_raw = null;
8   var $config_graph = null;
9   var $config_page = null;
10
11   var $rrd_fields = array();
12   var $rra_base = array();
13   var $rrd_step = 300;
14   var $rra_add_max = true;
15
16   var $status = 'unused';
17
18   function rrdstat($init_info = null) {
19     // ***** init RRD stat module *****
20     $this->set_def($init_info);
21
22     if (!is_null($this->rrd_file)) {
23       if (!is_writeable($this->rrd_file)) {
24         if (!file_exists($this->rrd_file)) {
25           if (touch($this->rrd_file)) { $this->create(); }
26           else { trigger_error('RRD file can not be created', E_USER_WARNING); }
27         }
28         else {
29           if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
30           else { trigger_error('RRD file is not readable', E_USER_WARNING); }
31         }
32       }
33       else {
34         $this->status = 'ok';
35       }
36     }
37   }
38
39   function set_def($init_info = null) {
40     if (is_array($init_info) && isset($init_info['file'])) {
41       // we have an array in the format we like to have
42       $iinfo =& $init_info;
43     }
44     else {
45       // we have something else (XML data?), try to generate the iinfo aray from it
46       $iinfo =& $init_info;
47     }
48
49     if (!isset($iinfo['file'])) { return false; }
50
51     $this->rrd_file = $iinfo['file'];
52
53     // fields (data sources, DS)
54     //  name - DS name
55     //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
56     //  heartbeat - if no sample recieved for that time, store UNKNOWN
57     //  min - U (unconstrained) or minimum value
58     //  max - U (unconstrained) or maximum value
59     //  update - this string will be fed into eval() for updating this field
60     if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
61       $this->rrd_fields = $iinfo['fields'];
62     }
63     else {
64       $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
65       $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
66     }
67
68
69     // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
70     //
71     // archives (RRAs):
72     // 600 samples of 5 minutes  (2 days and 2 hours)
73     // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
74     // 775 samples of 2 hours    (above + 50 days)
75     // 797 samples of 1 day      (above + 732 days, rounded up to 797)
76
77     $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
78
79     if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
80       $this->rra_base = $iinfo['rra_base'];
81     }
82     else {
83       $this->rra_base[] = array('step' => 1, 'rows' => 600);
84       $this->rra_base[] = array('step' => 6, 'rows' => 700);
85       $this->rra_base[] = array('step' => 24, 'rows' => 775);
86       $this->rra_base[] = array('step' => 288, 'rows' => 797);
87     }
88
89     $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
90
91     if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
92     if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
93     $this->config_raw = $iinfo;
94   }
95
96   function create() {
97     // create RRD file
98
99     // compose create command
100     $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
101     foreach ($this->rrd_fields as $ds) {
102       if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
103       if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
104       if (!isset($ds['min'])) { $ds['min'] = 'U'; }
105       if (!isset($ds['max'])) { $ds['max'] = 'U'; }
106       $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
107     }
108     foreach ($this->rra_base as $rra) {
109       if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
110       if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
111       if (!isset($rra['step'])) { $rra['step'] = 1; }
112       if (!isset($rra['rows'])) { $rra['rows'] = 600; }
113       $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
114     }
115     if ($this->rra_add_max) {
116       foreach ($this->rra_base as $rra) {
117         if (!isset($rra['cf'])) {
118           // only rows that have no CF set will be looked at here
119           $rra['cf'] = 'MAX';
120           if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
121           if (!isset($rra['step'])) { $rra['step'] = 1; }
122           if (!isset($rra['rows'])) { $rra['rows'] = 600; }
123           $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
124         }
125       }
126     }
127     $output = array(); $return_var = null;
128     exec($create_cmd, $output, $return_var);
129     if ($return_var) { trigger_error('rrd create returned with value '.$return_var, E_USER_WARNING); }
130     else { $this->status = 'ok'; }
131   }
132
133   function update($upArray = null) {
134     // feed new data into RRD
135     if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
136     $upvals = array();
137     foreach($this->rrd_fields as $ds) {
138       if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
139       elseif (isset($ds['update'])) { $val = eval($ds['update']); }
140       else { $val = null; }
141       $upvals[] = $val;
142     }
143     $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
144     $output = array(); $return_var = null;
145     exec($update_cmd, $output, $return_var);
146     if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
147   return ($return_var == 0);
148   }
149
150   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
151     // fetch data from a RRD
152     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
153
154     if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
155     if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
156     if (!is_numeric($end)) { $end = $this->last_update(); }
157     elseif ($end < 0) { $end += $this->last_update(); }
158     $end = intval($end/$resolution)*$resolution;
159     if (!is_numeric($start)) { $start = $end; }
160     elseif ($start < 0) { $start += $end; }
161     $start = intval($start/$resolution)*$resolution;
162
163     $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
164     $return = `$fetch_cmd 2>&1`;
165
166     if (strpos($return, 'ERROR') !== false) {
167       trigger_error('rrd fetch error: '.$return, E_USER_WARNING);
168       $fresult = false;
169     }
170     else {
171       $fresult = array();
172       $rows = explode("\n", $return);
173       $fields = preg_split('/\s+/', array_shift($rows));
174       if (array_shift($fields) == 'timestamp') {
175         $fresult[0] = $fields;
176         foreach ($rows as $row) {
177           if (strlen(trim($row))) {
178             $rvals = preg_split('/\s+/', $row);
179             $rtime = array_shift($rvals);
180             $rv_array = array();
181             foreach ($rvals as $key=>$rval) {
182               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
183             }
184             $fresult[$rtime] = $rv_array;
185           }
186         }
187       }
188     }
189   return $fresult;
190   }
191
192   function graph($timeframe = 'day', $sub = null, $extra = null) {
193     // create a RRD graph
194     static $gColors;
195     if (!isset($gColors)) {
196       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
197     }
198
199     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
200
201     // assemble configuration
202     $gconf = $this->config_graph;
203     if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
204       if (is_array($gconf)) { $gconf = array_merge($gconf, $this->config_raw['graph.'.$sub]); }
205       else { $gconf = $this->config_raw['graph.'.$sub]; }
206     }
207     if (is_array($extra)) {
208       if (is_array($gconf)) { $gconf = array_merge($gconf, $extra); }
209       else { $gconf = $extra; }
210     }
211
212     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
213       $format = $gconf['format']; $fmt_ext = '.svg';
214     }
215     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
216       $format = $gconf['format']; $fmt_ext = '.eps';
217     }
218     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
219       $format = $gconf['format']; $fmt_ext = '.pdf';
220     }
221     else {
222       $format = 'PNG'; $fmt_ext = '.png';
223     }
224
225     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
226     else { $fname = str_replace('.rrd', (is_null($sub)?'':'-%s').'-%t%f', $this->rrd_file); }
227     $fname = str_replace('%s', strval($sub), $fname);
228     $fname = str_replace('%t', $timeframe, $fname);
229     $fname = str_replace('%f', $fmt_ext, $fname);
230     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
231
232     $graphrows = array(); $gC = 0;
233     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
234
235     if ($timeframe == 'day') {
236       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
237       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
238       // vertical lines at day borders
239       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
240       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
241       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
242     }
243     elseif ($timeframe == 'week') {
244       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
245       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
246       // vertical lines at week borders
247       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
248       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
249     }
250     elseif ($timeframe == 'month') {
251       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
252       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
253       // vertical lines at month borders
254       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
255       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
256     }
257     elseif ($timeframe == 'year') {
258       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
259       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
260       // vertical lines at month borders
261       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
262       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
263     }
264     else {
265       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
266       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
267     }
268
269     if (isset($gconf['rows']) && count($gconf['rows'])) {
270       foreach ($gconf['rows'] as $erow) {
271         if (isset($erow['name']) && strlen($erow['name'])) {
272           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
273           $grow = array();
274           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
275           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
276           if ($grow['dType'] == 'DEF') {
277             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
278             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
279           }
280           else {
281             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
282           }
283           if (isset($erow['scale'])) {
284             $graphrows[] = $grow;
285             $grow = array();
286             $grow['dType'] = 'CDEF';
287             $grow['name'] = $erow['name'];
288             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
289           }
290           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
291           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
292           if ($gC >= count($gColors)) { $gC = 0; }
293           if (isset($erow['legend'])) {
294             $grow['legend'] = $erow['legend'];
295             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
296           }
297           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
298           $graphrows[] = $grow;
299         }
300       }
301     }
302     else {
303       foreach ($this->rrd_fields as $ds) {
304         $grow = array();
305         $grow['dType'] = 'DEF';
306         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
307         $grow['dsname'] = $ds['name'];
308         $grow['cf'] = 'AVERAGE';
309         if (isset($gconf['scale'])) {
310           $graphrows[] = $grow;
311           $grow = array();
312           $grow['dType'] = 'CDEF';
313           $grow['name'] = $ds['name'];
314           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
315         }
316         $grow['gType'] = ($ds['name']=='ds0')?'AREA':'LINE1';
317         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
318         $graphrows[] = $grow;
319       }
320     }
321
322     if (isset($gconf['special']) && count($gconf['special'])) {
323       foreach ($gconf['special'] as $crow) {
324         $srow = array();
325         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
326         if ($grow['sType'] != 'COMMENT') {
327           // XXX: use line below and remove cf var once we have rrdtol 1.2
328           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
329           $srow['name'] = $crow['name'];
330           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
331           if (isset($crow['cf'])) {
332             // XXX: use line below once we have rrdtol 1.2
333             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
334           }
335           elseif (isset($crow['rpn_expr'])) {
336             // XXX: does only work with rrdtool 1.2
337             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
338           }
339         }
340         $srow['text'] = isset($crow['text'])?$crow['text']:'';
341         $specialrows[] = $srow;
342       }
343     }
344     else {
345       foreach ($graphrows as $grow) {
346         if (isset($grow['gType']) && strlen($grow['gType'])) {
347           $textprefix = isset($grow['legend'])?$grow['legend']:$grow['name'];
348           // XXX: use lines below once we have rrdtol 1.2
349           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
350           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
351           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
352           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
353           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
354         }
355       }
356     }
357
358     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
359     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
360     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
361     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
362     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
363     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
364       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
365     }
366     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
367     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
368     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
369     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
370     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
371     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
372     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
373     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
374     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
375     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
376       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
377     }
378     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
379       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
380     }
381     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
382
383     foreach ($graphrows as $grow) {
384       if (isset($grow['dType']) && strlen($grow['dType'])) {
385         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
386         $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
387       }
388       if (isset($grow['gType']) && strlen($grow['gType'])) {
389         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
390         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
391         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
392         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
393         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
394         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
395       }
396     }
397
398     foreach ($specialrows as $srow) {
399       $addSpecial .= ' '.$srow['sType'];
400       // XXX: eliminate cf once we have rrdtool 1.2
401       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
402       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
403       $addSpecial .= ':'.$this->text_quote($srow['text']);
404     }
405
406     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
407     $return = `$graph_cmd 2>&1`;
408
409     if (strpos($return, 'ERROR') !== false) {
410       trigger_error('rrd graph error: '.$return, E_USER_WARNING);
411       $return = $graph_cmd."\n\n".$return;
412     }
413   return $return;
414   }
415
416   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
417     // create a simple (MRTG-like) HTML page and return it in a string
418     $basename = str_replace('.rrd', '', $this->rrd_file);
419
420     // assemble configuration
421     $pconf = $this->config_page;
422     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
423       if (is_array($pconf)) { $gconf = array_merge($pconf, $this->config_raw['page.'.$sub]); }
424       else { $pconf = $this->config_raw['page.'.$sub]; }
425     }
426     if (is_array($page_extras)) {
427       if (is_array($pconf)) { $pconf = array_merge($pconf, $page_extras); }
428       else { $pconf = $page_extras; }
429     }
430
431     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$basename.' - RRD statistics';
432     $gtitle = array();
433     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
434     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
435     $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
436     $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
437
438     $out = '<html><head>';
439     $out .= '<title>'.$ptitle.'</title>';
440     $out .= '<style>';
441     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
442     else {
443       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
444       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
445       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
446       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
447       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
448     }
449     if (isset($pconf['style'])) { $out .= $pconf['style']; }
450     $out .= '</style>';
451     $out .= '</head>';
452     $out .= '<body>';
453
454     $out .= '<h1>'.$ptitle.'</h1>';
455     if (!isset($pconf['show_update']) || $pconf['show_update']) {
456       $out .= '<p class="last_up">Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
457     }
458
459     if (in_array($this->status, array('ok','readonly'))) {
460       $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
461       foreach (array('day','week','month','year') as $tframe) {
462         $ret = $this->graph($tframe, $g_sub, $graph_extras);
463         if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
464         else { $graph_cmd = null; }
465         $grout = explode("\n",$ret);
466         $gmeta = array();
467         foreach ($grout as $gline) {
468           if (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
469             $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
470           }
471           elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
472             $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
473           }
474           elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
475             $gmeta['var'][$regs[1]] = $regs[2];
476           }
477           elseif (strlen(trim($gline))) {
478             $gmeta['info'][] = $gline;
479           }
480         }
481         $out .= '<div class="'.$tframe.'">';
482 //         $out .= '<p>'.nl2br($ret).'</p>';
483         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
484         $out .= '<img src="'.$basename.(!is_null($g_sub)?'-'.$g_sub:'').'-'.$tframe.'.png"';
485         $out .= ' alt="'.$basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
486         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
487         if (isset($gmeta['data']) && count($gmeta['data'])) {
488           $out .= '<table class="gdata">';
489           foreach ($gmeta['data'] as $field=>$gdata) {
490             $out .= '<tr><th>'.$field.'</th>';
491             foreach ($gdata as $gkey=>$gval) {
492               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
493             }
494             $out .= '</tr>';
495           }
496           $out .= '</table>';
497         }
498         if (isset($gmeta['var']) && count($gmeta['var'])) {
499           foreach ($gmeta['var'] as $gkey=>$gval) {
500             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
501           }
502         }
503         if (isset($gmeta['info']) && count($gmeta['info'])) {
504           foreach ($gmeta['info'] as $gval) {
505             $out .= '<p class="ginfo">'.$gval.'</p>';
506           }
507         }
508       }
509     }
510     else {
511       $out .= 'RRD error: status is "'.$this->status.'"';
512     }
513     $out .= '</div>';
514
515     $out .= '</body></html>';
516   return $out;
517   }
518
519   function last_update() {
520     // fetch time of last update in this RRD file
521     static $last_update;
522     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
523       $last_cmd = 'rrdtool last '.$this->rrd_file;
524       $return = trim(`$last_cmd 2>&1`);
525       $last_update = is_numeric($return)?$return:null;
526     }
527   return isset($last_update)?$last_update:null;
528   }
529
530   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
531 }
532 ?>