2fc1de17c7b02186a494e3fcab683a971bf4a949
[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_all = null;
9   var $config_raw = null;
10   var $config_graph = null;
11   var $config_page = null;
12
13   var $rrd_fields = array();
14   var $rra_base = array();
15   var $rrd_step = 300;
16   var $rra_add_max = true;
17
18   var $status = 'unused';
19
20   function rrdstat($rrdconfig, $conf_id = null) {
21     // ***** init RRD stat module *****
22     $this->set_def($rrdconfig, $conf_id);
23
24     if (($this->status == 'unused') && !is_null($this->rrd_file)) {
25       if (!is_writeable($this->rrd_file)) {
26         if (!file_exists($this->rrd_file)) {
27           if (@touch($this->rrd_file)) { $this->create(); }
28           else { trigger_error('RRD file can not be created', E_USER_WARNING); }
29         }
30         else {
31           if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
32           else { trigger_error('RRD file is not readable', E_USER_WARNING); }
33         }
34       }
35       else {
36         $this->status = 'ok';
37       }
38     }
39   }
40
41   function set_def($rrdconfig, $conf_id = null) {
42     if (is_array($rrdconfig)) {
43       // we have an array in the format we like to have
44       $complete_conf =& $rrdconfig;
45     }
46     else {
47       // we have something else (XML data?), try to generate the iinfo aray from it
48       $complete_conf =& $rrdconfig;
49     }
50
51     if (!is_null($conf_id)) {
52       $iinfo = isset($complete_conf[$conf_id])?$complete_conf[$conf_id]:array();
53       if (isset($complete_conf['*'])) {
54         $iinfo = (array)$iinfo + (array)$complete_conf['*'];
55         if (isset($complete_conf['*']['graph'])) { $iinfo['graph'] = (array)$iinfo['graph'] + (array)$complete_conf['*']['graph']; }
56         if (isset($complete_conf['*']['page'])) { $iinfo['page'] = (array)$iinfo['page'] + (array)$complete_conf['*']['page']; }
57       }
58     }
59     else {
60       $iinfo = $complete_conf;
61     }
62
63     if (isset($iinfo['graph-only']) && $iinfo['graph-only'] && !is_null($conf_id)) {
64       $this->basename = $conf_id;
65       $this->status = 'graphonly';
66     }
67     elseif (isset($iinfo['file'])) {
68       $this->rrd_file = $iinfo['file'];
69       $this->basename = (substr($this->rrd_file, -4) == '.rrd')?substr($this->rrd_file, 0, -4):$this->rrd_file;
70     }
71     else {
72       $this->basename = !is_null($conf_id)?$conf_id:'xxx.unknown';
73     }
74
75     if (isset($iinfo['file'])) {
76       // fields (data sources, DS)
77       //  name - DS name
78       //  type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
79       //  heartbeat - if no sample recieved for that time, store UNKNOWN
80       //  min - U (unconstrained) or minimum value
81       //  max - U (unconstrained) or maximum value
82       //  update - this string will be fed into eval() for updating this field
83       if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
84         $this->rrd_fields = $iinfo['fields'];
85       }
86       else {
87         $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
88         $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
89       }
90
91
92       // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
93       //
94       // archives (RRAs):
95       // 600 samples of 5 minutes  (2 days and 2 hours)
96       // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
97       // 775 samples of 2 hours    (above + 50 days)
98       // 797 samples of 1 day      (above + 732 days, rounded up to 797)
99
100       $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
101
102       if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
103         $this->rra_base = $iinfo['rra_base'];
104       }
105       else {
106         $this->rra_base[] = array('step' => 1, 'rows' => 600);
107         $this->rra_base[] = array('step' => 6, 'rows' => 700);
108         $this->rra_base[] = array('step' => 24, 'rows' => 775);
109         $this->rra_base[] = array('step' => 288, 'rows' => 797);
110       }
111
112       $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
113     }
114
115     if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
116     if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
117     $this->config_raw = $iinfo;
118     $this->config_all = $complete_conf;
119   }
120
121   function create() {
122     // create RRD file
123
124     // compose create command
125     $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
126     foreach ($this->rrd_fields as $ds) {
127       if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
128       if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
129       if (!isset($ds['min'])) { $ds['min'] = 'U'; }
130       if (!isset($ds['max'])) { $ds['max'] = 'U'; }
131       $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
132     }
133     foreach ($this->rra_base as $rra) {
134       if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
135       if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
136       if (!isset($rra['step'])) { $rra['step'] = 1; }
137       if (!isset($rra['rows'])) { $rra['rows'] = 600; }
138       $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
139     }
140     if ($this->rra_add_max) {
141       foreach ($this->rra_base as $rra) {
142         if (!isset($rra['cf'])) {
143           // only rows that have no CF set will be looked at here
144           $rra['cf'] = 'MAX';
145           if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
146           if (!isset($rra['step'])) { $rra['step'] = 1; }
147           if (!isset($rra['rows'])) { $rra['rows'] = 600; }
148           $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
149         }
150       }
151     }
152     $return = `$create_cmd 2>&1`;
153     if (strpos($return, 'ERROR') !== false) {
154       trigger_error($this->rrd_file.' - rrd create error: '.$return, E_USER_WARNING);
155     }
156     else { $this->status = 'ok'; }
157   }
158
159   function update($upArray = null) {
160     // feed new data into RRD
161     if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return 1; }
162     $upvals = array();
163     if (isset($this->config_raw['update'])) {
164       $evalcode = $this->config_raw['update'];
165       if (!is_null($evalcode)) {
166         ob_start();
167         eval($evalcode);
168         $ret = ob_get_contents();
169         if (strlen($ret)) { $upvals = explode("\n", $ret); }
170         ob_end_clean();
171       }
172       $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
173       array_walk($upvals, $walkfunc);
174     }
175     else {
176       foreach ($this->rrd_fields as $ds) {
177         if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
178         elseif (isset($ds['update'])) {
179           $val = null; $evalcode = null;
180           if (substr($ds['update'], 0, 4) == 'val:') {
181             $evalcode = 'print(trim('.substr($ds['update'], 4).'));';
182           }
183           elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
184             $snmphost = 'localhost'; $snmpcomm = 'public';
185             list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
186             $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
187             $ifnr = null;
188             foreach ($iflist as $ifdesc) {
189               if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
190             }
191             $oid = null;
192             if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
193             elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
194             if (!is_null($ifnr) && !is_null($oid)) {
195               $evalcode = 'print(trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)));';
196             }
197           }
198           else { $evalcode = $ds['update']; }
199           if (!is_null($evalcode)) {
200             ob_start();
201             eval($evalcode);
202             $val = ob_get_contents();
203             ob_end_clean();
204           }
205         }
206         else { $val = null; }
207         $upvals[] = is_null($val)?'U':$val;
208       }
209     }
210     $return = null;
211     if (count($upvals)) {
212       $update_cmd = 'rrdtool update '.$this->rrd_file.' N:'.implode(':', $upvals);
213       $return = `$update_cmd 2>&1`;
214     }
215
216     if (strpos($return, 'ERROR') !== false) {
217       trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
218       $success = false;
219     }
220     else { $success = true; }
221   return ($return_var == 0);
222   }
223
224   function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
225     // fetch data from a RRD
226     if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
227
228     if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
229     if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
230     if (!is_numeric($end)) { $end = $this->last_update(); }
231     elseif ($end < 0) { $end += $this->last_update(); }
232     $end = intval($end/$resolution)*$resolution;
233     if (!is_numeric($start)) { $start = $end; }
234     elseif ($start < 0) { $start += $end; }
235     $start = intval($start/$resolution)*$resolution;
236
237     $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
238     $return = `$fetch_cmd 2>&1`;
239
240     if (strpos($return, 'ERROR') !== false) {
241       trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
242       $fresult = false;
243     }
244     else {
245       $fresult = array();
246       $rows = explode("\n", $return);
247       $fields = preg_split('/\s+/', array_shift($rows));
248       if (array_shift($fields) == 'timestamp') {
249         $fresult[0] = $fields;
250         foreach ($rows as $row) {
251           if (strlen(trim($row))) {
252             $rvals = preg_split('/\s+/', $row);
253             $rtime = array_shift($rvals);
254             $rv_array = array();
255             foreach ($rvals as $key=>$rval) {
256               $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
257             }
258             $fresult[$rtime] = $rv_array;
259           }
260         }
261       }
262     }
263   return $fresult;
264   }
265
266   function last_update() {
267     // fetch time of last update in this RRD file
268     static $last_update;
269     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
270       $last_cmd = 'rrdtool last '.$this->rrd_file;
271       $return = trim(`$last_cmd 2>&1`);
272       $last_update = is_numeric($return)?$return:null;
273     }
274   return isset($last_update)?$last_update:null;
275   }
276
277   function graph($timeframe = 'day', $sub = null, $extra = null) {
278     // create a RRD graph
279     static $gColors;
280     if (!isset($gColors)) {
281       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
282     }
283
284     if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
285
286     // assemble configuration
287     $gconf = (array)$extra;
288     if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
289       $gconf = $gconf + $this->config_raw['graph.'.$sub];
290     }
291     $gconf = $gconf + (array)$this->config_graph;
292
293     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
294       $format = $gconf['format']; $fmt_ext = '.svg';
295     }
296     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
297       $format = $gconf['format']; $fmt_ext = '.eps';
298     }
299     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
300       $format = $gconf['format']; $fmt_ext = '.pdf';
301     }
302     else {
303       $format = 'PNG'; $fmt_ext = '.png';
304     }
305
306     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
307     else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
308     $fname = str_replace('%s', strval($sub), $fname);
309     $fname = str_replace('%t', $timeframe, $fname);
310     $fname = str_replace('%f', $fmt_ext, $fname);
311     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
312     if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
313     $fname = str_replace('//', '/', $fname);
314
315     $graphrows = array(); $gC = 0;
316     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
317
318     if ($timeframe == 'day') {
319       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
320       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
321       // vertical lines at day borders
322       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
323       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
324       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
325     }
326     elseif ($timeframe == 'week') {
327       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
328       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
329       // vertical lines at week borders
330       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
331       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
332     }
333     elseif ($timeframe == 'month') {
334       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
335       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
336       // vertical lines at month borders
337       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
338       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
339     }
340     elseif ($timeframe == 'year') {
341       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
342       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
343       // vertical lines at month borders
344       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
345       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
346     }
347     else {
348       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
349       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
350     }
351
352     if (isset($gconf['rows']) && count($gconf['rows'])) {
353       foreach ($gconf['rows'] as $erow) {
354         if (isset($erow['name']) && strlen($erow['name'])) {
355           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
356           $grow = array();
357           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
358           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
359           if ($grow['dType'] == 'DEF') {
360             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
361             if (isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
362             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
363           }
364           else {
365             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
366           }
367           if (isset($erow['scale'])) {
368             $graphrows[] = $grow;
369             $grow = array();
370             $grow['dType'] = 'CDEF';
371             $grow['name'] = $erow['name'];
372             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
373           }
374           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
375           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
376           if ($gC >= count($gColors)) { $gC = 0; }
377           if (isset($erow['legend'])) {
378             $grow['legend'] = $erow['legend'];
379             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
380           }
381           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
382           if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
383           $graphrows[] = $grow;
384         }
385       }
386     }
387     else {
388       foreach ($this->rrd_fields as $key=>$ds) {
389         $grow = array();
390         $grow['dType'] = 'DEF';
391         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
392         $grow['dsname'] = $ds['name'];
393         $grow['cf'] = 'AVERAGE';
394         if (isset($gconf['scale'])) {
395           $graphrows[] = $grow;
396           $grow = array();
397           $grow['dType'] = 'CDEF';
398           $grow['name'] = $ds['name'];
399           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
400         }
401         $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
402         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
403         $graphrows[] = $grow;
404       }
405     }
406
407     if (isset($gconf['special']) && count($gconf['special'])) {
408       foreach ($gconf['special'] as $crow) {
409         $srow = array();
410         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
411         if ($grow['sType'] != 'COMMENT') {
412           // XXX: use line below and remove cf var once we have rrdtol 1.2
413           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
414           $srow['name'] = $crow['name'];
415           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
416           if (isset($crow['cf'])) {
417             // XXX: use line below once we have rrdtol 1.2
418             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
419           }
420           elseif (isset($crow['rpn_expr'])) {
421             // XXX: does only work with rrdtool 1.2
422             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
423           }
424         }
425         $srow['text'] = isset($crow['text'])?$crow['text']:'';
426         $specialrows[] = $srow;
427       }
428     }
429     else {
430       foreach ($graphrows as $grow) {
431         if (isset($grow['gType']) && strlen($grow['gType'])) {
432           $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
433           // XXX: use lines below once we have rrdtol 1.2
434           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
435           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
436           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
437           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
438           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
439         }
440       }
441     }
442
443     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
444     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
445     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
446     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
447     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
448     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
449       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
450     }
451     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
452     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
453     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
454     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
455     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
456     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
457     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
458     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
459     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
460     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
461       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
462     }
463     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
464       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
465     }
466     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
467
468     foreach ($graphrows as $grow) {
469       if (isset($grow['dType']) && strlen($grow['dType'])) {
470         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
471         if ($grow['dType'] == 'DEF') {
472           $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
473           $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
474         }
475         else { $gDefs .= $grow['rpn_expr']; }
476       }
477       if (isset($grow['gType']) && strlen($grow['gType'])) {
478         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
479         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
480         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
481         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
482         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
483         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
484       }
485     }
486
487     foreach ($specialrows as $srow) {
488       $addSpecial .= ' '.$srow['sType'];
489       // XXX: eliminate cf once we have rrdtool 1.2
490       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
491       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
492       $addSpecial .= ':'.$this->text_quote($srow['text']);
493     }
494
495     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
496     $return = `$graph_cmd 2>&1`;
497
498     if (strpos($return, 'ERROR') !== false) {
499       trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
500       $return = $graph_cmd."\n\n".$return;
501     }
502     $return = 'file:'.$fname."\n".$return;
503   return $return;
504   }
505
506   function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
507     // create a RRD graph and return meta info as a ready-to-use array
508     $gmeta = array('filename'=>null);
509     $ret = $this->graph($timeframe, $sub, $extra);
510     if (strpos($ret, "\n\n") !== false) { $gmeta['graph_cmd'] = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
511     else { $gmeta['graph_cmd'] = null; }
512     $grout = explode("\n", $ret);
513     foreach ($grout as $gline) {
514       if (preg_match('/^file:(.+)$/', $gline, $regs)) {
515         $gmeta['filename'] = $regs[1];
516       }
517       elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
518         $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
519       }
520       elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
521         $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
522       }
523       elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
524         $gmeta['var'][$regs[1]] = $regs[2];
525       }
526       elseif (strlen(trim($gline))) {
527         $gmeta['info'][] = $gline;
528       }
529     }
530     if (is_null($gmeta['filename'])) {
531       $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
532     }
533   return $gmeta;
534   }
535
536   function page($sub = null, $page_extras = null, $graph_extras = null) {
537     // create a (HTML) page and return it in a string
538
539     // assemble configuration
540     $pconf = (array)$page_extras;
541     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
542       $pconf = $pconf + $this->config_raw['page.'.$sub];
543     }
544     $pconf = $pconf + (array)$this->config_page;
545
546     $return = null;
547     switch ($pconf['type']) {
548       case 'index':
549         $return = $this->page_index($pconf);
550         break;
551       case 'overview':
552         $return = $this->page_overview($pconf, $graph_extras);
553         break;
554       case 'simple':
555       default:
556         $return = $this->page_simple($pconf, $graph_extras);
557         break;
558     }
559   return $return;
560   }
561
562   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
563     // create a simple (MRTG-like) HTML page and return it in a string
564     // XXX: this is here temporarily for compat only, it's preferred to use page()!
565
566     // assemble configuration
567     $pconf = (array)$page_extras;
568     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
569       $pconf = $pconf + $this->config_raw['page.'.$sub];
570     }
571     $pconf = $pconf + (array)$this->config_page;
572
573   return $this->page_simple($pconf, $graph_extras);
574   }
575
576   function page_index($pconf) {
577     // create a bare, very simple index list HTML page and return it in a string
578
579     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics index';
580
581     $out = '<html><head>';
582     $out .= '<title>'.$ptitle.'</title>';
583     $out .= '<style>';
584     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
585     else {
586       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
587       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
588       $out .= 'li.scanfile { font-style: italic; }';
589     }
590     if (isset($pconf['style'])) { $out .= $pconf['style']; }
591     $out .= '</style>';
592     $out .= '</head>';
593     $out .= '<body>';
594
595     $out .= '<h1>'.$ptitle.'</h1>';
596     if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
597       $out .= '<p class="intro">'.$pconf['text_intro'].'</p>';
598     }
599     elseif (!isset($pconf['text_intro'])) {
600       $out .= '<p class="intro">The following RRD stats are available:</p>';
601     }
602
603     $stats = $this->h_page_statsArray($pconf);
604
605     $out .= '<ul class="indexlist">';
606     foreach ($stats as $stat) {
607       $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
608       $surl = '?stat='.$stat['name'];
609       $out .= '<a href="'.$surl.'">'.$stat['name'].'</a>';
610       if (isset($stat['sub']) && count($stat['sub'])) {
611         $sprt = array();
612         foreach ($stat['sub'] as $ssub) { $sprt[] = '<a href="'.$surl.'&sub='.$ssub.'">'.$ssub.'</a>'; }
613         $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
614       }
615       $out .= '</li>';
616     }
617     $out .= '</ul>';
618
619     $out .= $this->h_page_footer();
620     $out .= '</body></html>';
621   return $out;
622   }
623
624   function page_overview($pconf, $graph_extras = null) {
625     // create an overview HTML page (including graphs) and return it in a string
626
627     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'RRD statistics overview';
628
629     $out = '<html><head>';
630     $out .= '<title>'.$ptitle.'</title>';
631     $out .= '<style>';
632     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
633     else {
634       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
635       $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }';
636       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
637       $out .= 'img.rrdgraph { border: none; }';
638     }
639     if (isset($pconf['style'])) { $out .= $pconf['style']; }
640     $out .= '</style>';
641     $out .= '</head>';
642     $out .= '<body>';
643
644     $out .= '<h1>'.$ptitle.'</h1>';
645     if (isset($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'; }
646
647     $stats = $this->h_page_statsArray($pconf);
648
649     $num_rows = is_numeric($pconf['num_rows'])?$pconf['num_rows']:2;
650     $num_cols = ceil(count($stats)/$num_rows);
651
652     $out .= '<table class="overview">';
653     for ($col = 0; $col < $num_cols; $col++) {
654       $out .= '<tr>';
655       for ($row = 0; $row < $num_rows; $row++) {
656         $idx = $col * $num_rows + $row;
657         $out .= '<td>';
658         if ($idx < count($stats)) {
659           list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
660           $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
661           $g_sub = $this->config_all[$sname][$s_psname]['graph_sub'];
662
663           if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
664             $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
665           }
666           elseif (isset($this->config_all[$sname]['page']['title_page'])) {
667             $s_ptitle = $this->config_all[$sname]['page']['title_page'];
668           }
669           else {
670             $s_ptitle = $sname.(isset($s_psub)?' ('.$s_psub.')':'').' statistics';
671           }
672           if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
673             $out .= '<h2>'.$s_ptitle.'</h2>';
674           }
675
676           $s_rrd = new rrdstat($this->config_all, $sname);
677           if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
678             $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
679             $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
680             if (isset($pconf['graph_url'])) {
681               $gURL = $pconf['graph_url'];
682               $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
683               $fname = str_replace('%p', $gmeta['filename'], $gURL);
684               if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
685             }
686             else {
687               $gURL = $gmeta['filename'];
688             }
689             $out .= '<a href="?stat='.$sname.(isset($s_psub)?'&sub='.$s_psub:'').'"';
690             $out .= '<img src="'.$gURL.'"';
691             $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
692             $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
693             $out .= '</a>';
694           }
695           else {
696             $out .= 'RRD error: status is "'.$s_rrd->status.'"';
697           }
698         }
699         else {
700           $out .= '&nbsp;';
701         }
702         $out .= '</td>';
703       }
704       $out .= '</tr>';
705     }
706     $out .= '</table>';
707
708     $out .= $this->h_page_footer();
709     $out .= '</body></html>';
710   return $out;
711   }
712
713   function page_simple($pconf, $graph_extras = null) {
714     // create a simple (MRTG-like) HTML page and return it in a string
715
716     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$this->basename.' - RRD statistics';
717     $gtitle = array();
718     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
719     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
720     $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
721     $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
722
723     $out = '<html><head>';
724     $out .= '<title>'.$ptitle.'</title>';
725     $out .= '<style>';
726     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
727     else {
728       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
729       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
730       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
731       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
732       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
733       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
734     }
735     if (isset($pconf['style'])) { $out .= $pconf['style']; }
736     $out .= '</style>';
737     $out .= '</head>';
738     $out .= '<body>';
739
740     $out .= '<h1>'.$ptitle.'</h1>';
741     if (!isset($pconf['show_update']) || $pconf['show_update']) {
742       $out .= '<p class="last_up">Last Update: '.(is_null($this->last_update())?'unknown':date('Y-m-d H:i:s', $this->last_update())).'</p>';
743     }
744
745     $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
746     if (in_array($this->status, array('ok','readonly','graphonly'))) {
747       foreach (array('day','week','month','year') as $tframe) {
748         $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
749         if (isset($pconf['graph_url'])) {
750           $gURL = $pconf['graph_url'];
751           $fname = str_replace('%f', basename($gmeta['filename']), $gURL);
752           $fname = str_replace('%p', $gmeta['filename'], $gURL);
753           if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
754         }
755         else {
756           $gURL = $gmeta['filename'];
757         }
758         $out .= '<div class="'.$tframe.'">';
759 //         $out .= '<p>'.nl2br($ret).'</p>';
760         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
761         $out .= '<img src="'.$gURL.'"';
762         $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
763         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
764         if (isset($gmeta['data']) && count($gmeta['data'])) {
765           $out .= '<table class="gdata">';
766           foreach ($gmeta['data'] as $field=>$gdata) {
767             $out .= '<tr><th>'.$field.'</th>';
768             foreach ($gdata as $gkey=>$gval) {
769               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
770             }
771             $out .= '</tr>';
772           }
773           $out .= '</table>';
774         }
775         if (isset($gmeta['var']) && count($gmeta['var'])) {
776           foreach ($gmeta['var'] as $gkey=>$gval) {
777             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
778           }
779         }
780         if (isset($gmeta['info']) && count($gmeta['info'])) {
781           foreach ($gmeta['info'] as $gval) {
782             $out .= '<p class="ginfo">'.$gval.'</p>';
783           }
784         }
785         $out .= '</div>';
786       }
787     }
788     else {
789       $out .= 'RRD error: status is "'.$this->status.'"';
790     }
791
792     $out .= $this->h_page_footer();
793     $out .= '</body></html>';
794   return $out;
795   }
796
797   function h_page_statsArray($pconf) {
798     // return array of stats to list on a page
799     $stats = array();
800     $snames = array(); $s_exclude = array(); $sfiles = array();
801     if (isset($pconf['index_ids'])) {
802       foreach (explode(',', $pconf['index_ids']) as $iid) {
803         if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
804         else { $snames[] = $iid; }
805       }
806     }
807     if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
808       foreach ($this->config_all as $iname=>$rinfo) {
809         if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
810             !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
811           $snames[] = $iname;
812         }
813       }
814     }
815     foreach ($snames as $iname) {
816       $newstat = array('name'=>$iname);
817       $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
818       if (is_array($this->config_all[$iname])) {
819         foreach ($this->config_all[$iname] as $key=>$val) {
820           if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
821         }
822       }
823       $stats[] = $newstat;
824     }
825     if (isset($pconf['scan_files']) && $pconf['scan_files']) {
826       $rrdfiles = glob('*.rrd');
827       foreach ($rrdfiles as $rrdfile) {
828         $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
829         if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
830           $stats[] = array('name'=>$iname, 'class'=>'scanfile');
831         }
832       }
833     }
834   return $stats;
835   }
836
837   function h_page_footer() {
838     // return generic page footer
839     $out = '<p class="footer">';
840     $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
841     $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
842     $out .= '</p>';
843   return $out;
844   }
845
846   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
847 }
848 ?>