retrieve further info from graph and use it for display in web page
[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', $special = 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($special) && is_array($this->config_raw['graph'][$special])) {
204       if (is_array($gconf)) { $gconf = array_merge($gconf, $this->config_raw['graph'][$special]); }
205       else { $gconf = $this->config_raw['graph'][$special]; }
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', '-%t%f', $this->rrd_file); }
227     $fname = str_replace('%t', $timeframe, $fname);
228     $fname = str_replace('%f', $fmt_ext, $fname);
229     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
230
231     $graphrows = array(); $gC = 0;
232     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
233
234     if ($timeframe == 'day') {
235       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
236       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
237       // vertical lines at day borders
238       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
239       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
240       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
241     }
242     elseif ($timeframe == 'week') {
243       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
244       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
245       // vertical lines at week borders
246       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
247       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
248     }
249     elseif ($timeframe == 'month') {
250       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
251       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
252       // vertical lines at month borders
253       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
254       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
255     }
256     elseif ($timeframe == 'year') {
257       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
258       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
259       // vertical lines at month borders
260       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
261       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
262     }
263     else {
264       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
265       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
266     }
267
268     if (isset($gconf['rows']) && count($gconf['rows'])) {
269       foreach ($gconf['rows'] as $erow) {
270         if (isset($erow['name']) && strlen($erow['name'])) {
271           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
272           $grow = array();
273           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
274           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
275           if ($grow['dType'] == 'DEF') {
276             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
277             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
278           }
279           else {
280             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
281           }
282           if (isset($erow['scale'])) {
283             $graphrows[] = $grow;
284             $grow = array();
285             $grow['dType'] = 'CDEF';
286             $grow['name'] = $erow['name'];
287             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
288           }
289           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
290           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
291           if ($gC >= count($gColors)) { $gC = 0; }
292           if (isset($erow['legend'])) {
293             $grow['legend'] = $erow['legend'];
294             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
295           }
296           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
297           $graphrows[] = $grow;
298         }
299       }
300     }
301     else {
302       foreach ($this->rrd_fields as $ds) {
303         $grow = array();
304         $grow['dType'] = 'DEF';
305         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
306         $grow['dsname'] = $ds['name'];
307         $grow['cf'] = 'AVERAGE';
308         if (isset($gconf['scale'])) {
309           $graphrows[] = $grow;
310           $grow = array();
311           $grow['dType'] = 'CDEF';
312           $grow['name'] = $ds['name'];
313           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
314         }
315         $grow['gType'] = ($ds['name']=='ds0')?'AREA':'LINE1';
316         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
317         $graphrows[] = $grow;
318       }
319     }
320
321     if (isset($gconf['special']) && count($gconf['special'])) {
322       foreach ($gconf['special'] as $crow) {
323         $srow = array();
324         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
325         if ($grow['sType'] != 'COMMENT') {
326           // XXX: use line below and remove cf var once we have rrdtol 1.2
327           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
328           $srow['name'] = $crow['name'];
329           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
330           if (isset($crow['cf'])) {
331             // XXX: use line below once we have rrdtol 1.2
332             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
333           }
334           elseif (isset($crow['rpn_expr'])) {
335             // XXX: does only work with rrdtool 1.2
336             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
337           }
338         }
339         $srow['text'] = isset($crow['text'])?$crow['text']:'';
340         $specialrows[] = $srow;
341       }
342     }
343     else {
344       foreach ($graphrows as $grow) {
345         if (isset($grow['gType']) && strlen($grow['gType'])) {
346           $textprefix = isset($grow['legend'])?$grow['legend']:$grow['name'];
347           // XXX: use lines below once we have rrdtol 1.2
348           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
349           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
350           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
351           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
352           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
353         }
354       }
355     }
356
357     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
358     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
359     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
360     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
361     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
362     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
363       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
364     }
365     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
366     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
367     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
368     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
369     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
370     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
371     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
372     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
373     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
374     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
375       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
376     }
377     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
378       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
379     }
380     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
381
382     foreach ($graphrows as $grow) {
383       if (isset($grow['dType']) && strlen($grow['dType'])) {
384         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
385         $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
386       }
387       if (isset($grow['gType']) && strlen($grow['gType'])) {
388         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
389         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
390         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
391         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
392         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
393         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
394       }
395     }
396
397     foreach ($specialrows as $srow) {
398       $addSpecial .= ' '.$srow['sType'];
399       // XXX: eliminate cf once we have rrdtool 1.2
400       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
401       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
402       $addSpecial .= ':'.$this->text_quote($srow['text']);
403     }
404
405     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
406     $return = `$graph_cmd 2>&1`;
407
408     if (strpos($return, 'ERROR') !== false) {
409       trigger_error('rrd graph error: '.$return, E_USER_WARNING);
410       $return = $graph_cmd."\n\n".$return;
411     }
412   return $return;
413   }
414
415   function simple_html($page_extras = null, $graph_extras = null) {
416     // create a simple (MRTG-like) HTML page and return it in a string
417     $basename = str_replace('.rrd', '', $this->rrd_file);
418
419     // assemble configuration
420     $pconf = $this->config_page;
421     if (is_array($page_extras)) {
422       if (is_array($pconf)) { $pconf = array_merge($pconf, $page_extras); }
423       else { $pconf = $page_extras; }
424     }
425
426     $ptitle = $basename.' - RRD statistics';
427     $gtitle = array();
428     $gtitle['day'] = 'Day overview (scaling 5 minutes)';
429     $gtitle['week'] = 'Week overview (scaling 30 minutes)';
430     $gtitle['month'] = 'Month overview (scaling 2 hours)';
431     $gtitle['year'] = 'Year overview (scaling 1 day)';
432
433     $out = '<html><head>';
434     $out .= '<title>'.$ptitle.'</title>';
435     $out .= '<style>';
436     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
437     else {
438       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
439       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
440       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
441       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
442       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
443     }
444     if (isset($pconf['style'])) { $out .= $pconf['style']; }
445     $out .= '</style>';
446     $out .= '</head>';
447     $out .= '<body>';
448
449     $out .= '<h1>'.$ptitle.'</h1>';
450     $out .= '<p class="last_up">Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
451
452     if (in_array($this->status, array('ok','readonly'))) {
453       foreach (array('day','week','month','year') as $tframe) {
454         $ret = $this->graph($tframe, null, $graph_extras);
455         if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
456         else { $graph_cmd = null; }
457         $grout = explode("\n",$ret);
458         $gmeta = array();
459         foreach ($grout as $gline) {
460           if (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
461             $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
462           }
463           elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
464             $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
465           }
466           elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
467             $gmeta['var'][$regs[1]] = $regs[2];
468           }
469           elseif (strlen(trim($gline))) {
470             $gmeta['info'][] = $gline;
471           }
472         }
473         $out .= '<div class="'.$tframe.'">';
474 //         $out .= '<p>'.nl2br($ret).'</p>';
475         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
476         $out .= '<img src="'.$basename.'-'.$tframe.'.png"';
477         $out .= ' alt="'.$basename.' - '.$tframe.'" class="rrdgraph"';
478         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
479         if (isset($gmeta['data']) && count($gmeta['data'])) {
480           $out .= '<table class="gdata">';
481           foreach ($gmeta['data'] as $field=>$gdata) {
482             $out .= '<tr><th>'.$field.'</th>';
483             foreach ($gdata as $gkey=>$gval) {
484               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
485             }
486             $out .= '</tr>';
487           }
488           $out .= '</table>';
489         }
490         if (isset($gmeta['var']) && count($gmeta['var'])) {
491           foreach ($gmeta['var'] as $gkey=>$gval) {
492             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
493           }
494         }
495         if (isset($gmeta['info']) && count($gmeta['info'])) {
496           foreach ($gmeta['info'] as $gval) {
497             $out .= '<p class="ginfo">'.$gval.'</p>';
498           }
499         }
500       }
501     }
502     else {
503       $out .= 'RRD error: status is "'.$this->status.'"';
504     }
505     $out .= '</div>';
506
507     $out .= '</body></html>';
508   return $out;
509   }
510
511   function last_update() {
512     // fetch time of last update in this RRD file
513     static $last_update;
514     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
515       $last_cmd = 'rrdtool last '.$this->rrd_file;
516       $return = trim(`$last_cmd 2>&1`);
517       $last_update = is_numeric($return)?$return:null;
518     }
519   return isset($last_update)?$last_update:null;
520   }
521
522   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
523 }
524 ?>