c1eed086555576cc5e904ccf885690fcd6e74212
[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'])) {
140         $val = null; $evalcode = null;
141         if (substr($ds['update'], 0, 4) == 'val:') {
142           $evalcode = 'print(trim('.substr($ds['update'], 4).'));';
143         }
144         elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
145           $snmphost = 'localhost'; $snmpcomm = 'public';
146           list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
147           $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
148           $ifnr = null;
149           foreach ($iflist as $ifdesc) {
150             if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
151           }
152           $oid = null;
153           if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
154           elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
155           if (!is_null($ifnr) && !is_null($oid)) {
156             $evalcode = 'print(trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)));';
157           }
158         }
159         else { $evalcode = $ds['update']; }
160         if (!is_null($evalcode)) {
161           ob_start();
162           eval($evalcode);
163           $val = ob_get_contents();
164           ob_end_clean();
165         }
166       }
167       else { $val = null; }
168       $upvals[] = is_null($val)?'U':$val;
169     }
170     $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
171     $output = array(); $return_var = null;
172     exec($update_cmd, $output, $return_var);
173     if ($return_var) { trigger_error('rrd update returned with value '.$return_var, E_USER_WARNING); }
174   return ($return_var == 0);
175   }
176
177   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
178     // fetch data from a RRD
179     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
180
181     if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
182     if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
183     if (!is_numeric($end)) { $end = $this->last_update(); }
184     elseif ($end < 0) { $end += $this->last_update(); }
185     $end = intval($end/$resolution)*$resolution;
186     if (!is_numeric($start)) { $start = $end; }
187     elseif ($start < 0) { $start += $end; }
188     $start = intval($start/$resolution)*$resolution;
189
190     $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
191     $return = `$fetch_cmd 2>&1`;
192
193     if (strpos($return, 'ERROR') !== false) {
194       trigger_error('rrd fetch error: '.$return, E_USER_WARNING);
195       $fresult = false;
196     }
197     else {
198       $fresult = array();
199       $rows = explode("\n", $return);
200       $fields = preg_split('/\s+/', array_shift($rows));
201       if (array_shift($fields) == 'timestamp') {
202         $fresult[0] = $fields;
203         foreach ($rows as $row) {
204           if (strlen(trim($row))) {
205             $rvals = preg_split('/\s+/', $row);
206             $rtime = array_shift($rvals);
207             $rv_array = array();
208             foreach ($rvals as $key=>$rval) {
209               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
210             }
211             $fresult[$rtime] = $rv_array;
212           }
213         }
214       }
215     }
216   return $fresult;
217   }
218
219   function graph($timeframe = 'day', $sub = null, $extra = null) {
220     // create a RRD graph
221     static $gColors;
222     if (!isset($gColors)) {
223       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
224     }
225
226     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
227
228     // assemble configuration
229     $gconf = $this->config_graph;
230     if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
231       if (is_array($gconf)) { $gconf = array_merge($gconf, $this->config_raw['graph.'.$sub]); }
232       else { $gconf = $this->config_raw['graph.'.$sub]; }
233     }
234     if (is_array($extra)) {
235       if (is_array($gconf)) { $gconf = array_merge($gconf, $extra); }
236       else { $gconf = $extra; }
237     }
238
239     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
240       $format = $gconf['format']; $fmt_ext = '.svg';
241     }
242     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
243       $format = $gconf['format']; $fmt_ext = '.eps';
244     }
245     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
246       $format = $gconf['format']; $fmt_ext = '.pdf';
247     }
248     else {
249       $format = 'PNG'; $fmt_ext = '.png';
250     }
251
252     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
253     else { $fname = str_replace('.rrd', (is_null($sub)?'':'-%s').'-%t%f', $this->rrd_file); }
254     $fname = str_replace('%s', strval($sub), $fname);
255     $fname = str_replace('%t', $timeframe, $fname);
256     $fname = str_replace('%f', $fmt_ext, $fname);
257     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
258
259     $graphrows = array(); $gC = 0;
260     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
261
262     if ($timeframe == 'day') {
263       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
264       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
265       // vertical lines at day borders
266       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
267       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
268       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
269     }
270     elseif ($timeframe == 'week') {
271       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
272       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
273       // vertical lines at week borders
274       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
275       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
276     }
277     elseif ($timeframe == 'month') {
278       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
279       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
280       // vertical lines at month borders
281       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
282       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
283     }
284     elseif ($timeframe == 'year') {
285       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
286       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
287       // vertical lines at month borders
288       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01')).'#FF0000';
289       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01').' -1 year').'#FF0000';
290     }
291     else {
292       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
293       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
294     }
295
296     if (isset($gconf['rows']) && count($gconf['rows'])) {
297       foreach ($gconf['rows'] as $erow) {
298         if (isset($erow['name']) && strlen($erow['name'])) {
299           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
300           $grow = array();
301           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
302           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
303           if ($grow['dType'] == 'DEF') {
304             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
305             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
306           }
307           else {
308             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
309           }
310           if (isset($erow['scale'])) {
311             $graphrows[] = $grow;
312             $grow = array();
313             $grow['dType'] = 'CDEF';
314             $grow['name'] = $erow['name'];
315             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
316           }
317           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
318           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
319           if ($gC >= count($gColors)) { $gC = 0; }
320           if (isset($erow['legend'])) {
321             $grow['legend'] = $erow['legend'];
322             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
323           }
324           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
325           $graphrows[] = $grow;
326         }
327       }
328     }
329     else {
330       foreach ($this->rrd_fields as $ds) {
331         $grow = array();
332         $grow['dType'] = 'DEF';
333         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
334         $grow['dsname'] = $ds['name'];
335         $grow['cf'] = 'AVERAGE';
336         if (isset($gconf['scale'])) {
337           $graphrows[] = $grow;
338           $grow = array();
339           $grow['dType'] = 'CDEF';
340           $grow['name'] = $ds['name'];
341           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
342         }
343         $grow['gType'] = ($ds['name']=='ds0')?'AREA':'LINE1';
344         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
345         $graphrows[] = $grow;
346       }
347     }
348
349     if (isset($gconf['special']) && count($gconf['special'])) {
350       foreach ($gconf['special'] as $crow) {
351         $srow = array();
352         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
353         if ($grow['sType'] != 'COMMENT') {
354           // XXX: use line below and remove cf var once we have rrdtol 1.2
355           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
356           $srow['name'] = $crow['name'];
357           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
358           if (isset($crow['cf'])) {
359             // XXX: use line below once we have rrdtol 1.2
360             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
361           }
362           elseif (isset($crow['rpn_expr'])) {
363             // XXX: does only work with rrdtool 1.2
364             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
365           }
366         }
367         $srow['text'] = isset($crow['text'])?$crow['text']:'';
368         $specialrows[] = $srow;
369       }
370     }
371     else {
372       foreach ($graphrows as $grow) {
373         if (isset($grow['gType']) && strlen($grow['gType'])) {
374           $textprefix = isset($grow['legend'])?$grow['legend']:$grow['name'];
375           // XXX: use lines below once we have rrdtol 1.2
376           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
377           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
378           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
379           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
380           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
381         }
382       }
383     }
384
385     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
386     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
387     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
388     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
389     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
390     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
391       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
392     }
393     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
394     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
395     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
396     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
397     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
398     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
399     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
400     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
401     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
402     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
403       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
404     }
405     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
406       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
407     }
408     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
409
410     foreach ($graphrows as $grow) {
411       if (isset($grow['dType']) && strlen($grow['dType'])) {
412         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
413         $gDefs .= ($grow['dType']=='DEF')?$this->rrd_file.':'.$grow['dsname'].':'.$grow['cf']:$grow['rpn_expr'];
414       }
415       if (isset($grow['gType']) && strlen($grow['gType'])) {
416         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
417         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
418         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
419         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
420         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
421         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
422       }
423     }
424
425     foreach ($specialrows as $srow) {
426       $addSpecial .= ' '.$srow['sType'];
427       // XXX: eliminate cf once we have rrdtool 1.2
428       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
429       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
430       $addSpecial .= ':'.$this->text_quote($srow['text']);
431     }
432
433     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
434     $return = `$graph_cmd 2>&1`;
435
436     if (strpos($return, 'ERROR') !== false) {
437       trigger_error('rrd graph error: '.$return, E_USER_WARNING);
438       $return = $graph_cmd."\n\n".$return;
439     }
440   return $return;
441   }
442
443   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
444     // create a simple (MRTG-like) HTML page and return it in a string
445     $basename = str_replace('.rrd', '', $this->rrd_file);
446
447     // assemble configuration
448     $pconf = $this->config_page;
449     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
450       if (is_array($pconf)) { $gconf = array_merge($pconf, $this->config_raw['page.'.$sub]); }
451       else { $pconf = $this->config_raw['page.'.$sub]; }
452     }
453     if (is_array($page_extras)) {
454       if (is_array($pconf)) { $pconf = array_merge($pconf, $page_extras); }
455       else { $pconf = $page_extras; }
456     }
457
458     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$basename.' - RRD statistics';
459     $gtitle = array();
460     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
461     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
462     $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
463     $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
464
465     $out = '<html><head>';
466     $out .= '<title>'.$ptitle.'</title>';
467     $out .= '<style>';
468     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
469     else {
470       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
471       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
472       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
473       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
474       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
475       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
476     }
477     if (isset($pconf['style'])) { $out .= $pconf['style']; }
478     $out .= '</style>';
479     $out .= '</head>';
480     $out .= '<body>';
481
482     $out .= '<h1>'.$ptitle.'</h1>';
483     if (!isset($pconf['show_update']) || $pconf['show_update']) {
484       $out .= '<p class="last_up">Last Update: '.date('Y-m-d H:i:s', $this->last_update()).'</p>';
485     }
486
487     if (in_array($this->status, array('ok','readonly'))) {
488       $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
489       foreach (array('day','week','month','year') as $tframe) {
490         $ret = $this->graph($tframe, $g_sub, $graph_extras);
491         if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
492         else { $graph_cmd = null; }
493         $grout = explode("\n",$ret);
494         $gmeta = array();
495         foreach ($grout as $gline) {
496           if (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
497             $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
498           }
499           elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
500             $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
501           }
502           elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
503             $gmeta['var'][$regs[1]] = $regs[2];
504           }
505           elseif (strlen(trim($gline))) {
506             $gmeta['info'][] = $gline;
507           }
508         }
509         $out .= '<div class="'.$tframe.'">';
510 //         $out .= '<p>'.nl2br($ret).'</p>';
511         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
512         $out .= '<img src="'.$basename.(!is_null($g_sub)?'-'.$g_sub:'').'-'.$tframe.'.png"';
513         $out .= ' alt="'.$basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
514         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
515         if (isset($gmeta['data']) && count($gmeta['data'])) {
516           $out .= '<table class="gdata">';
517           foreach ($gmeta['data'] as $field=>$gdata) {
518             $out .= '<tr><th>'.$field.'</th>';
519             foreach ($gdata as $gkey=>$gval) {
520               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
521             }
522             $out .= '</tr>';
523           }
524           $out .= '</table>';
525         }
526         if (isset($gmeta['var']) && count($gmeta['var'])) {
527           foreach ($gmeta['var'] as $gkey=>$gval) {
528             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
529           }
530         }
531         if (isset($gmeta['info']) && count($gmeta['info'])) {
532           foreach ($gmeta['info'] as $gval) {
533             $out .= '<p class="ginfo">'.$gval.'</p>';
534           }
535         }
536       }
537     }
538     else {
539       $out .= 'RRD error: status is "'.$this->status.'"';
540     }
541     $out .= '</div>';
542
543     $out .= '<p class="footer">';
544     $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
545     $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
546     $out .= '</p>';
547
548     $out .= '</body></html>';
549   return $out;
550   }
551
552   function last_update() {
553     // fetch time of last update in this RRD file
554     static $last_update;
555     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
556       $last_cmd = 'rrdtool last '.$this->rrd_file;
557       $return = trim(`$last_cmd 2>&1`);
558       $last_update = is_numeric($return)?$return:null;
559     }
560   return isset($last_update)?$last_update:null;
561   }
562
563   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
564 }
565 ?>