support different page types
[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 graph($timeframe = 'day', $sub = null, $extra = null) {
267     // create a RRD graph
268     static $gColors;
269     if (!isset($gColors)) {
270       $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
271     }
272
273     if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
274
275     // assemble configuration
276     $gconf = (array)$extra;
277     if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
278       $gconf = $gconf + $this->config_raw['graph.'.$sub];
279     }
280     $gconf = $gconf + (array)$this->config_graph;
281
282     if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
283       $format = $gconf['format']; $fmt_ext = '.svg';
284     }
285     elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
286       $format = $gconf['format']; $fmt_ext = '.eps';
287     }
288     elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
289       $format = $gconf['format']; $fmt_ext = '.pdf';
290     }
291     else {
292       $format = 'PNG'; $fmt_ext = '.png';
293     }
294
295     if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
296     else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
297     $fname = str_replace('%s', strval($sub), $fname);
298     $fname = str_replace('%t', $timeframe, $fname);
299     $fname = str_replace('%f', $fmt_ext, $fname);
300     if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
301     if (isset($gconf['path'])) { $fname = $gconf['path'].'/'.$fname; }
302     $fname = str_replace('//', '/', $fname);
303
304     $graphrows = array(); $gC = 0;
305     $gDefs = ''; $gGraphs = ''; $addSpecial = '';
306
307     if ($timeframe == 'day') {
308       $duration = isset($gconf['duration'])?$gconf['duration']:30*3600; // 30 hours
309       $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
310       // vertical lines at day borders
311       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
312       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
313       if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
314     }
315     elseif ($timeframe == 'week') {
316       $duration = isset($gconf['duration'])?$gconf['duration']:8*86400; // 8 days
317       $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
318       // vertical lines at week borders
319       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
320       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
321     }
322     elseif ($timeframe == 'month') {
323       $duration = isset($gconf['duration'])?$gconf['duration']:36*86400; // 36 days
324       $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
325       // vertical lines at month borders
326       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
327       $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
328     }
329     elseif ($timeframe == 'year') {
330       $duration = isset($gconf['duration'])?$gconf['duration']:396*86400; // 365+31 days
331       $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
332       // vertical lines at month borders
333       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
334       $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
335     }
336     else {
337       $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
338       $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
339     }
340
341     if (isset($gconf['rows']) && count($gconf['rows'])) {
342       foreach ($gconf['rows'] as $erow) {
343         if (isset($erow['name']) && strlen($erow['name'])) {
344           if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
345           $grow = array();
346           $grow['dType'] = isset($erow['dType'])?$erow['dType']:'DEF';
347           $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
348           if ($grow['dType'] == 'DEF') {
349             $grow['dsname'] = isset($erow['dsname'])?$erow['dsname']:$erow['name'];
350             if (isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
351             $grow['cf'] = isset($erow['cf'])?$erow['cf']:'AVERAGE';
352           }
353           else {
354             $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
355           }
356           if (isset($erow['scale'])) {
357             $graphrows[] = $grow;
358             $grow = array();
359             $grow['dType'] = 'CDEF';
360             $grow['name'] = $erow['name'];
361             $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
362           }
363           $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1';
364           $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
365           if ($gC >= count($gColors)) { $gC = 0; }
366           if (isset($erow['legend'])) {
367             $grow['legend'] = $erow['legend'];
368             if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
369           }
370           if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
371           if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
372           $graphrows[] = $grow;
373         }
374       }
375     }
376     else {
377       foreach ($this->rrd_fields as $key=>$ds) {
378         $grow = array();
379         $grow['dType'] = 'DEF';
380         $grow['name'] = $ds['name'].(isset($gconf['scale'])?'_tmp':'');
381         $grow['dsname'] = $ds['name'];
382         $grow['cf'] = 'AVERAGE';
383         if (isset($gconf['scale'])) {
384           $graphrows[] = $grow;
385           $grow = array();
386           $grow['dType'] = 'CDEF';
387           $grow['name'] = $ds['name'];
388           $grow['rpn_expr'] = $ds['name'].'_tmp,'.$gconf['scale'].',*';
389         }
390         $grow['gType'] = ((count($this->rrd_fields)==2) && ($key==0))?'AREA':'LINE1';
391         $grow['color'] = $gColors[$gC++]; if ($gC >= count($gColors)) { $gC = 0; }
392         $graphrows[] = $grow;
393       }
394     }
395
396     if (isset($gconf['special']) && count($gconf['special'])) {
397       foreach ($gconf['special'] as $crow) {
398         $srow = array();
399         $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
400         if ($grow['sType'] != 'COMMENT') {
401           // XXX: use line below and remove cf var once we have rrdtol 1.2
402           // $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
403           $srow['name'] = $crow['name'];
404           $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
405           if (isset($crow['cf'])) {
406             // XXX: use line below once we have rrdtol 1.2
407             // $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
408           }
409           elseif (isset($crow['rpn_expr'])) {
410             // XXX: does only work with rrdtool 1.2
411             $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
412           }
413         }
414         $srow['text'] = isset($crow['text'])?$crow['text']:'';
415         $specialrows[] = $srow;
416       }
417     }
418     else {
419       foreach ($graphrows as $grow) {
420         if (isset($grow['gType']) && strlen($grow['gType'])) {
421           $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
422           // XXX: use lines below once we have rrdtol 1.2
423           // $graphrows[] = array('dType'=>'VDEF', 'name'=>$grow['name'].'_last', 'rpn_expr'=>$grow['name'].',LAST');
424           // $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'].'_last', 'text'=>'%3.2lf%s');
425           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|Maximum|%.2lf%s');
426           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|Average|%.2lf%s');
427           $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|Current|%.2lf%s');
428         }
429       }
430     }
431
432     $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
433     $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
434     if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
435     if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
436     if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
437     if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
438       if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
439     }
440     if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
441     if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
442     if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
443     if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
444     if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
445     if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
446     if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
447     if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
448     if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
449     if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
450       foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
451     }
452     if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
453       foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
454     }
455     if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
456
457     foreach ($graphrows as $grow) {
458       if (isset($grow['dType']) && strlen($grow['dType'])) {
459         $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
460         if ($grow['dType'] == 'DEF') {
461           $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
462           $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
463         }
464         else { $gDefs .= $grow['rpn_expr']; }
465       }
466       if (isset($grow['gType']) && strlen($grow['gType'])) {
467         // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
468         if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
469         $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
470         if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
471         // XXX: remove above STACK if-command and uncomment the one below once we have rrdtool 1.2
472         //if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
473       }
474     }
475
476     foreach ($specialrows as $srow) {
477       $addSpecial .= ' '.$srow['sType'];
478       // XXX: eliminate cf once we have rrdtool 1.2
479       // $addSpecial .= ($grow['sType']!='COMMENT')?':'.$grow['name']:'');
480       $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
481       $addSpecial .= ':'.$this->text_quote($srow['text']);
482     }
483
484     $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
485     $return = `$graph_cmd 2>&1`;
486
487     if (strpos($return, 'ERROR') !== false) {
488       trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
489       $return = $graph_cmd."\n\n".$return;
490     }
491     $return = 'file:'.$fname."\n".$return;
492   return $return;
493   }
494
495   function page($sub = null, $page_extras = null, $graph_extras = null) {
496     // create a (HTML) page and return it in a string
497
498     // assemble configuration
499     $pconf = (array)$page_extras;
500     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
501       $pconf = $pconf + $this->config_raw['page.'.$sub];
502     }
503     $pconf = $pconf + (array)$this->config_page;
504
505     $return = null;
506     switch ($pconf['type']) {
507       case 'index':
508         $return = $this->page_index($pconf);
509         break;
510       case 'overview':
511         $return = $this->page_overview($pconf, $graph_extras);
512         break;
513       case 'simple':
514       default:
515         $return = $this->page_simple($pconf, $graph_extras);
516         break;
517     }
518   return $return;
519   }
520
521   function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
522     // create a simple (MRTG-like) HTML page and return it in a string
523     // XXX: this is here temporarily for compat only, it's preferred to use page()!
524
525     // assemble configuration
526     $pconf = (array)$page_extras;
527     if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
528       $pconf = $pconf + $this->config_raw['page.'.$sub];
529     }
530     $pconf = $pconf + (array)$this->config_page;
531
532   return $this->page_simple($pconf, $graph_extras);
533   }
534
535   function page_index($pconf) {
536     // create a bare, very simple index list HTML page and return it in a string
537
538     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:'Index - RRD statistics';
539
540     $out = '<html><head>';
541     $out .= '<title>'.$ptitle.'</title>';
542     $out .= '<style>';
543     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
544     else {
545       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
546       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
547       $out .= 'li.scanfile { font-style: italic; }';
548     }
549     if (isset($pconf['style'])) { $out .= $pconf['style']; }
550     $out .= '</style>';
551     $out .= '</head>';
552     $out .= '<body>';
553
554     $out .= '<h1>'.$ptitle.'</h1>';
555     $out .= '<p class="intro">The following RRD stats are available:</p>';
556
557     $out .= '<ul class="indexlist">';
558     $snames = array(); $s_exclude = array();
559     $stats = array(); $sfiles = array();
560     if (isset($pconf['index_ids'])) {
561       foreach (explode(',', $pconf['index_ids']) as $iid) {
562         if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
563         else { $snames[] = $iid; }
564       }
565     }
566     if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
567       foreach ($this->config_all as $iname=>$rinfo) {
568         if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
569             !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
570           $snames[] = $iname;
571         }
572       }
573     }
574     foreach ($snames as $iname) {
575       $newstat = array('name'=>$iname);
576       $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
577       foreach ($this->config_all[$iname] as $key=>$val) {
578         if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
579       }
580       $stats[] = $newstat;
581     }
582     if (isset($pconf['scan_files']) && $pconf['scan_files']) {
583       $rrdfiles = glob('*.rrd');
584       foreach ($rrdfiles as $rrdfile) {
585         $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
586         if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
587           $stats[] = array('name'=>$iname, 'class'=>'scanfile');
588         }
589       }
590     }
591     foreach ($stats as $stat) {
592       $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
593       $surl = '?stat='.$stat['name'];
594       $out .= '<a href="'.$surl.'">'.$stat['name'].'</a>';
595       if (isset($stat['sub']) && count($stat['sub'])) {
596         $sprt = array();
597         foreach ($stat['sub'] as $ssub) { $sprt[] = '<a href="'.$surl.'&sub='.$ssub.'">'.$ssub.'</a>'; }
598         $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
599       }
600       $out .= '</li>';
601     }
602     $out .= '</ul>';
603
604     $out .= '<p class="footer">';
605     $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
606     $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
607     $out .= '</p>';
608
609     $out .= '</body></html>';
610
611   return $out;
612   }
613
614   function page_overview($pconf, $graph_extras = null) {
615     // create an overview HTML page (including graphs) and return it in a string
616
617   return $this->page_index($pconf);
618   }
619
620   function page_simple($pconf, $graph_extras = null) {
621     // create a simple (MRTG-like) HTML page and return it in a string
622
623     $ptitle = isset($pconf['title_page'])?$pconf['title_page']:$this->basename.' - RRD statistics';
624     $gtitle = array();
625     $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:'Day overview (scaling 5 minutes)';
626     $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:'Week overview (scaling 30 minutes)';
627     $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:'Month overview (scaling 2 hours)';
628     $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:'Year overview (scaling 1 day)';
629
630     $out = '<html><head>';
631     $out .= '<title>'.$ptitle.'</title>';
632     $out .= '<style>';
633     if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
634     else {
635       $out .= 'h1 { font-weight: bold; font-size: 1.5em; }';
636       $out .= 'h2 { font-weight: bold; font-size: 1em; }';
637       $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }';
638       $out .= 'table.gdata { border: 1px solid gray; border-collapse: collapse; }';
639       $out .= 'table.gdata td, table.gdata th { border: 1px solid gray; padding: 0.1em 0.2em; }';
640       $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }';
641     }
642     if (isset($pconf['style'])) { $out .= $pconf['style']; }
643     $out .= '</style>';
644     $out .= '</head>';
645     $out .= '<body>';
646
647     $out .= '<h1>'.$ptitle.'</h1>';
648     if (!isset($pconf['show_update']) || $pconf['show_update']) {
649       $out .= '<p class="last_up">Last Update: '.(is_null($this->last_update())?'unknown':date('Y-m-d H:i:s', $this->last_update())).'</p>';
650     }
651
652     if (in_array($this->status, array('ok','readonly','graphonly'))) {
653       $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
654       foreach (array('day','week','month','year') as $tframe) {
655         $ret = $this->graph($tframe, $g_sub, $graph_extras);
656         if (strpos($ret, "\n\n") !== false) { $graph_cmd = substr($ret, 0, strpos($ret, "\n\n")); $ret = substr($ret, strpos($ret, "\n\n")+2); }
657         else { $graph_cmd = null; }
658         $grout = explode("\n",$ret);
659         $gfilename = null;
660         $gmeta = array();
661         foreach ($grout as $gline) {
662           if (preg_match('/^file:(.+)$/', $gline, $regs)) {
663             $gfilename = $regs[1];
664           }
665           elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
666             $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
667           }
668           elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
669             $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
670           }
671           elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
672             $gmeta['var'][$regs[1]] = $regs[2];
673           }
674           elseif (strlen(trim($gline))) {
675             $gmeta['info'][] = $gline;
676           }
677         }
678         if (is_null($gfilename)) { $gfilename = $this->basename.(!is_null($g_sub)?'-'.$g_sub:'').'-'.$tframe.'.png'; }
679         if (isset($pconf['graph_url'])) {
680           $gURL = $pconf['graph_url'];
681           $fname = str_replace('%f', basename($gfilename), $gURL);
682           $fname = str_replace('%p', $gfilename, $gURL);
683           if (substr($gURL, -1) == '/') { $gURL .= $gfilename; }
684         }
685         else {
686           $gURL = $gfilename;
687         }
688         $out .= '<div class="'.$tframe.'">';
689 //         $out .= '<p>'.nl2br($ret).'</p>';
690         $out .= '<h2>'.$gtitle[$tframe].'</h2>';
691         $out .= '<img src="'.$gURL.'"';
692         $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
693         $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;">';
694         if (isset($gmeta['data']) && count($gmeta['data'])) {
695           $out .= '<table class="gdata">';
696           foreach ($gmeta['data'] as $field=>$gdata) {
697             $out .= '<tr><th>'.$field.'</th>';
698             foreach ($gdata as $gkey=>$gval) {
699               $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
700             }
701             $out .= '</tr>';
702           }
703           $out .= '</table>';
704         }
705         if (isset($gmeta['var']) && count($gmeta['var'])) {
706           foreach ($gmeta['var'] as $gkey=>$gval) {
707             $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>';
708           }
709         }
710         if (isset($gmeta['info']) && count($gmeta['info'])) {
711           foreach ($gmeta['info'] as $gval) {
712             $out .= '<p class="ginfo">'.$gval.'</p>';
713           }
714         }
715       }
716     }
717     else {
718       $out .= 'RRD error: status is "'.$this->status.'"';
719     }
720     $out .= '</div>';
721
722     $out .= '<p class="footer">';
723     $out .= 'Statistics created by <a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>';
724     $out .= ' using a library created by <a href="http://www.kairo.at/">KaiRo.at</a>.';
725     $out .= '</p>';
726
727     $out .= '</body></html>';
728   return $out;
729   }
730
731   function last_update() {
732     // fetch time of last update in this RRD file
733     static $last_update;
734     if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
735       $last_cmd = 'rrdtool last '.$this->rrd_file;
736       $return = trim(`$last_cmd 2>&1`);
737       $last_update = is_numeric($return)?$return:null;
738     }
739   return isset($last_update)?$last_update:null;
740   }
741
742   function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
743 }
744 ?>