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