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