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