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