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