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