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