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