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