make last/avg/max VDEFs not clash with maybe manually set DEFs (modern RRD only)
[php-utility-classes.git] / include / classes / rrdstat.php-class
CommitLineData
b7878f4d 1<?php
0ee9d2d0 2/* ***** BEGIN LICENSE BLOCK *****
3 *
4 * The contents of this file are subject to Austrian copyright reegulations
5 * ("Urheberrecht"); you may not use this file except in compliance with
6 * those laws.
7 * This contents and any derived work, if it gets distributed in any way,
8 * is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
9 * either express or implied.
10 *
11 * The Original Code is KaiRo's RRD statistics class.
12 *
13 * The Initial Developer of the Original Code is
14 * KaiRo - Robert Kaiser.
8b4f4335 15 * Portions created by the Initial Developer are Copyright (C) 2005-2006
0ee9d2d0 16 * the Initial Developer. All Rights Reserved.
17 *
18 * Contributor(s): Robert Kaiser <kairo@kairo.at>
19 *
20 * ***** END LICENSE BLOCK ***** */
21
b7878f4d 22class rrdstat {
0ee9d2d0 23 // rrdstat PHP class
24 // rrdtool statistics functions
25 //
26 // function rrdstat($rrdconfig, [$conf_id])
27 // CONSTRUCTOR
28 // if $conf_id is set, $rrdconfig is a total configuration set
29 // else it's the configuration for this one RRD
30 // currently only a config array is supported, XML config is planned
31 //
32 // var $rrd_file
33 // RRD file name
34 //
35 // var $basename
36 // base name for this RRD (usually file name without .rrd)
37 //
2e28e4bd 38 // var $basedir
39 // base directory for this RRD (with a trailing slash)
40 // note that $rrd_file usually includes that path as well, but graph directory gets based on this value
41 //
0ee9d2d0 42 // var $config_all
43 // complete, raw configuration array set
44 //
45 // var $config_raw
46 // configuration array set for current RRD
47 //
48 // var $config_graph
49 // configuration array set for default graph in this RRD
50 //
51 // var $config_page
52 // configuration array set for default page in this RRD
53 //
54 // var $rrd_fields
55 // definition of this RRD's fields
56 //
57 // var $rra_base
58 // definition of this RRD's base RRAs
59 //
60 // var $rrd_step
61 // basic stepping of this RRD in seconds (default: 300)
62 //
63 // var $rra_add_max
64 // should RRAs for MAX be added for every base RRA? (bool, default: true)
65 //
66 // var $status
67 // status of the RRD (unused/ok/readonly/graphonly)
68 // note that most functions require certain status values
69 // (e.g. update only works if status is ok, graph for ok/readonly/graphonly)
70 //
724f6e78 71 // var $mod_textdomain
72 // GNU gettext domain for this module
73 //
0ee9d2d0 74 // function set_def($rrdconfig, [$conf_id])
75 // set definitions based on given configuration
76 // [intended for internal use, called by the constructor]
77 //
586031ce 78 // function rrd_version() {
79 // get RRDtool version string
80 //
0ee9d2d0 81 // function create()
82 // create RRD file according to set config
83 //
84 // function update([$upArray])
85 // feed new data into RRD (either use given array of values or use auto-update info from config)
86 //
87 // function fetch([$cf] = 'AVERAGE', $resolution = null, $start = null, $end = null)
88 // fetch data from the defined RRD
89 // using given consolidation function [default is AVERAGE],
90 // resolution (seconds, default is the RRD's stepping),
91 // start and end times (unix epoch, defaults are the RRD's last update time)
92 //
93 // function last_update()
94 // fetch time of last update in this RRD file
95 //
96 // function graph([$timeframe], [$sub], [$extra])
97 // create a RRD graph (and return all meta info in a flat string)
98 // for given timeframe (day [default]/week/month/year),
99 // sub-graph ID (if given) and extra config options (if given)
100 //
101 // function graph_plus([$timeframe], [$sub], [$extra])
102 // create a RRD graph (see above) and return meta info as a ready-to-use array
103 //
104 // function page([$sub], [$page_extras], [$graph_extras])
105 // create a (HTML) page and return it in a string
106 // for given sub-page ID (if given, default is a simple HTML page)
107 // and extra page and graph config options (if given)
108 //
109 // function simple_html([$sub], [$page_extras], [$graph_extras])
110 // create a simple (MRTG-like) HTML page and return it in a string
111 // XXX: this is here temporarily for compat only, it's preferred to use page()!
112 //
113 // function page_index($pconf)
114 // create a bare, very simple index list HTML page and return it in a string
115 // using given page config options
116 // [intended for internal use, called by page()]
117 //
118 // function page_overview($pconf, [$graph_extras])
119 // create an overview HTML page (including graphs) and return it in a string
120 // using given page config options and extra graph options (if given)
121 // [intended for internal use, called by page()]
122 //
123 // function page_simple($pconf, [$graph_extras])
124 // create a simple (MRTG-like) HTML page and return it in a string
125 // using given page config options and extra graph options (if given)
126 // [intended for internal use, called by page()]
127 //
128 // function h_page_statsArray($pconf)
129 // return array of stats to list on a page, using given page config options
130 // [intended for internal use, called by page_*()]
131 //
132 // function h_page_footer()
133 // return generic page footer
134 // [intended for internal use, called by page_*()]
135 //
136 // function text_quote($text)
137 // return a quoted/escaped text for use in rrdtool commandline text fields
b7878f4d 138
2a386f5a 139 var $rrd_file = null;
31df2e13 140 var $basename = null;
2e28e4bd 141 var $basedir = null;
b7878f4d 142
099bd59f 143 var $config_all = null;
a039a75c 144 var $config_raw = null;
145 var $config_graph = null;
146 var $config_page = null;
147
b7878f4d 148 var $rrd_fields = array();
149 var $rra_base = array();
150 var $rrd_step = 300;
151 var $rra_add_max = true;
152
153 var $status = 'unused';
154
724f6e78 155 var $mod_textdomain;
156
ebe03325 157 function rrdstat($rrdconfig, $conf_id = null) {
b7878f4d 158 // ***** init RRD stat module *****
724f6e78 159 $this->mod_textdomain = 'class_rrdstat';
160 $mod_charset = 'iso-8859-15';
161
162 bindtextdomain($this->mod_textdomain, class_exists('baseutils')?baseutils::getDir('locale'):'locale/');
163 bind_textdomain_codeset($this->mod_textdomain, $mod_charset);
164
ebe03325 165 $this->set_def($rrdconfig, $conf_id);
b7878f4d 166
b1776944 167 if (($this->status == 'unused') && !is_null($this->rrd_file)) {
2a386f5a 168 if (!is_writeable($this->rrd_file)) {
169 if (!file_exists($this->rrd_file)) {
86ff8b91 170 if (@touch($this->rrd_file)) { $this->create(); }
2a386f5a 171 else { trigger_error('RRD file can not be created', E_USER_WARNING); }
172 }
173 else {
174 if (is_readable($this->rrd_file)) { $this->status = 'readonly'; }
175 else { trigger_error('RRD file is not readable', E_USER_WARNING); }
176 }
b7878f4d 177 }
178 else {
2a386f5a 179 $this->status = 'ok';
b7878f4d 180 }
181 }
b7878f4d 182 }
183
ebe03325 184 function set_def($rrdconfig, $conf_id = null) {
185 if (is_array($rrdconfig)) {
b7878f4d 186 // we have an array in the format we like to have
ebe03325 187 $complete_conf =& $rrdconfig;
b7878f4d 188 }
189 else {
190 // we have something else (XML data?), try to generate the iinfo aray from it
ebe03325 191 $complete_conf =& $rrdconfig;
192 }
193
194 if (!is_null($conf_id)) {
195 $iinfo = isset($complete_conf[$conf_id])?$complete_conf[$conf_id]:array();
e1727e7f 196 if (isset($complete_conf['*'])) {
197 $iinfo = (array)$iinfo + (array)$complete_conf['*'];
198 if (isset($complete_conf['*']['graph'])) { $iinfo['graph'] = (array)$iinfo['graph'] + (array)$complete_conf['*']['graph']; }
199 if (isset($complete_conf['*']['page'])) { $iinfo['page'] = (array)$iinfo['page'] + (array)$complete_conf['*']['page']; }
200 }
ebe03325 201 }
202 else {
203 $iinfo = $complete_conf;
b7878f4d 204 }
205
2e28e4bd 206 if (isset($iinfo['path']) && strlen($iinfo['path'])) {
207 $this->basedir = $iinfo['path'];
208 if (substr($this->basedir, -1) != '/') { $this->basedir .= '/'; }
209 }
210
b1776944 211 if (isset($iinfo['graph-only']) && $iinfo['graph-only'] && !is_null($conf_id)) {
212 $this->basename = $conf_id;
213 $this->status = 'graphonly';
214 }
099bd59f 215 elseif (isset($iinfo['file'])) {
2e28e4bd 216 $this->rrd_file = (($iinfo['file']{0} != '/')?$this->basedir:'').$iinfo['file'];
82d064f4 217 $this->basename = basename((substr($this->rrd_file, -4) == '.rrd')?substr($this->rrd_file, 0, -4):$this->rrd_file);
b1776944 218 }
abe8eac1 219 elseif (!is_null($conf_id) && file_exists($conf_id.'.rrd')) {
2e28e4bd 220 $this->rrd_file = (($iinfo['file']{0} != '/')?$this->basedir:'').$conf_id.'.rrd';
abe8eac1 221 $this->basename = $conf_id;
222 }
b7878f4d 223 else {
099bd59f 224 $this->basename = !is_null($conf_id)?$conf_id:'xxx.unknown';
225 }
226
abe8eac1 227 if (!is_null($this->rrd_file)) {
099bd59f 228 // fields (data sources, DS)
229 // name - DS name
230 // type - one of COUNTER, GAUGE, DERIVE, ABSOLUTE
231 // heartbeat - if no sample recieved for that time, store UNKNOWN
232 // min - U (unconstrained) or minimum value
233 // max - U (unconstrained) or maximum value
234 // update - this string will be fed into eval() for updating this field
235 if (isset($iinfo['fields']) && is_array($iinfo['fields'])) {
236 $this->rrd_fields = $iinfo['fields'];
237 }
238 else {
239 $this->rrd_fields[] = array('name' => 'ds0', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
240 $this->rrd_fields[] = array('name' => 'ds1', 'type' => 'COUNTER', 'heartbeat' => 600, 'min' => 'U', 'max' => 'U');
241 }
b7878f4d 242
243
099bd59f 244 // MRTG-style RRD "database", see http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/tut/rrdtutorial.en.html
245 //
246 // archives (RRAs):
247 // 600 samples of 5 minutes (2 days and 2 hours)
248 // 700 samples of 30 minutes (2 days and 2 hours, plus 12.5 days)
249 // 775 samples of 2 hours (above + 50 days)
250 // 797 samples of 1 day (above + 732 days, rounded up to 797)
b7878f4d 251
099bd59f 252 $this->rrd_step = isset($iinfo['rrd_step'])?$iinfo['rrd_step']:300;
b7878f4d 253
099bd59f 254 if (isset($iinfo['rra_base']) && is_array($iinfo['rra_base'])) {
255 $this->rra_base = $iinfo['rra_base'];
256 }
257 else {
258 $this->rra_base[] = array('step' => 1, 'rows' => 600);
259 $this->rra_base[] = array('step' => 6, 'rows' => 700);
260 $this->rra_base[] = array('step' => 24, 'rows' => 775);
261 $this->rra_base[] = array('step' => 288, 'rows' => 797);
262 }
b7878f4d 263
099bd59f 264 $this->rra_add_max = isset($iinfo['rra_add_max'])?$iinfo['rra_add_max']:true;
265 }
a039a75c 266
267 if (isset($iinfo['graph'])) { $this->config_graph = $iinfo['graph']; }
268 if (isset($iinfo['page'])) { $this->config_page = $iinfo['page']; }
269 $this->config_raw = $iinfo;
099bd59f 270 $this->config_all = $complete_conf;
b7878f4d 271 }
272
586031ce 273 function rrd_version() {
274 // return RRDtool version
275 static $version;
276 if (!isset($version)) {
277 $create_cmd = 'rrdtool --version';
278 $return = `$create_cmd 2>&1`;
279 if (strpos($return, 'ERROR') !== false) {
280 trigger_error($this->rrd_file.' - rrd version error: '.$return, E_USER_WARNING);
281 }
282
283 if (preg_match('/^\s*RRDtool ([\d\.]+)\s+/', $return, $regs)) {
284 $version = $regs[1];
285 }
286 else {
287 $version = '0.0';
288 }
289 }
290 return $version;
291 }
292
b7878f4d 293 function create() {
294 // create RRD file
295
296 // compose create command
297 $create_cmd = 'rrdtool create '.$this->rrd_file.' --step '.$this->rrd_step;
298 foreach ($this->rrd_fields as $ds) {
299 if (!isset($ds['type'])) { $ds['type'] = 'COUNTER'; }
300 if (!isset($ds['heartbeat'])) { $ds['heartbeat'] = 2*$this->rrd_step; }
301 if (!isset($ds['min'])) { $ds['min'] = 'U'; }
302 if (!isset($ds['max'])) { $ds['max'] = 'U'; }
303 $create_cmd .= ' DS:'.$ds['name'].':'.$ds['type'].':'.$ds['heartbeat'].':'.$ds['min'].':'.$ds['max'];
304 }
305 foreach ($this->rra_base as $rra) {
306 if (!isset($rra['cf'])) { $rra['cf'] = 'AVERAGE'; }
307 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
308 if (!isset($rra['step'])) { $rra['step'] = 1; }
309 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
310 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
311 }
312 if ($this->rra_add_max) {
313 foreach ($this->rra_base as $rra) {
314 if (!isset($rra['cf'])) {
315 // only rows that have no CF set will be looked at here
316 $rra['cf'] = 'MAX';
317 if (!isset($rra['xff'])) { $rra['xff'] = 0.5; }
318 if (!isset($rra['step'])) { $rra['step'] = 1; }
319 if (!isset($rra['rows'])) { $rra['rows'] = 600; }
320 $create_cmd .= ' RRA:'.$rra['cf'].':'.$rra['xff'].':'.$rra['step'].':'.$rra['rows'];
321 }
322 }
323 }
b61757c1 324 $return = `$create_cmd 2>&1`;
325 if (strpos($return, 'ERROR') !== false) {
326 trigger_error($this->rrd_file.' - rrd create error: '.$return, E_USER_WARNING);
327 }
b7878f4d 328 else { $this->status = 'ok'; }
329 }
330
331 function update($upArray = null) {
332 // feed new data into RRD
633b21af 333 if ($this->status != 'ok') { trigger_error('Cannot update non-writeable file', E_USER_WARNING); return false; }
b7878f4d 334 $upvals = array();
de093632 335 if (isset($this->config_raw['update'])) {
b5e79d08 336 if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $this->config_raw['update'], $regs)) {
337 $upfunc = create_function('', $regs[1]);
338 $upvals = $upfunc();
339 }
340 else {
341 $evalcode = $this->config_raw['update'];
342 if (!is_null($evalcode)) {
343 ob_start();
344 eval($evalcode);
345 $ret = ob_get_contents();
346 if (strlen($ret)) { $upvals = explode("\n", $ret); }
347 ob_end_clean();
348 }
de093632 349 }
350 }
351 else {
352 foreach ($this->rrd_fields as $ds) {
353 if (is_array($upArray) && isset($upArray[$ds['name']])) { $val = $upArray[$ds['name']]; }
354 elseif (isset($ds['update'])) {
355 $val = null; $evalcode = null;
356 if (substr($ds['update'], 0, 4) == 'val:') {
b5e79d08 357 $evalcode = 'function { return trim('.substr($ds['update'], 4).')); }';
c5db3bd5 358 }
de093632 359 elseif (substr($ds['update'], 0, 8) == 'snmp-if:') {
360 $snmphost = 'localhost'; $snmpcomm = 'public';
361 list($nix, $ifname, $valtype) = explode(':', $ds['update'], 3);
362 $iflist = explode("\n", `snmpwalk -v2c -c $snmpcomm $snmphost interfaces.ifTable.ifEntry.ifDescr`);
363 $ifnr = null;
364 foreach ($iflist as $ifdesc) {
365 if (preg_match('/ifDescr\.(\d+) = STRING: '.$ifname.'/', $ifdesc, $regs)) { $ifnr = $regs[1]; }
366 }
367 $oid = null;
368 if ($valtype == 'in') { $oid = '1.3.6.1.2.1.2.2.1.10.'.$ifnr; }
369 elseif ($valtype == 'out') { $oid = '1.3.6.1.2.1.2.2.1.16.'.$ifnr; }
370 if (!is_null($ifnr) && !is_null($oid)) {
b5e79d08 371 $evalcode = 'function { return trim(substr(strrchr(`snmpget -v2c -c '.$snmpcomm.' '.$snmphost.' '.$oid.'`,":"),1)); }';
de093632 372 }
373 }
374 else { $evalcode = $ds['update']; }
b5e79d08 375 if (preg_match('/^\s*function\s+{(.*)}\s*$/is', $evalcode, $regs)) {
376 $upfunc = create_function('', $regs[1]);
377 $val = $upfunc();
378 }
379 elseif (!is_null($evalcode)) {
de093632 380 ob_start();
381 eval($evalcode);
382 $val = ob_get_contents();
383 ob_end_clean();
c5db3bd5 384 }
385 }
de093632 386 else { $val = null; }
b5e79d08 387 $upvals[$ds['name']] = $val;
c5db3bd5 388 }
b7878f4d 389 }
b5e79d08 390 $key_names = (!is_numeric(array_shift(array_keys($upvals))));
82d064f4 391 if (in_array('L', $upvals, true)) {
f21e94d9 392 // for at least one value, we need to set the same as the last recorded value
31cb3fc4 393 $fvals = $this->fetch();
394 $rowids = array_shift($fvals);
395 $lastvals = array_shift($fvals);
f21e94d9 396 foreach (array_keys($upvals, 'L') as $akey) {
b5e79d08 397 $upvals[$akey] = $key_names?$lastvals[$akey]:$lastvals[$rowids[$akey]];
f21e94d9 398 }
399 }
eb12543d 400 $walkfunc = create_function('&$val,$key', '$val = is_numeric(trim($val))?trim($val):"U";');
401 array_walk($upvals, $walkfunc);
25b93a4d 402 $return = null;
403 if (count($upvals)) {
b5e79d08 404 $update_cmd = 'rrdtool update '.$this->rrd_file.($key_names?' --template '.implode(':', array_keys($upvals)):'').' N:'.implode(':', $upvals);
25b93a4d 405 $return = `$update_cmd 2>&1`;
406 }
b61757c1 407
408 if (strpos($return, 'ERROR') !== false) {
409 trigger_error($this->rrd_file.' - rrd update error: '.$return, E_USER_WARNING);
410 $success = false;
411 }
412 else { $success = true; }
633b21af 413 return $success;
b7878f4d 414 }
415
a039a75c 416 function fetch($cf = 'AVERAGE', $resolution = null, $start = null, $end = null) {
417 // fetch data from a RRD
418 if (!in_array($this->status, array('ok','readonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
419
420 if (!in_array($cf, array('AVERAGE','MIN','MAX','LAST'))) { $cf = 'AVERAGE'; }
421 if (!is_numeric($resolution)) { $resolution = $this->rrd_step; }
422 if (!is_numeric($end)) { $end = $this->last_update(); }
423 elseif ($end < 0) { $end += $this->last_update(); }
424 $end = intval($end/$resolution)*$resolution;
425 if (!is_numeric($start)) { $start = $end; }
426 elseif ($start < 0) { $start += $end; }
427 $start = intval($start/$resolution)*$resolution;
428
429 $fetch_cmd = 'rrdtool fetch '.$this->rrd_file.' '.$cf.' --resolution '.$resolution.' --start '.$start.' --end '.$end;
430 $return = `$fetch_cmd 2>&1`;
431
432 if (strpos($return, 'ERROR') !== false) {
b61757c1 433 trigger_error($this->rrd_file.' - rrd fetch error: '.$return, E_USER_WARNING);
a039a75c 434 $fresult = false;
435 }
436 else {
437 $fresult = array();
438 $rows = explode("\n", $return);
439 $fields = preg_split('/\s+/', array_shift($rows));
440 if (array_shift($fields) == 'timestamp') {
441 $fresult[0] = $fields;
442 foreach ($rows as $row) {
443 if (strlen(trim($row))) {
444 $rvals = preg_split('/\s+/', $row);
31cb3fc4 445 $rtime = str_replace(':', '', array_shift($rvals));
a039a75c 446 $rv_array = array();
447 foreach ($rvals as $key=>$rval) {
448 $rv_array[$fields[$key]] = ($rval=='nan')?null:floatval($rval);
449 }
450 $fresult[$rtime] = $rv_array;
451 }
452 }
453 }
454 }
455 return $fresult;
456 }
b7878f4d 457
f5e899df 458 function last_update() {
459 // fetch time of last update in this RRD file
460 static $last_update;
461 if (!isset($last_update) && in_array($this->status, array('ok','readonly'))) {
462 $last_cmd = 'rrdtool last '.$this->rrd_file;
463 $return = trim(`$last_cmd 2>&1`);
464 $last_update = is_numeric($return)?$return:null;
465 }
466 return isset($last_update)?$last_update:null;
467 }
468
2c30ff69 469 function graph($timeframe = 'day', $sub = null, $extra = null) {
a039a75c 470 // create a RRD graph
471 static $gColors;
b7878f4d 472 if (!isset($gColors)) {
473 $gColors = array('#00CC00','#0000FF','#000000','#FF0000','#00FF00','#FFFF00','#FF00FF','#00FFFF','#808080','#800000','#008000','#000080','#808000','#800080','#008080','#C0C0C0');
474 }
475
b1776944 476 if (!in_array($this->status, array('ok','readonly','graphonly'))) { trigger_error('Error: rrd status is '.$this->status, E_USER_WARNING); return false; }
a039a75c 477
478 // assemble configuration
e1727e7f 479 $gconf = (array)$extra;
2c30ff69 480 if (!is_null($sub) && is_array($this->config_raw['graph.'.$sub])) {
e1727e7f 481 $gconf = $gconf + $this->config_raw['graph.'.$sub];
a039a75c 482 }
e1727e7f 483 $gconf = $gconf + (array)$this->config_graph;
a039a75c 484
485 if (isset($gconf['format']) && ($gconf['format'] == 'SVG')) {
486 $format = $gconf['format']; $fmt_ext = '.svg';
487 }
488 elseif (isset($gconf['format']) && ($gconf['format'] == 'EPS')) {
489 $format = $gconf['format']; $fmt_ext = '.eps';
490 }
491 elseif (isset($gconf['format']) && ($gconf['format'] == 'PDF')) {
492 $format = $gconf['format']; $fmt_ext = '.pdf';
493 }
494 else {
495 $format = 'PNG'; $fmt_ext = '.png';
496 }
497
498 if (isset($gconf['filename'])) { $fname = $gconf['filename']; }
31df2e13 499 else { $fname = $this->basename.(is_null($sub)?'':'-%s').'-%t%f'; }
2c30ff69 500 $fname = str_replace('%s', strval($sub), $fname);
a039a75c 501 $fname = str_replace('%t', $timeframe, $fname);
502 $fname = str_replace('%f', $fmt_ext, $fname);
503 if (substr($fname, -strlen($fmt_ext)) != $fmt_ext) { $fname .= $fmt_ext; }
2e28e4bd 504 if (isset($gconf['path']) && ($fname{0} != '/')) { $fname = $gconf['path'].'/'.$fname; }
505 if ($fname{0} != '/') { $fname = $this->basedir.$fname; }
ebe03325 506 $fname = str_replace('//', '/', $fname);
b7878f4d 507
abe8eac1 508 $graphrows = array(); $specialrows = array(); $gC = 0;
4ba56977 509 $gDefs = ''; $gGraphs = ''; $addSpecial = '';
510
cd6b890c 511 // the default size for the graph area has a width of 400px, so use 400 slices by default
4ba56977 512 if ($timeframe == 'day') {
a039a75c 513 $slice = isset($gconf['slice'])?$gconf['slice']:300; // 5 minutes
cd6b890c 514 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 33.33 hours
4ba56977 515 // vertical lines at day borders
516 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d')).'#FF0000';
517 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' -1 day').'#FF0000';
a039a75c 518 if (!isset($gconf['grid_x'])) { $gconf['grid_x'] = 'HOUR:1:HOUR:6:HOUR:2:0:%-H'; }
4ba56977 519 }
520 elseif ($timeframe == 'week') {
a039a75c 521 $slice = isset($gconf['slice'])?$gconf['slice']:1800; // 30 minutes
cd6b890c 522 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 8.33 days
4ba56977 523 // vertical lines at week borders
524 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')+1).' day').'#FF0000';
525 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-d').' '.(-date('w')-6).' day').'#FF0000';
526 }
527 elseif ($timeframe == 'month') {
a039a75c 528 $slice = isset($gconf['slice'])?$gconf['slice']:7200; // 2 hours
cd6b890c 529 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 33.33 days
4ba56977 530 // vertical lines at month borders
531 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01')).'#FF0000';
532 $addSpecial .= ' VRULE:'.strtotime(date('Y-m-01').' -1 month').'#FF0000';
533 }
534 elseif ($timeframe == 'year') {
a039a75c 535 $slice = isset($gconf['slice'])?$gconf['slice']:86400; // 1 day
cd6b890c 536 $duration = isset($gconf['duration'])?$gconf['duration']:400*$slice; // 400 days
4ba56977 537 // vertical lines at month borders
dfe923be 538 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00')).'#FF0000';
539 $addSpecial .= ' VRULE:'.strtotime(date('Y-01-01 12:00:00').' -1 year').'#FF0000';
4ba56977 540 }
541 else {
a039a75c 542 $duration = isset($gconf['duration'])?$gconf['duration']:$this->rrd_step*500; // 500 steps
543 $slice = isset($gconf['slice'])?$gconf['slice']:$this->rrd_step; // whatever our step is
4ba56977 544 }
545
67c0bd08 546 $use_gcrows = (isset($gconf['rows']) && count($gconf['rows']));
547 if ($use_gcrows) { $grow_def =& $gconf['rows']; }
548 else { $grow_def =& $this->rrd_fields; }
549 foreach ($grow_def as $key=>$erow) {
550 if (isset($erow['name']) && strlen($erow['name'])) {
551 if (!isset($erow['scale']) && isset($gconf['scale'])) { $erow['scale'] = $gconf['scale']; }
552 if (!isset($erow['scale_time_src']) && isset($gconf['scale_time_src'])) { $erow['scale_time_src'] = $gconf['scale_time_src']; }
553 if (!isset($erow['scale_time_tgt']) && isset($gconf['scale_time_tgt'])) { $erow['scale_time_tgt'] = $gconf['scale_time_tgt']; }
554 foreach (array('scale_time_src','scale_time_tgt') as $st) {
555 if (!isset($erow[$st]) || !is_numeric($erow[$st])) {
556 switch (@$erow[$st]) {
557 case 'dyn':
558 case 'auto':
559 $erow[$st] = $slice;
560 break;
561 case 'day':
562 $erow[$st] = 24*3600;
563 break;
564 case '2hr':
565 case '2hours':
566 $erow[$st] = 7200;
567 break;
568 case 'hr':
569 case 'hour':
570 $erow[$st] = 3600;
571 break;
572 case '30min':
573 $erow[$st] = 1800;
574 break;
575 case '5min':
576 $erow[$st] = 300;
577 break;
578 case 'min':
579 $erow[$st] = 60;
580 break;
581 case 's':
582 case 'sec':
583 default:
584 $erow[$st] = 1;
585 break;
2304f1ba 586 }
587 }
b7878f4d 588 }
67c0bd08 589 $scale_time_factor = $erow['scale_time_tgt']/$erow['scale_time_src'];
590 if ($scale_time_factor != 1) { $erow['scale'] = (isset($erow['scale'])?$erow['scale']:1)*$scale_time_factor; }
b7878f4d 591 $grow = array();
67c0bd08 592 $grow['dType'] = ($use_gcrows && isset($erow['dType']))?$erow['dType']:'DEF';
593 $grow['name'] = $erow['name'].(isset($erow['scale'])?'_tmp':'');
594 if ($grow['dType'] == 'DEF') {
595 $grow['dsname'] = ($use_gcrows && isset($erow['dsname']))?$erow['dsname']:$erow['name'];
596 if ($use_gcrows && isset($erow['dsfile'])) { $grow['dsfile'] = $erow['dsfile']; }
597 $grow['cf'] = ($use_gcrows && isset($erow['cf']))?$erow['cf']:'AVERAGE';
598 }
599 else {
600 $grow['rpn_expr'] = isset($erow['rpn_expr'])?$erow['rpn_expr']:'0';
601 }
602 if (isset($erow['scale'])) {
5f42eda6 603 $graphrows[] = $grow;
604 $grow = array();
605 $grow['dType'] = 'CDEF';
67c0bd08 606 $grow['name'] = $erow['name'];
607 $grow['rpn_expr'] = $erow['name'].'_tmp,'.$erow['scale'].',*';
5f42eda6 608 }
67c0bd08 609 if ($use_gcrows) { $grow['gType'] = isset($erow['gType'])?$erow['gType']:'LINE1'; }
610 else { $grow['gType'] = ((count($grow_def)==2) && ($key==0))?'AREA':'LINE1'; }
611 $grow['color'] = isset($erow['color'])?$erow['color']:$gColors[$gC++];
612 $grow['color_bg'] = isset($erow['color_bg'])?$erow['color_bg']:'';
613 if ($gC >= count($gColors)) { $gC = 0; }
614 if (isset($erow['legend'])) {
615 $grow['legend'] = $erow['legend'];
75124b94 616 if (!isset($gconf['show_legend'])) { $gconf['show_legend'] = true; }
617 }
67c0bd08 618 if (isset($erow['stack'])) { $grow['stack'] = ($erow['stack'] == true); }
619 if (isset($erow['desc'])) { $grow['desc'] = $erow['desc']; }
620 if (isset($erow['legend_long'])) { $grow['legend_long'] = $erow['legend_long']; }
b7878f4d 621 $graphrows[] = $grow;
622 }
623 }
624
16cc643c 625 if (isset($gconf['special']) && count($gconf['special'])) {
626 foreach ($gconf['special'] as $crow) {
627 $srow = array();
628 $srow['sType'] = isset($crow['sType'])?$crow['sType']:'COMMENT';
629 if ($grow['sType'] != 'COMMENT') {
630 // XXX: use line below and remove cf var once we have rrdtol 1.2
586031ce 631 if ($this->rrd_version() >= '1.2') {
632 $srow['name'] = $crow['name'].(isset($crow['cf'])?'_'.$crow['cf']:'');
633 }
634 else {
635 $srow['name'] = $crow['name'];
636 $srow['cf'] = isset($crow['cf'])?$crow['cf']:'AVERAGE';
637 }
16cc643c 638 if (isset($crow['cf'])) {
586031ce 639 if ($this->rrd_version() >= '1.2') {
640 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'].'_'.$crow['cf'], 'rpn_expr'=>$srow['name'].','.$crow['cf']);
641 }
16cc643c 642 }
643 elseif (isset($crow['rpn_expr'])) {
586031ce 644 if ($this->rrd_version() >= '1.2') {
645 $graphrows[] = array('dType'=>'VDEF', 'name'=>$srow['name'], 'rpn_expr'=>$crow['rpn_expr']);
646 }
16cc643c 647 }
648 }
649 $srow['text'] = isset($crow['text'])?$crow['text']:'';
650 $specialrows[] = $srow;
651 }
652 }
653 else {
ecc732d5 654 $td = $this->mod_textdomain;
16cc643c 655 foreach ($graphrows as $grow) {
656 if (isset($grow['gType']) && strlen($grow['gType'])) {
fe34d2fe 657 $textprefix = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
586031ce 658 if ($this->rrd_version() >= '1.2') {
3b68f7a1 659 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__max', 'rpn_expr'=>$grow['name'].',MAXIMUM');
660 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__max', 'text'=>$textprefix.'|'.dgettext($td, 'Maximum').'|%.2lf%s');
661 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__avg', 'rpn_expr'=>$grow['name'].',AVERAGE');
662 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__avg', 'text'=>$textprefix.'|'.dgettext($td, 'Average').'|%.2lf%s');
663 $graphrows[] = array('dType'=>'VDEF', 'name'=>'_'.$grow['name'].'__last', 'rpn_expr'=>$grow['name'].',LAST');
664 $specialrows[] = array('sType'=>'PRINT', 'name'=>'_'.$grow['name'].'__last', 'text'=>$textprefix.'|'.dgettext($td, 'Current').'|%.2lf%s');
586031ce 665 }
666 else {
667 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'MAX', 'text'=>$textprefix.'|'.dgettext($td, 'Maximum').'|%.2lf%s');
668 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'AVERAGE', 'text'=>$textprefix.'|'.dgettext($td, 'Average').'|%.2lf%s');
669 $specialrows[] = array('sType'=>'PRINT', 'name'=>$grow['name'], 'cf'=>'LAST', 'text'=>$textprefix.'|'.dgettext($td, 'Current').'|%.2lf%s');
670 }
16cc643c 671 }
672 }
673 }
674
a039a75c 675 $endtime = isset($gconf['time_end'])?$gconf['time_end']:(is_numeric($this->last_update())?$this->last_update():time());
676 $gOpts = ' --start '.($endtime-$duration).' --end '.$endtime.' --step '.$slice;
677 if (isset($gconf['label_top'])) { $gOpts .= ' --title '.$this->text_quote($gconf['label_top']); }
678 if (isset($gconf['label_y'])) { $gOpts .= ' --vertical-label '.$this->text_quote($gconf['label_y']); }
679 if (isset($gconf['width'])) { $gOpts .= ' --width '.$gconf['width']; }
680 if (isset($gconf['height'])) { $gOpts .= ' --height '.$gconf['height'];
681 if (($gconf['height'] <= 32) && isset($gconf['thumb']) && ($gconf['thumb'])) { $gOpts .= ' --only-graph'; }
4ba56977 682 }
a039a75c 683 if (!isset($gconf['show_legend']) || (!$gconf['show_legend'])) { $gOpts .= ' --no-legend'; }
d6ad10a5 684 if (isset($gconf['logarithmic']) && $gconf['logarithmic']) { $gOpts .= ' --logarithmic'; }
a039a75c 685 if (isset($gconf['min_y'])) { $gOpts .= ' --lower-limit '.$gconf['min_y']; }
686 if (isset($gconf['max_y'])) { $gOpts .= ' --upper-limit '.$gconf['max_y']; }
687 if (isset($gconf['fix_scale_y']) && $gconf['fix_scale_y']) { $gOpts .= ' --rigid'; }
688 if (isset($gconf['grid_x'])) { $gOpts .= ' --x-grid '.$gconf['grid_x']; }
689 if (isset($gconf['grid_y'])) { $gOpts .= ' --y-grid '.$gconf['grid_y']; }
d6ad10a5 690 if (isset($gconf['gridfit']) && (!$gconf['gridfit'])) { $gOpts .= ' --no-gridfit'; }
691 if (isset($gconf['calc_scale_y']) && $gconf['calc_scale_y']) { $gOpts .= ' --alt-autoscale'; }
692 if (isset($gconf['calc_max_y']) && $gconf['calc_max_y']) { $gOpts .= ' --alt-autoscale-max'; }
a039a75c 693 if (isset($gconf['units_exponent'])) { $gOpts .= ' --units-exponent '.$gconf['units_exponent']; }
694 if (isset($gconf['units_length'])) { $gOpts .= ' --units-length '.$gconf['units_length']; }
e5574259 695 if (($this->rrd_version() < '1.2') || !count($specialrows)) {
696 // lazy graphics omit all print reporting in RRDtool 1.2!
697 // --> so don't use them there when we want to print stuff
698 if (!isset($gconf['force_recreate']) || (!$gconf['force_recreate'])) { $gOpts .= ' --lazy'; }
699 }
a039a75c 700 if (isset($gconf['force_color']) && is_array($gconf['force_color'])) {
701 foreach ($gconf['force_color'] as $ctag=>$cval) { $gOpts .= ' --color '.$ctag.$cval; }
4ba56977 702 }
a039a75c 703 if (isset($gconf['force_font']) && is_array($gconf['force_font'])) {
704 foreach ($gconf['force_font'] as $ctag=>$cval) { $gOpts .= ' --font '.$ctag.$cval; }
4ba56977 705 }
a039a75c 706 if (isset($gconf['units_binary']) && $gconf['units_binary']) { $gOpts .= ' --base 1024'; }
4ba56977 707
b7878f4d 708 foreach ($graphrows as $grow) {
4ba56977 709 if (isset($grow['dType']) && strlen($grow['dType'])) {
710 $gDefs .= ' '.$grow['dType'].':'.$grow['name'].'=';
b1776944 711 if ($grow['dType'] == 'DEF') {
712 $gDefs .= isset($grow['dsfile'])?$grow['dsfile']:$this->rrd_file;
713 $gDefs .= ':'.$grow['dsname'].':'.$grow['cf'];
714 }
715 else { $gDefs .= $grow['rpn_expr']; }
4ba56977 716 }
717 if (isset($grow['gType']) && strlen($grow['gType'])) {
16cc643c 718 // XXX: change from STACK type to STACK flag once we have rrdtool 1.2
586031ce 719 if ($this->rrd_version() < '1.2') {
720 // rrdtool 1.0 only know STACK type
721 if (isset($grow['stack']) && $grow['stack']) { $grow['gType'] = 'STACK'; }
722 }
4ba56977 723 $gGraphs .= ' '.$grow['gType'].':'.$grow['name'].$grow['color'];
724 if (isset($grow['legend'])) { $gGraphs .= ':'.$this->text_quote($grow['legend']); }
586031ce 725 if ($this->rrd_version() >= '1.2') {
726 // rrdtool 1.2 and above have STACK flag
727 if (isset($grow['stack']) && $grow['stack']) { $gGraphs .= ':STACK'; }
728 }
4ba56977 729 }
b7878f4d 730 }
731
16cc643c 732 foreach ($specialrows as $srow) {
733 $addSpecial .= ' '.$srow['sType'];
586031ce 734 if ($this->rrd_version() >= '1.2') {
735 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name']:'');
736 }
737 else {
738 $addSpecial .= (($srow['sType']!='COMMENT')?':'.$srow['name'].':'.$srow['cf']:'');
739 }
16cc643c 740 $addSpecial .= ':'.$this->text_quote($srow['text']);
741 }
742
5f42eda6 743 $graph_cmd = 'rrdtool graph '.str_replace('*', '\*', $fname.$gOpts.$gDefs.$gGraphs.$addSpecial);
b7878f4d 744 $return = `$graph_cmd 2>&1`;
745
b7878f4d 746 if (strpos($return, 'ERROR') !== false) {
b61757c1 747 trigger_error($this->rrd_file.' - rrd graph error: '.$return, E_USER_WARNING);
586031ce 748 $return = 'command:'.$graph_cmd."\n\n".$return;
749 }
750 if (0) {
751 // debug output
752 $return = 'command:'.$graph_cmd."\n\n".$return;
b7878f4d 753 }
506711ee 754 $legendlines = '';
755 foreach ($graphrows as $grow) {
756 $legendline = isset($grow['desc'])?$grow['desc']:(isset($grow['legend'])?$grow['legend']:$grow['name']);
2304f1ba 757 $legendline .= '|'.@$grow['color'];
506711ee 758 $legendline .= '|'.(isset($grow['color_bg'])?$grow['color_bg']:'');
759 $legendline .= '|'.(isset($grow['legend_long'])?$grow['legend_long']:'');
760 $legendlines .= 'legend:'.$legendline."\n";
761 }
762 $return = 'file:'.$fname."\n".$legendlines.$return;
a039a75c 763 return $return;
b7878f4d 764 }
765
f5e899df 766 function graph_plus($timeframe = 'day', $sub = null, $extra = null) {
767 // create a RRD graph and return meta info as a ready-to-use array
506711ee 768 $gmeta = array('filename'=>null,'legends_long'=>false,'default_colorize'=>false);
f5e899df 769 $ret = $this->graph($timeframe, $sub, $extra);
586031ce 770 if (0) {
771 // debug output
772 $gmeta['ret'] = $ret;
773 }
f5e899df 774 $grout = explode("\n", $ret);
775 foreach ($grout as $gline) {
586031ce 776 if (preg_match('/^command:(.+)$/', $gline, $regs)) {
777 $gmeta['graph_cmd'] = $regs[1];
778 }
779 elseif (preg_match('/^file:(.+)$/', $gline, $regs)) {
f5e899df 780 $gmeta['filename'] = $regs[1];
781 }
48c82fbe 782 elseif (preg_match('/^legend:([^\|]+)\|([^|]*)\|([^\|]*)\|(.*)$/', $gline, $regs)) {
506711ee 783 $gmeta['legend'][$regs[1]] = array('color'=>$regs[2], 'color_bg'=>$regs[3], 'desc_long'=>$regs[4]);
784 if (strlen($regs[4])) { $gmeta['legends_long'] = true; }
785 if (strlen($regs[3]) || strlen($regs[4])) { $gmeta['default_colorize'] = true; }
786 }
f5e899df 787 elseif (preg_match('/^(\d+)x(\d+)$/', $gline, $regs)) {
788 $gmeta['width'] = $regs[1]; $gmeta['height'] = $regs[2];
789 }
790 elseif (preg_match('/^([^\|]+)\|([^|]+)\|([^\|]*)$/', $gline, $regs)) {
791 $gmeta['data'][$regs[1]][$regs[2]] = $regs[3];
792 }
793 elseif (preg_match('/^([^\|]+)\|([^\|]*)$/', $gline, $regs)) {
794 $gmeta['var'][$regs[1]] = $regs[2];
795 }
796 elseif (strlen(trim($gline))) {
797 $gmeta['info'][] = $gline;
798 }
799 }
800 if (is_null($gmeta['filename'])) {
801 $gmeta['filename'] = $this->basename.(!is_null($sub)?'-'.$sub:'').'-'.$timeframe.'.png';
802 }
803 return $gmeta;
804 }
805
099bd59f 806 function page($sub = null, $page_extras = null, $graph_extras = null) {
807 // create a (HTML) page and return it in a string
808
809 // assemble configuration
810 $pconf = (array)$page_extras;
811 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
812 $pconf = $pconf + $this->config_raw['page.'.$sub];
813 }
814 $pconf = $pconf + (array)$this->config_page;
815
816 $return = null;
82d064f4 817 switch (@$pconf['type']) {
099bd59f 818 case 'index':
819 $return = $this->page_index($pconf);
820 break;
821 case 'overview':
822 $return = $this->page_overview($pconf, $graph_extras);
823 break;
824 case 'simple':
825 default:
826 $return = $this->page_simple($pconf, $graph_extras);
827 break;
828 }
829 return $return;
830 }
831
2c30ff69 832 function simple_html($sub = null, $page_extras = null, $graph_extras = null) {
b7878f4d 833 // create a simple (MRTG-like) HTML page and return it in a string
099bd59f 834 // XXX: this is here temporarily for compat only, it's preferred to use page()!
a039a75c 835
836 // assemble configuration
e1727e7f 837 $pconf = (array)$page_extras;
2c30ff69 838 if (!is_null($sub) && is_array($this->config_raw['page.'.$sub])) {
e1727e7f 839 $pconf = $pconf + $this->config_raw['page.'.$sub];
a039a75c 840 }
e1727e7f 841 $pconf = $pconf + (array)$this->config_page;
a039a75c 842
099bd59f 843 return $this->page_simple($pconf, $graph_extras);
844 }
845
846 function page_index($pconf) {
847 // create a bare, very simple index list HTML page and return it in a string
724f6e78 848 $td = $this->mod_textdomain;
849 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:dgettext($td, 'RRD statistics index');
099bd59f 850
586031ce 851 $out = '<html><head>'."\n";
852 $out .= '<title>'.$ptitle.'</title>'."\n";
853 $out .= '<style type="text/css">'."\n";
099bd59f 854 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
855 else {
586031ce 856 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
857 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
858 $out .= 'li.scanfile { font-style: italic; }'."\n";
099bd59f 859 }
860 if (isset($pconf['style'])) { $out .= $pconf['style']; }
586031ce 861 $out .= '</style>'."\n";
862 $out .= '</head>'."\n";
863 $out .= '<body>'."\n";
099bd59f 864
586031ce 865 $out .= '<h1>'.$ptitle.'</h1>'."\n";
f5e899df 866 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) {
586031ce 867 $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'."\n";
099bd59f 868 }
f5e899df 869 elseif (!isset($pconf['text_intro'])) {
586031ce 870 $out .= '<p class="intro">'.dgettext($td, 'The following RRD stats are available:').'</p>'."\n";
099bd59f 871 }
f5e899df 872
873 $stats = $this->h_page_statsArray($pconf);
874
82d064f4 875 if (isset($pconf['stats_url'])) { $sURL_base = $pconf['stats_url']; }
876 else { $sURL_base = '?stat=%i%a'; }
877
878 if (isset($pconf['stats_url_add'])) { $sURL_add = $pconf['stats_url_add']; }
879 else { $sURL_add = '&sub=%s'; }
880
586031ce 881 $out .= '<ul class="indexlist">'."\n";
099bd59f 882 foreach ($stats as $stat) {
883 $out .= '<li'.(isset($stat['class'])?' class="'.$stat['class'].'"':'').'>';
82d064f4 884 $sURL = str_replace('%i', $stat['name'], $sURL_base);
885 $sURL = str_replace('%a', '', $sURL);
886 $sURL = str_replace('%s', '', $sURL);
887 $out .= '<a href="'.$sURL.'">'.$stat['name'].'</a>';
099bd59f 888 if (isset($stat['sub']) && count($stat['sub'])) {
889 $sprt = array();
82d064f4 890 foreach ($stat['sub'] as $ssub) {
891 $sURL = str_replace('%i', $stat['name'], $sURL_base);
892 $sURL = str_replace('%a', $sURL_add, $sURL);
893 $sURL = str_replace('%s', $ssub, $sURL);
894 $sprt[] = '<a href="'.$sURL.'">'.$ssub.'</a>';
895 }
099bd59f 896 $out .= ' <span="subs">('.implode(', ', $sprt).')</span>';
897 }
586031ce 898 $out .= '</li>'."\n";
099bd59f 899 }
586031ce 900 $out .= '</ul>'."\n";
099bd59f 901
f5e899df 902 $out .= $this->h_page_footer();
586031ce 903 $out .= '</body></html>'."\n";
099bd59f 904 return $out;
905 }
906
907 function page_overview($pconf, $graph_extras = null) {
908 // create an overview HTML page (including graphs) and return it in a string
724f6e78 909 $td = $this->mod_textdomain;
910 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:dgettext($td, 'RRD statistics overview');
f5e899df 911
586031ce 912 $out = '<html><head>'."\n";
913 $out .= '<title>'.$ptitle.'</title>'."\n";
914 $out .= '<style type="text/css">'."\n";
f5e899df 915 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
916 else {
586031ce 917 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
918 $out .= 'h2 { font-weight: bold; font-size: 1em; margin: 0.5em 0; }'."\n";
919 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
920 $out .= 'img.rrdgraph { border: none; }'."\n";
f5e899df 921 }
922 if (isset($pconf['style'])) { $out .= $pconf['style']; }
586031ce 923 $out .= '</style>'."\n";
924 $out .= '</head>'."\n";
925 $out .= '<body>'."\n";
f5e899df 926
586031ce 927 $out .= '<h1>'.$ptitle.'</h1>'."\n";
d6ad10a5 928 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'; }
f5e899df 929
930 $stats = $this->h_page_statsArray($pconf);
931
ecc732d5 932 if (isset($pconf['stats_url'])) { $sURL_base = $pconf['stats_url']; }
933 else { $sURL_base = '?stat=%i%a'; }
934
935 if (isset($pconf['stats_url_add'])) { $sURL_add = $pconf['stats_url_add']; }
936 else { $sURL_add = '&sub=%s'; }
937
f5e899df 938 $num_rows = is_numeric($pconf['num_rows'])?$pconf['num_rows']:2;
939 $num_cols = ceil(count($stats)/$num_rows);
940
586031ce 941 $out .= '<table class="overview">'."\n";
f5e899df 942 for ($col = 0; $col < $num_cols; $col++) {
586031ce 943 $out .= '<tr>'."\n";
f5e899df 944 for ($row = 0; $row < $num_rows; $row++) {
945 $idx = $col * $num_rows + $row;
586031ce 946 $out .= '<td>'."\n";
f5e899df 947 if ($idx < count($stats)) {
2304f1ba 948 @list($sname, $s_psub) = explode('|', $stats[$idx]['name'], 2);
f5e899df 949 $s_psname = 'page'.(isset($s_psub)?'.'.$s_psub:'');
2304f1ba 950 $g_sub = @$this->config_all[$sname][$s_psname]['graph_sub'];
f5e899df 951
952 if (isset($this->config_all[$sname][$s_psname]['title_page'])) {
953 $s_ptitle = $this->config_all[$sname][$s_psname]['title_page'];
954 }
955 elseif (isset($this->config_all[$sname]['page']['title_page'])) {
956 $s_ptitle = $this->config_all[$sname]['page']['title_page'];
957 }
958 else {
e2da2e9f 959 $s_ptitle = isset($s_psub)?sprintf(dgettext($td, '%s (%s) statistics'), $sname, $s_psub):sprintf(dgettext($td, '%s statistics'), $sname);
f5e899df 960 }
961 if (!isset($pconf['hide_titles']) || !$pconf['hide_titles']) {
586031ce 962 $out .= '<h2>'.$s_ptitle.'</h2>'."\n";
f5e899df 963 }
964
965 $s_rrd = new rrdstat($this->config_all, $sname);
966 if (in_array($s_rrd->status, array('ok','readonly','graphonly'))) {
967 $tframe = isset($pconf['graph_timeframe'])?$pconf['graph_timeframe']:'day';
968 $gmeta = $s_rrd->graph_plus($tframe, $g_sub);
969 if (isset($pconf['graph_url'])) {
970 $gURL = $pconf['graph_url'];
ecc732d5 971 $gURL = str_replace('%f', basename($gmeta['filename']), $gURL);
972 $gURL = str_replace('%p', $gmeta['filename'], $gURL);
f5e899df 973 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
974 }
975 else {
976 $gURL = $gmeta['filename'];
977 }
ecc732d5 978 $sURL = str_replace('%i', $sname, $sURL_base);
979 $sURL = str_replace('%a', isset($s_psub)?$sURL_add:'', $sURL);
506711ee 980 $sURL = str_replace('%s', isset($s_psub)?$s_psub:'', $sURL);
ecc732d5 981 $out .= '<a href="'.$sURL.'">';
f5e899df 982 $out .= '<img src="'.$gURL.'"';
983 $out .= ' alt="'.$s_rrd->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
ecc732d5 984 if (isset($gmeta['width']) && isset($gmeta['height'])) { $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;"'; }
586031ce 985 $out .= '></a>'."\n";
f5e899df 986 }
987 else {
586031ce 988 $out .= sprintf(dgettext($td, 'RRD error: status is "%s"'), $s_rrd->status)."\n";
f5e899df 989 }
990 }
991 else {
992 $out .= '&nbsp;';
993 }
586031ce 994 $out .= '</td>'."\n";
f5e899df 995 }
586031ce 996 $out .= '</tr>'."\n";
f5e899df 997 }
586031ce 998 $out .= '</table>'."\n";
f5e899df 999
1000 $out .= $this->h_page_footer();
586031ce 1001 $out .= '</body></html>'."\n";
f5e899df 1002 return $out;
099bd59f 1003 }
1004
1005 function page_simple($pconf, $graph_extras = null) {
1006 // create a simple (MRTG-like) HTML page and return it in a string
724f6e78 1007 $td = $this->mod_textdomain;
099bd59f 1008
724f6e78 1009 $ptitle = isset($pconf['title_page'])?$pconf['title_page']:sprintf(dgettext($td, '%s - RRD statistics'),$this->basename);
16cc643c 1010 $gtitle = array();
724f6e78 1011 $gtitle['day'] = isset($pconf['title_day'])?$pconf['title_day']:dgettext($td, 'Day overview (scaling 5 minutes)');
1012 $gtitle['week'] = isset($pconf['title_week'])?$pconf['title_week']:dgettext($td, 'Week overview (scaling 30 minutes)');
1013 $gtitle['month'] = isset($pconf['title_month'])?$pconf['title_month']:dgettext($td, 'Month overview (scaling 2 hours)');
1014 $gtitle['year'] = isset($pconf['title_year'])?$pconf['title_year']:dgettext($td, 'Year overview (scaling 1 day)');
506711ee 1015 $ltitle = isset($pconf['title_legend'])?$pconf['title_legend']:dgettext($td, 'Legend:');
b7878f4d 1016
586031ce 1017 $out = '<html><head>'."\n";
1018 $out .= '<title>'.$ptitle.'</title>'."\n";
1019 $out .= '<style type="text/css">'."\n";
16cc643c 1020 if (isset($pconf['style_base'])) { $out .= $pconf['style_base']; }
1021 else {
586031ce 1022 $out .= 'h1 { font-weight: bold; font-size: 1.5em; }'."\n";
1023 $out .= 'h2 { font-weight: bold; font-size: 1em; }'."\n";
1024 $out .= '.gdata, .gvar, .ginfo { font-size: 0.75em; margin: 0.5em 0; }'."\n";
1025 $out .= 'table.gdata, table.legend { border: 1px solid gray; border-collapse: collapse; }'."\n";
1026 $out .= 'table.gdata td, table.gdata th, '."\n";
1027 $out .= 'table.legend td, table.legend th { border: 1px solid gray; padding: 0.1em 0.2em; }'."\n";
1028 $out .= 'div.legend { font-size: 0.75em; margin: 0.5em 0; }'."\n";
1029 $out .= 'div.legend p { margin: 0; }'."\n";
1030 $out .= '.footer { font-size: 0.75em; margin: 0.5em 0; }'."\n";
16cc643c 1031 }
1032 if (isset($pconf['style'])) { $out .= $pconf['style']; }
586031ce 1033 $out .= '</style>'."\n";
1034 $out .= '</head>'."\n";
1035 $out .= '<body>'."\n";
16cc643c 1036
586031ce 1037 $out .= '<h1>'.$ptitle.'</h1>'."\n";
1038 if (isset($pconf['text_intro']) && strlen($pconf['text_intro'])) { $out .= '<p class="intro">'.$pconf['text_intro'].'</p>'."\n"; }
2c30ff69 1039 if (!isset($pconf['show_update']) || $pconf['show_update']) {
724f6e78 1040 $out .= '<p class="last_up">';
1041 if (is_null($this->last_update())) { $up_time = dgettext($td, 'unknown'); }
1042 elseif (class_exists('baseutils')) { $up_time = baseutils::dateFormat($this->last_update(), 'short'); }
1043 else { $up_time = date('Y-m-d H:i:s', $this->last_update()); }
1044 $out .= sprintf(dgettext($td, 'Last Update: %s'), $up_time);
586031ce 1045 $out .= '</p>'."\n";
2c30ff69 1046 }
4ba56977 1047
f5e899df 1048 $g_sub = isset($pconf['graph_sub'])?$pconf['graph_sub']:null;
b1776944 1049 if (in_array($this->status, array('ok','readonly','graphonly'))) {
b7878f4d 1050 foreach (array('day','week','month','year') as $tframe) {
f5e899df 1051 $gmeta = $this->graph_plus($tframe, $g_sub, $graph_extras);
253ead9f 1052 if (isset($pconf['graph_url'])) {
1053 $gURL = $pconf['graph_url'];
82d064f4 1054 $gURL = str_replace('%f', basename($gmeta['filename']), $gURL);
1055 $gURL = str_replace('%p', $gmeta['filename'], $gURL);
f5e899df 1056 if (substr($gURL, -1) == '/') { $gURL .= $gmeta['filename']; }
253ead9f 1057 }
1058 else {
f5e899df 1059 $gURL = $gmeta['filename'];
253ead9f 1060 }
586031ce 1061 $out .= '<div class="'.$tframe.'">'."\n";
1062 if (0) {
1063 // debug output
1064 ob_start();
1065 print_r($gmeta);
1066 $buffer = ob_get_contents();
1067 ob_end_clean();
1068 $out .= '<p>'.nl2br($buffer).'</p>';
1069 }
1070 $out .= '<h2>'.$gtitle[$tframe].'</h2>'."\n";
253ead9f 1071 $out .= '<img src="'.$gURL.'"';
31df2e13 1072 $out .= ' alt="'.$this->basename.(!is_null($g_sub)?' - '.$g_sub:'').' - '.$tframe.'" class="rrdgraph"';
82d064f4 1073 if (isset($gmeta['width']) && isset($gmeta['height'])) { $out .= ' style="width:'.$gmeta['width'].'px;height:'.$gmeta['height'].'px;"'; }
586031ce 1074 $out .= '>'."\n";
506711ee 1075 $colorize_data = (isset($pconf['data_colorize']) && $pconf['data_colorize']) || (!isset($pconf['data_colorize']) && $gmeta['default_colorize']);
16cc643c 1076 if (isset($gmeta['data']) && count($gmeta['data'])) {
586031ce 1077 $out .= '<table class="gdata">'."\n";
16cc643c 1078 foreach ($gmeta['data'] as $field=>$gdata) {
506711ee 1079 $out .= '<tr><th';
1080 if ($colorize_data && isset($gmeta['legend'][$field])) {
1081 $out .= ' style="color:'.$gmeta['legend'][$field]['color'].';';
1082 if (strlen($gmeta['legend'][$field]['color_bg'])) {
1083 $out .= 'background-color:'.$gmeta['legend'][$field]['color_bg'].';';
1084 }
1085 $out .= '"';
1086 }
1087 $out .= '>'.$field.'</th>';
16cc643c 1088 foreach ($gdata as $gkey=>$gval) {
1089 $out .= '<td><span class="gkey">'.$gkey.': </span>'.$gval.'</td>';
1090 }
586031ce 1091 $out .= '</tr>'."\n";
16cc643c 1092 }
586031ce 1093 $out .= '</table>'."\n";
16cc643c 1094 }
1095 if (isset($gmeta['var']) && count($gmeta['var'])) {
1096 foreach ($gmeta['var'] as $gkey=>$gval) {
586031ce 1097 $out .= '<p class="gvar"><span class="gkey">'.$gkey.': </span>'.$gval.'</p>'."\n";
16cc643c 1098 }
1099 }
1100 if (isset($gmeta['info']) && count($gmeta['info'])) {
1101 foreach ($gmeta['info'] as $gval) {
586031ce 1102 $out .= '<p class="ginfo">'.$gval.'</p>'."\n";
16cc643c 1103 }
1104 }
586031ce 1105 $out .= '</div>'."\n";
b7878f4d 1106 }
506711ee 1107 if ($gmeta['legends_long'] && (!isset($pconf['show_legend']) || $pconf['show_legend'])) {
586031ce 1108 $out .= '<div class="legend">'."\n";
1109 $out .= '<p>'.$ltitle.'</p>'."\n";
1110 $out .= '<table class="legend">'."\n";
506711ee 1111 foreach ($gmeta['legend'] as $field=>$legend) {
d6ad10a5 1112 if (strlen($legend['desc_long'])) {
1113 $out .= '<tr><th';
1114 if ($colorize_data && isset($gmeta['legend'][$field])) {
1115 $out .= ' style="color:'.$gmeta['legend'][$field]['color'].';';
1116 if (strlen($gmeta['legend'][$field]['color_bg'])) {
1117 $out .= 'background-color:'.$gmeta['legend'][$field]['color_bg'].';';
1118 }
1119 $out .= '"';
506711ee 1120 }
d6ad10a5 1121 $out .= '>'.$field.'</th>';
1122 $out .= '<td>'.$legend['desc_long'].'</td>';
586031ce 1123 $out .= '</tr>'."\n";
506711ee 1124 }
506711ee 1125 }
586031ce 1126 $out .= '</table>'."\n";
1127 $out .= '</div>'."\n";
506711ee 1128 }
b7878f4d 1129 }
1130 else {
586031ce 1131 $out .= sprintf(dgettext($td, 'RRD error: status is "%s"'), $this->status)."\n";
b7878f4d 1132 }
c5db3bd5 1133
f5e899df 1134 $out .= $this->h_page_footer();
586031ce 1135 $out .= '</body></html>'."\n";
b7878f4d 1136 return $out;
1137 }
1138
f5e899df 1139 function h_page_statsArray($pconf) {
1140 // return array of stats to list on a page
1141 $stats = array();
1142 $snames = array(); $s_exclude = array(); $sfiles = array();
1143 if (isset($pconf['index_ids'])) {
1144 foreach (explode(',', $pconf['index_ids']) as $iid) {
1145 if ($iid{0} == '-') { $s_exclude[] = substr($iid, 1); }
1146 else { $snames[] = $iid; }
1147 }
4ba56977 1148 }
f5e899df 1149 if (!isset($pconf['scan_config']) || $pconf['scan_config']) {
1150 foreach ($this->config_all as $iname=>$rinfo) {
1151 if (($iname != '*') && !(isset($rinfo['hidden']) && $rinfo['hidden']) &&
1152 !(in_array($iname, $snames)) && !(in_array($iname, $s_exclude))) {
1153 $snames[] = $iname;
1154 }
1155 }
1156 }
1157 foreach ($snames as $iname) {
1158 $newstat = array('name'=>$iname);
1159 $sfiles[] = isset($this->config_all[$iname]['file'])?$this->config_all[$iname]['file']:$iname.'.rrd';
1160 if (is_array($this->config_all[$iname])) {
1161 foreach ($this->config_all[$iname] as $key=>$val) {
1162 if (substr($key, 0, 5) == 'page.') { $newstat['sub'][] = substr($key, 5); }
1163 }
1164 }
1165 $stats[] = $newstat;
1166 }
1167 if (isset($pconf['scan_files']) && $pconf['scan_files']) {
1168 $rrdfiles = glob('*.rrd');
1169 foreach ($rrdfiles as $rrdfile) {
1170 $iname = (substr($rrdfile, -4) == '.rrd')?substr($rrdfile, 0, -4):$rrdfile;
1171 if (!in_array($rrdfile, $sfiles) && !(in_array($iname, $s_exclude))) {
1172 $stats[] = array('name'=>$iname, 'class'=>'scanfile');
1173 }
1174 }
1175 }
1176 return $stats;
1177 }
1178
1179 function h_page_footer() {
1180 // return generic page footer
1181 $out = '<p class="footer">';
724f6e78 1182 $out .= sprintf(dgettext($this->mod_textdomain, 'Statistics created with %s using a library created by %s.'),
1183 '<a href="http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/">RRDtool</a>',
1184 '<a href="http://www.kairo.at/">KaiRo.at</a>');
586031ce 1185 $out .= '</p>'."\n";
f5e899df 1186 return $out;
4ba56977 1187 }
1188
b7878f4d 1189 function text_quote($text) { return '"'.str_replace('"', '\"', str_replace(':', '\:', $text)).'"'; }
1190}
1191?>